From ab1b09d14fcc594fb3c2fa9e9b523f538de7d223 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 02:51:15 +0100 Subject: [PATCH 001/135] feat: add spark via breez sdk --- .github/workflows/release-internal.yml | 2 + .github/workflows/release.yml | 10 + app/build.gradle.kts | 3 + .../main/java/to/bitkit/data/SettingsStore.kt | 2 + .../commands/NotifyPaymentReceivedHandler.kt | 7 + app/src/main/java/to/bitkit/env/Env.kt | 14 + .../java/to/bitkit/models/BackupCategory.kt | 4 + .../java/to/bitkit/models/BackupPayloads.kt | 12 + .../java/to/bitkit/repositories/BackupRepo.kt | 38 + .../to/bitkit/repositories/LightningRepo.kt | 112 ++- .../repositories/PaykitAllowanceExecutor.kt | 30 +- .../repositories/PaykitAllowanceRepo.kt | 13 +- .../repositories/PaykitPaymentProofRepo.kt | 61 +- .../bitkit/repositories/PrivatePaykitRepo.kt | 5 +- .../java/to/bitkit/repositories/SparkRepo.kt | 874 ++++++++++++++++++ .../java/to/bitkit/repositories/WalletRepo.kt | 20 +- .../to/bitkit/services/LightningService.kt | 15 + .../to/bitkit/services/MigrationService.kt | 4 + .../java/to/bitkit/services/SparkService.kt | 266 ++++++ app/src/main/java/to/bitkit/ui/ContentView.kt | 237 ++++- .../java/to/bitkit/ui/components/FeeInfo.kt | 7 +- .../bitkit/ui/components/LightningChannel.kt | 40 +- .../ui/screens/transfer/FundingScreen.kt | 139 ++- .../screens/transfer/SavingsAdvancedScreen.kt | 43 +- .../screens/transfer/SavingsConfirmScreen.kt | 254 +++-- .../screens/transfer/SavingsProgressScreen.kt | 46 +- .../ui/screens/transfer/SettingUpScreen.kt | 269 ++++++ .../screens/transfer/SparkFundingViewModel.kt | 454 +++++++++ .../screens/transfer/SpendingAmountScreen.kt | 327 +++++++ .../screens/transfer/SpendingConfirmScreen.kt | 367 ++++++++ .../screens/transfer/SpendingIntroScreen.kt | 80 ++ .../screens/transfer/TransferIntroScreen.kt | 85 ++ .../transfer/TransferLearnMoreScreen.kt | 112 +++ .../transfer/hardware/SpendingHwSignScreen.kt | 270 ++++++ .../hardware/SpendingHwSignedScreen.kt | 111 +++ .../bitkit/ui/screens/wallets/HomeScreen.kt | 10 +- .../screens/wallets/SpendingWalletScreen.kt | 5 +- .../screens/wallets/receive/EditInvoiceVM.kt | 6 + .../wallets/receive/ReceiveQrScreen.kt | 4 +- .../screens/wallets/receive/ReceiveSheet.kt | 2 + .../screens/wallets/send/HwSendViewModel.kt | 4 +- .../settings/lightning/ChannelDetailScreen.kt | 4 +- .../lightning/LightningConnectionsScreen.kt | 144 ++- .../LightningConnectionsViewModel.kt | 51 +- .../settings/lightning/SparkDetailScreen.kt | 209 +++++ .../lightning/SparkDetailViewModel.kt | 64 ++ .../usecases/DeriveBalanceStateUseCase.kt | 15 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 63 +- .../to/bitkit/viewmodels/BackupsViewModel.kt | 7 +- .../to/bitkit/viewmodels/SettingsViewModel.kt | 18 + .../to/bitkit/viewmodels/TransferViewModel.kt | 123 ++- .../to/bitkit/viewmodels/WalletViewModel.kt | 3 + app/src/main/res/values-ar/strings.xml | 56 ++ app/src/main/res/values-b+es+419/strings.xml | 56 ++ app/src/main/res/values-ca/strings.xml | 56 ++ app/src/main/res/values-cs/strings.xml | 56 ++ app/src/main/res/values-de/strings.xml | 56 ++ app/src/main/res/values-el/strings.xml | 56 ++ app/src/main/res/values-es-rES/strings.xml | 56 ++ app/src/main/res/values-es/strings.xml | 56 ++ app/src/main/res/values-fr/strings.xml | 56 ++ app/src/main/res/values-it/strings.xml | 56 ++ app/src/main/res/values-nl/strings.xml | 56 ++ app/src/main/res/values-pl/strings.xml | 56 ++ app/src/main/res/values-pt-rBR/strings.xml | 56 ++ app/src/main/res/values-pt/strings.xml | 56 ++ app/src/main/res/values-ru/strings.xml | 56 ++ app/src/main/res/values/strings.xml | 57 ++ .../NotifyPaymentReceivedHandlerTest.kt | 19 + .../to/bitkit/repositories/BackupRepoTest.kt | 57 ++ .../bitkit/repositories/LightningRepoTest.kt | 54 ++ .../repositories/PaykitAllowancePayerTest.kt | 37 + .../repositories/PaykitAllowanceRepoTest.kt | 14 + .../PaykitPaymentProofRepoTest.kt | 55 ++ .../PrivatePaykitAllowancePaymentTest.kt | 4 + .../repositories/PrivatePaykitRepoTest.kt | 27 + .../repositories/SparkClaimOfferTest.kt | 95 ++ .../to/bitkit/repositories/SparkRepoTest.kt | 572 ++++++++++++ .../to/bitkit/repositories/WalletRepoTest.kt | 3 + .../to/bitkit/services/SparkServiceTest.kt | 73 ++ .../test/java/to/bitkit/test/IdleSparkRepo.kt | 14 + .../test/java/to/bitkit/ui/ContentViewTest.kt | 32 + .../java/to/bitkit/ui/WalletViewModelTest.kt | 8 + .../transfer/SparkFundingViewModelTest.kt | 240 +++++ .../wallets/receive/EditInvoiceVMTest.kt | 19 + .../LightningConnectionsViewModelTest.kt | 5 + .../usecases/DeriveBalanceStateUseCaseTest.kt | 21 + .../viewmodels/AppViewModelSendFlowTest.kt | 92 +- .../viewmodels/TransferViewModelTest.kt | 215 ++++- changelog.d/next/1697.added.md | 1 + docs/screens-map.md | 9 + gradle/libs.versions.toml | 1 + journeys/README.md | 3 + journeys/amount-limits/README.md | 11 +- .../transfer-spending-over-max.xml | 24 + .../transfer-spending-preset-delete.xml | 46 + journeys/hardware-wallet/README.md | 3 + .../passphrase-transfer-to-spending.xml | 74 ++ .../transfer-to-spending-node-warmup.xml | 37 + .../hardware-wallet/transfer-to-spending.xml | 59 ++ journeys/transfer/savings-select-funds.xml | 30 + .../transfer/spark-transfer-to-spending.xml | 29 + .../spending-confirm-amount-change.xml | 33 + .../transfer/transfer-unavailable-sheet.xml | 4 +- scripts/spark-regtest-esplora.py | 100 ++ scripts/spark-regtest-fund.py | 50 + settings.gradle.kts | 4 + 107 files changed, 7860 insertions(+), 276 deletions(-) create mode 100644 app/src/main/java/to/bitkit/repositories/SparkRepo.kt create mode 100644 app/src/main/java/to/bitkit/services/SparkService.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/SpendingIntroScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/TransferIntroScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/TransferLearnMoreScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignedScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkClaimOfferTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt create mode 100644 app/src/test/java/to/bitkit/services/SparkServiceTest.kt create mode 100644 app/src/test/java/to/bitkit/test/IdleSparkRepo.kt create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt create mode 100644 changelog.d/next/1697.added.md create mode 100644 journeys/amount-limits/transfer-spending-over-max.xml create mode 100644 journeys/amount-limits/transfer-spending-preset-delete.xml create mode 100644 journeys/hardware-wallet/passphrase-transfer-to-spending.xml create mode 100644 journeys/hardware-wallet/transfer-to-spending-node-warmup.xml create mode 100644 journeys/hardware-wallet/transfer-to-spending.xml create mode 100644 journeys/transfer/savings-select-funds.xml create mode 100644 journeys/transfer/spark-transfer-to-spending.xml create mode 100644 journeys/transfer/spending-confirm-amount-change.xml create mode 100755 scripts/spark-regtest-esplora.py create mode 100755 scripts/spark-regtest-fund.py diff --git a/.github/workflows/release-internal.yml b/.github/workflows/release-internal.yml index 8099065f11..1a042d86ca 100644 --- a/.github/workflows/release-internal.yml +++ b/.github/workflows/release-internal.yml @@ -73,6 +73,8 @@ jobs: KEYSTORE_PASSWORD: ${{ secrets.INTERNAL_KEYSTORE_PASSWORD }} KEY_ALIAS: ${{ secrets.INTERNAL_KEY_ALIAS }} KEY_PASSWORD: ${{ secrets.INTERNAL_KEY_PASSWORD }} + # Optional: without it the build passes and Spark (Lightning without channels) stays off. + BREEZ_API_KEY: ${{ secrets.BREEZ_API_KEY }} run: | set -euo pipefail ./gradlew assembleMainnetRelease --no-daemon --stacktrace diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index edcca33abc..a957db809d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -66,6 +66,15 @@ jobs: printf '%s' "$BITKIT_KEYSTORE_BASE64" | base64 --decode > "$keystore_path" echo "KEYSTORE_FILE=$keystore_path" >> "$GITHUB_ENV" + - name: Check Breez API key + env: + BREEZ_API_KEY: ${{ secrets.BREEZ_API_KEY }} + run: | + if [ -z "${BREEZ_API_KEY// /}" ]; then + echo "::error::BREEZ_API_KEY is missing from the release environment; a release without it ships with Spark (Lightning without channels) off." + exit 1 + fi + - name: Build release artifacts env: GPR_USER: ${{ secrets.GPR_USER || github.actor }} @@ -74,6 +83,7 @@ jobs: KEYSTORE_PASSWORD: ${{ secrets.BITKIT_KEYSTORE_PASSWORD }} KEY_ALIAS: ${{ secrets.BITKIT_KEY_ALIAS }} KEY_PASSWORD: ${{ secrets.BITKIT_KEY_PASSWORD }} + BREEZ_API_KEY: ${{ secrets.BREEZ_API_KEY }} run: | set -euo pipefail ./gradlew assembleMainnetRelease bundleMainnetRelease --no-daemon --stacktrace diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6198983ef9..04873d1fbc 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -356,6 +356,8 @@ androidComponents { "USDT_RPC_URL", localProp("USDT_RPC_URL").orElse("https://bitkit.to/v1/usdt/chain-rpc").stringField(), ) + buildConfigFields.put("BREEZ_API_KEY", localProp("BREEZ_API_KEY").orElse("").stringField()) + buildConfigFields.put("ESPLORA_URL", localProp("ESPLORA_URL").orElse("").stringField()) buildConfigFields.put("E2E", e2eEnv.booleanField()) buildConfigFields.put("E2E_BACKEND", e2eBackendEnv.stringField()) buildConfigFields.put("E2E_LOCAL_HOST", e2eLocalHostEnv.stringField()) @@ -566,6 +568,7 @@ dependencies { implementation(libs.bitkit.core) } implementation(libs.paykit) + implementation(libs.breez.sdk.spark) { exclude(group = "net.java.dev.jna", module = "jna") } implementation(libs.vss.client) if (localBitkitCoreAar == null) nativeDebugSymbols(libs.bitkit.core.nativeDebugSymbolsArtifact()) nativeDebugSymbols(libs.ldk.node.android.nativeDebugSymbolsArtifact()) diff --git a/app/src/main/java/to/bitkit/data/SettingsStore.kt b/app/src/main/java/to/bitkit/data/SettingsStore.kt index 5a1c735fdc..e5085ff311 100644 --- a/app/src/main/java/to/bitkit/data/SettingsStore.kt +++ b/app/src/main/java/to/bitkit/data/SettingsStore.kt @@ -212,7 +212,9 @@ data class SettingsData( val selectedCurrency: String = "USD", val defaultTransactionSpeed: TransactionSpeed = TransactionSpeed.default(), val showEmptyBalanceView: Boolean = true, + val hasSeenSpendingIntro: Boolean = false, val hasSeenWidgetsIntro: Boolean = false, + val hasSeenTransferIntro: Boolean = false, val hasSeenSavingsIntro: Boolean = false, val hasSeenShopIntro: Boolean = false, val hasSeenProfileIntro: Boolean = false, diff --git a/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt b/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt index b00865ba75..b016c232e3 100644 --- a/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt +++ b/app/src/main/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandler.kt @@ -15,6 +15,7 @@ import to.bitkit.models.NewTransactionSheetType import to.bitkit.models.msatCeilOf import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo +import to.bitkit.repositories.SparkRepo import to.bitkit.services.MigrationService import to.bitkit.utils.Logger import javax.inject.Inject @@ -35,6 +36,7 @@ class NotifyPaymentReceivedHandler @Inject constructor( private val settingsStore: SettingsStore, private val clock: Clock, private val receivedNotificationContent: ReceivedNotificationContent, + private val sparkRepo: SparkRepo, ) { private val presentationClaimsLock = Any() private val presentationClaims = mutableSetOf() @@ -124,6 +126,11 @@ class NotifyPaymentReceivedHandler @Inject constructor( if (command.details.amountSats <= 0) return false } + if (sparkRepo.markWithdrawalAsTransfer(command.txid)) { + Logger.debug("Skipping onchain receive '${command.txid}' from a Spark withdrawal", context = TAG) + return false + } + if (settings.pendingRestoreActivitySeen) { Logger.debug("Skipping onchain receive '${command.txid}' until the first sync after restore", context = TAG) return false diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 83a1ed564f..09b2fd0dab 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -31,6 +31,14 @@ internal object Env { ).filter { it.first in enabled }.map { it.second } } + val breezApiKey: String? get() = BuildConfig.BREEZ_API_KEY.takeIf { it.isNotBlank() } + + /** + * Esplora endpoint for the node's chain source on regtest builds, set to put the wallet on Spark's regtest chain + * through `scripts/spark-regtest-esplora.py`; Electrum is used when unset. + */ + val regtestEsploraUrl: String? + get() = BuildConfig.ESPLORA_URL.takeIf { it.isNotBlank() && network == Network.REGTEST } val isDebug = BuildConfig.DEBUG const val isE2eTest = BuildConfig.E2E val e2eBackend = BuildConfig.E2E_BACKEND.lowercase() @@ -226,6 +234,12 @@ internal object Env { fun ldkStoragePath(walletIndex: Int) = storagePathOf(walletIndex, network.name.lowercase(), "ldk") + fun sparkStoragePath(walletIndex: Int) = storagePathOf(walletIndex, network.name.lowercase(), "spark") + + /** A restored Spark exit data backup waiting to be imported once Spark connects; outside Spark's storage. */ + fun sparkExitRestorePath(walletIndex: Int) = + Path(storagePathOf(walletIndex, network.name.lowercase(), "spark-restore"), "exit-state.json").toString() + fun bitkitCoreStoragePath(walletIndex: Int): String { return storagePathOf(walletIndex, network.name.lowercase(), "core") } diff --git a/app/src/main/java/to/bitkit/models/BackupCategory.kt b/app/src/main/java/to/bitkit/models/BackupCategory.kt index d71ad17e1d..484bb3a05d 100644 --- a/app/src/main/java/to/bitkit/models/BackupCategory.kt +++ b/app/src/main/java/to/bitkit/models/BackupCategory.kt @@ -42,6 +42,10 @@ enum class BackupCategory( icon = R.drawable.ic_tag, title = R.string.settings__backup__category_tags, ), + SPARK_EXIT( + icon = R.drawable.ic_lightning, + title = R.string.settings__backup__category_spark_exit, + ), // Descoped in v1, will return in v2: // PROFILE( // icon = R.drawable.ic_user, diff --git a/app/src/main/java/to/bitkit/models/BackupPayloads.kt b/app/src/main/java/to/bitkit/models/BackupPayloads.kt index 4a099eac1f..f3e05e639b 100644 --- a/app/src/main/java/to/bitkit/models/BackupPayloads.kt +++ b/app/src/main/java/to/bitkit/models/BackupPayloads.kt @@ -88,3 +88,15 @@ data class WidgetsBackupV1( val createdAt: Long, val widgets: WidgetsData, ) + +/** + * The Spark wallet's unilateral exit data, as the SDK exports it, kept so a wallet restored on another device can + * still exit on-chain while the Spark operators are unreachable. + */ +@Serializable +data class SparkExitBackupV1( + val version: Int = 1, + val createdAt: Long, + val network: String, + val exitState: String, +) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index c3dde00481..9d90f5a89f 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -19,8 +19,10 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @@ -69,6 +71,7 @@ import to.bitkit.models.MetadataBackupV1 import to.bitkit.models.PaykitAllowanceStateBackup import to.bitkit.models.PaykitPaymentStateBackup import to.bitkit.models.SettingsBackupV1 +import to.bitkit.models.SparkExitBackupV1 import to.bitkit.models.Toast import to.bitkit.models.WalletBackupV1 import to.bitkit.models.WalletScope @@ -137,6 +140,7 @@ class BackupRepo @Inject constructor( private val keychain: Keychain, private val onchainSendAttemptStore: OnchainSendAttemptStore, private val lightningRepo: Provider, + private val sparkRepo: SparkRepo, private val vssStoreIdProvider: VssStoreIdProvider, private val preActivityMetadataRepo: PreActivityMetadataRepo, private val lightningService: LightningService, @@ -435,6 +439,20 @@ class BackupRepo @Inject constructor( // payment and sync traffic does not re-upload the whole metadata envelope. dataListenerJobs.add(observeBackupChanges(activityRepo.activityTagsChanged, BackupCategory.METADATA)) + // SPARK_EXIT - back up once Spark is ready, which replays when observing starts after it connected, + // and again whenever Spark announces its unilateral exit data changed + dataListenerJobs.add( + scope.launch { + merge( + sparkRepo.state.map { it.isReady }.distinctUntilChanged().filter { it }, + sparkRepo.exitStateChanged, + ).collect { + if (shouldSkipBackup()) return@collect + markBackupRequired(BackupCategory.SPARK_EXIT) + } + } + ) + // LIGHTNING_CONNECTIONS - Only display sync timestamp, ldk-node manages its own backups @OptIn(FlowPreview::class) val lightningConnectionsJob = scope.launch { @@ -581,6 +599,7 @@ class BackupRepo @Inject constructor( val upload = when (category) { BackupCategory.WALLET -> uploadWalletBackup() BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup() + BackupCategory.SPARK_EXIT -> uploadSparkExitBackup() else -> runSuspendCatching { vssBackupClient.putObject(key = category.name, data = getBackupDataBytes(category)).getOrThrow() } @@ -619,6 +638,15 @@ class BackupRepo @Inject constructor( } } + /** Nothing to back up until Spark connects, which marks [BackupCategory.SPARK_EXIT] required again. */ + private suspend fun uploadSparkExitBackup(): Result = runSuspendCatching { + val backup = sparkRepo.exitBackup().getOrThrow() ?: return@runSuspendCatching + vssBackupClient.putObject( + key = BackupCategory.SPARK_EXIT.name, + data = json.encodeToString(backup).toByteArray(), + ).getOrThrow() + } + suspend fun persistWalletBackup(): Result = withContext(ioDispatcher) { walletBackupMutex.withLock { uploadWalletBackup() } @@ -752,6 +780,10 @@ class BackupRepo @Inject constructor( BackupCategory.LIGHTNING_CONNECTIONS -> throw NotImplementedError("LIGHTNING backup is managed by ldk-node") BackupCategory.USDT_RECOVERY -> throw UsdtException.BackupUnavailable() + BackupCategory.SPARK_EXIT -> { + val backup = checkNotNull(sparkRepo.exitBackup().getOrThrow()) { "Spark is not connected" } + json.encodeToString(backup).toByteArray() + } } private suspend fun getMetadataBackupDataBytes(): ByteArray = withContext(ioDispatcher) { @@ -955,6 +987,12 @@ class BackupRepo @Inject constructor( } // SETTINGS is optional; preserving explicit local corrections is required. connectionSession.replay() + // Before the slower categories, so the exit data is staged before Spark connects and syncs. + performRestore(BackupCategory.SPARK_EXIT) { dataBytes -> + val parsed = json.decodeFromString(String(dataBytes)) + sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow() + parsed.createdAt + } val retainedWalletBackup = keychain.loadString(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name) if (retainedWalletBackup.isNullOrEmpty()) { var didRestoreWalletBackup = false diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 46d9fc0edd..ad995b68cc 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -21,6 +21,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow @@ -49,6 +50,7 @@ import org.lightningdevkit.ldknode.ChannelDataMigration import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.ClosureReason import org.lightningdevkit.ldknode.CoinSelectionAlgorithm +import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.Network import org.lightningdevkit.ldknode.NodeStatus @@ -56,6 +58,7 @@ import org.lightningdevkit.ldknode.OutPoint import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentHash import org.lightningdevkit.ldknode.PaymentId +import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PeerDetails import org.lightningdevkit.ldknode.SpendableUtxo import org.lightningdevkit.ldknode.Txid @@ -69,6 +72,7 @@ import to.bitkit.data.keychain.requireWalletRestoreComplete import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env +import to.bitkit.ext.calculateRemoteBalance import to.bitkit.ext.getSatsPerVByteFor import to.bitkit.ext.nowMillis import to.bitkit.ext.runSuspendCatching @@ -80,6 +84,7 @@ import to.bitkit.models.ElectrumServer import to.bitkit.models.NATIVE_WITNESS_TYPES import to.bitkit.models.NodeLifecycleState import to.bitkit.models.OpenChannelResult +import to.bitkit.models.ReceiveLiquidityDecision import to.bitkit.models.TransactionSpeed import to.bitkit.models.WalletScope import to.bitkit.models.safe @@ -130,6 +135,7 @@ class LightningRepo @Inject constructor( private val vssBackupClientLdk: VssBackupClientLdk, private val urlValidator: UrlValidator, private val electrumProbeService: ElectrumProbeService, + private val sparkRepo: SparkRepo, ) : OnchainReleasing { private val _lightningState = MutableStateFlow(LightningState()) val lightningState = _lightningState.asStateFlow() @@ -138,6 +144,12 @@ class LightningRepo @Inject constructor( val nodeEventUpdates = _nodeEventUpdates.asSharedFlow() val nodeEvents = nodeEventUpdates.map { it.event } + /** Whether Spark is connected and can send and receive Lightning payments. */ + val isSparkReady: Flow get() = sparkRepo.state.map { it.isReady }.distinctUntilChanged() + + /** Whether Spark synced its payments since it connected, so its payment list is complete. */ + val isSparkSynced: Flow get() = sparkRepo.state.map { it.hasSynced }.distinctUntilChanged() + private val scope = appScope(bgDispatcher, TAG) private val _eventHandlers = ConcurrentHashMap.newKeySet() @@ -180,6 +192,7 @@ class LightningRepo @Inject constructor( init { observeConnectivityForSyncRetry() + scope.launch { sparkRepo.nodeEvents.collect { onSparkEvent(it) } } } private fun observeConnectivityForSyncRetry() { @@ -360,6 +373,9 @@ class LightningRepo @Inject constructor( if (shouldCancelPendingStop) cancelPendingStop() + // Spark needs no node, so it starts alongside it and stays up while the node stops in background. + scope.launch { sparkRepo.start(walletIndex) } + eventHandler?.let { _eventHandlers.add(it) } // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) @@ -607,6 +623,14 @@ class LightningRepo @Inject constructor( ) } + private suspend fun onSparkEvent(event: Event) { + val settledReceiveInvoice = (event as? Event.PaymentReceived)?.let { invalidateSettledReceiveInvoice(it) } + _eventHandlers.toList().forEach { + runCatching { it.invoke(event) } + } + _nodeEventUpdates.emit(NodeEventUpdate(event = event, settledReceiveInvoice = settledReceiveInvoice)) + } + private suspend fun invalidateSettledReceiveInvoice(event: Event.PaymentReceived): SettledReceiveInvoice? { val cachedReceive = runSuspendCatching { cacheStore.data.first() @@ -907,6 +931,7 @@ class LightningRepo @Inject constructor( lastKnownNodeId = null _lastKnownChannels.update { persistentListOf() } lightningService.wipeStorage(walletIndex) + sparkRepo.wipe(walletIndex) clearProbeOutcomes() _lightningState.update { LightningState( @@ -1304,6 +1329,9 @@ class LightningRepo @Inject constructor( expirySeconds: UInt = Defaults.bolt11ExpirySec, ): Result = executeWhenNodeRunning("createInvoice") { requireWalletRestoreComplete() + if (shouldReceiveWithSpark(amountSats)) { + return@executeWhenNodeRunning sparkRepo.createInvoice(amountSats, description, expirySeconds) + } runCatching { lightningService.receive(amountSats, description, expirySeconds) } } @@ -1313,9 +1341,34 @@ class LightningRepo @Inject constructor( expirySeconds: UInt = Defaults.bolt11ExpirySec, ): Result = executeWhenNodeRunning("createInvoiceMsats") { requireWalletRestoreComplete() + if (shouldReceiveWithSpark(amountMsats / MSATS_PER_SAT)) { + val amountSats = (amountMsats / MSATS_PER_SAT).takeIf { it > 0uL } + return@executeWhenNodeRunning sparkRepo.createInvoice(amountSats, description, expirySeconds) + } runCatching { lightningService.receiveMsats(amountMsats, description, expirySeconds) } } + /** Receives on Spark when no ready channel has the inbound capacity for [amountSats]. */ + private fun shouldReceiveWithSpark(amountSats: ULong?): Boolean { + if (!sparkRepo.canReceive()) return false + val readyChannels = _lightningState.value.channels.filter { it.isChannelReady } + return !ReceiveLiquidityDecision.canCreateLightningInvoice( + hasReadyChannels = readyChannels.isNotEmpty(), + inboundCapacitySats = readyChannels.calculateRemoteBalance(), + invoiceAmountSats = amountSats, + ) + } + + /** Pays with Spark when no channel has the outbound capacity for the invoice amount. */ + private fun shouldPayWithSpark(bolt11: String, sats: ULong?): Boolean { + val amountSats = sats ?: runCatching { Bolt11Invoice.fromStr(bolt11).amountMilliSatoshis() }.getOrNull() + ?.let { it / MSATS_PER_SAT } ?: return false + val state = _lightningState.value + val ldkCanSend = state.nodeLifecycleState.canRun() && + state.channels.totalNextOutboundHtlcLimitSats() >= amountSats + return !ldkCanSend && sparkRepo.canSend(amountSats) + } + suspend fun fetchLnurlInvoice( data: LnurlPayData, amountMsats: ULong, @@ -1409,6 +1462,22 @@ class LightningRepo @Inject constructor( paymentDeadlineAt: Instant?, maxTotalRoutingFeeMsat: ULong?, onBeforeSend: suspend () -> Boolean, + ): Result { + if (shouldPayWithSpark(bolt11, sats)) { + runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } + if (!onBeforeSend()) return Result.failure(PaymentAbortedBeforeSend()) + runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } + return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) + } + return payInvoiceWithLdk(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) + } + + private suspend fun payInvoiceWithLdk( + bolt11: String, + sats: ULong?, + paymentDeadlineAt: Instant?, + maxTotalRoutingFeeMsat: ULong?, + onBeforeSend: suspend () -> Boolean, ): Result = executeWhenNodeRunning("payInvoice") { requireWalletRestoreComplete() waitForUsableChannels() @@ -1420,6 +1489,17 @@ class LightningRepo @Inject constructor( } } + /** Confirmations of an on-chain transaction this wallet sent or received, 0 while unconfirmed. */ + suspend fun onchainConfirmations(txid: String): UInt? = withContext(bgDispatcher) { + val kind = lightningService.listPayments() + ?.map { it.kind } + ?.filterIsInstance() + ?.firstOrNull { it.txid.equals(txid, ignoreCase = true) } ?: return@withContext null + val confirmed = kind.status as? ConfirmationStatus.Confirmed ?: return@withContext 0u + val tip = _lightningState.value.block()?.height ?: return@withContext null + if (tip < confirmed.height) 0u else tip - confirmed.height + 1u + } + suspend fun listPaymentsOrNull(): List? = withContext(bgDispatcher) { lightningService.listPayments() } @@ -1872,6 +1952,17 @@ class LightningRepo @Inject constructor( } } + /** Finishes an accepted transfer locally; [orderId] is null for a transfer that funds the Spark wallet. */ + suspend fun completeAcceptedTransferFollowup(orderId: String?, txid: String) { + val attempt = onchainSendAttemptStore.current() ?: return + if (attempt.isTransfer && attempt.orderId == orderId && attempt.txid.equals(txid, ignoreCase = true) && + attempt.hasPositiveEvidence + ) { + finishOnchainSendLocally(attempt) + onchainSendAttemptStore.markLocalFollowupComplete(attempt.attemptId, attempt.walletIndex) + } + } + // A change signal only: consumers must reread and validate the original attempt. val onchainSendAttemptUpdates get() = onchainSendAttemptStore.backupStateVersion @@ -2206,6 +2297,7 @@ class LightningRepo @Inject constructor( fun canSend(amountSats: ULong): Boolean { val state = _lightningState.value + if (sparkRepo.canSend(amountSats)) return true if (!state.nodeLifecycleState.canRun()) return false return state.channels.totalNextOutboundHtlcLimitSats() >= amountSats } @@ -2256,9 +2348,22 @@ class LightningRepo @Inject constructor( if (state.nodeLifecycleState.isRunning()) state.channels else it } + /** The completion event of a Spark send that settled before its caller started watching for it. */ + suspend fun settledSparkSendEvent(paymentHash: String): Event? = sparkRepo.settledSendEvent(paymentHash) + + /** Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. */ + suspend fun sparkLightningSend(paymentHash: String): SparkLightningSend = sparkRepo.lightningSend(paymentHash) + + /** False while Spark is supported but its payment list is not complete yet, so a missing payment proves nothing. */ + fun canListSparkPayments(): Boolean = sparkRepo.canListPayments() + + /** + * Whether Lightning can be received, through a usable channel or Spark; Paykit publishes a Lightning endpoint + * only then. + */ fun canReceive(): Boolean { val isRunning = _lightningState.value.nodeLifecycleState.isRunning() - return isRunning && lightningService.canReceive() + return isRunning && (lightningService.canReceive() || sparkRepo.canReceive()) } suspend fun bumpFeeByRbf( @@ -2328,6 +2433,7 @@ class LightningRepo @Inject constructor( } suspend fun estimateRoutingFees(bolt11: String): Result = executeWhenNodeRunning("estimateRoutingFees") { + if (shouldPayWithSpark(bolt11, null)) return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, null) Logger.info("Estimating routing fees for bolt11: $bolt11", context = TAG) lightningService.estimateRoutingFees(bolt11).onSuccess { Logger.info("Routing fees estimated: '$it'", context = TAG) @@ -2338,6 +2444,9 @@ class LightningRepo @Inject constructor( suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result = executeWhenNodeRunning("estimateRoutingFeesForAmount") { + if (shouldPayWithSpark(bolt11, amountSats)) { + return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, amountSats) + } Logger.info("Estimating routing fees for amount: '$amountSats'", context = TAG) lightningService.estimateRoutingFeesForAmount(bolt11, amountSats).onSuccess { Logger.info("Routing fees estimated: '$it'", context = TAG) @@ -2639,6 +2748,7 @@ class LightningRepo @Inject constructor( private const val VSS_KEY_EXTERNAL_SCORES_CACHE = "external_pathfinding_scores_cache" private const val MS_SYNC_LOOP_DEBOUNCE = 500L private const val SYNC_RETRY_DELAY_MS = 15_000L + private const val MSATS_PER_SAT = 1_000uL private val BACKGROUND_STOP_DELAY = 5.seconds private val CHANNELS_USABLE_TIMEOUT = 15.seconds private val CHANNELS_USABLE_POLL_DELAY = 1.seconds diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 1c72fe4bae..de0910b5ab 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -42,6 +42,7 @@ import javax.inject.Singleton import kotlin.time.Clock import kotlin.time.Duration.Companion.days import kotlin.time.Instant +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus /** The side effects of paying one request, kept apart so the admission logic is testable without a node. */ @Singleton @@ -132,16 +133,35 @@ class PaykitAllowancePayer @Inject constructor( return PaymentOutcome.SUCCEEDED.takeIf { hasProof } } - /** True once the node can list its payments, so a payment missing from the list is one it never sent. */ + /** + * True once the node and Spark can both list their payments, so a payment missing from both lists is one the + * wallet never sent. + */ suspend fun canListLightningPayments(): Boolean = - runSuspendCatching { lightningRepo.listPaymentsOrNull() }.getOrNull() != null + runSuspendCatching { lightningRepo.listPaymentsOrNull() }.getOrNull() != null && + lightningRepo.canListSparkPayments() - /** The node's status for an outbound payment, or null when the node does not know it (or is not running). */ - suspend fun lightningPaymentStatus(paymentHash: String): PaymentStatus? = + /** + * The status of an outbound payment from the node, else from Spark; null when neither knows it (or the node is + * not running). PENDING while Spark cannot list its payments, so a Spark send is never read as never sent. + */ + suspend fun lightningPaymentStatus(paymentHash: String): PaymentStatus? { runSuspendCatching { lightningRepo.listPaymentsOrNull() } .getOrNull() ?.firstOrNull { it.direction == PaymentDirection.OUTBOUND && it.id.equals(paymentHash, ignoreCase = true) } - ?.status + ?.let { return it.status } + val spark = runSuspendCatching { lightningRepo.sparkLightningSend(paymentHash) } + .getOrDefault(SparkLightningSend.Unavailable) + return when (spark) { + SparkLightningSend.Unavailable -> PaymentStatus.PENDING + SparkLightningSend.NotFound -> null + is SparkLightningSend.Found -> when (spark.status) { + SparkPaymentStatus.COMPLETED -> PaymentStatus.SUCCEEDED + SparkPaymentStatus.PENDING -> PaymentStatus.PENDING + SparkPaymentStatus.FAILED -> PaymentStatus.FAILED + } + } + } } /** diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt index be283f9cf6..50be0304fe 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt @@ -171,12 +171,15 @@ class PaykitAllowanceRepo @Inject constructor( .map { it.nodeLifecycleState.isRunning() } .distinctUntilChanged() .filter { it } - .collect { - // Attempts recovery left open while the node could not list payments are settled now. - executor.activeIdentity?.let { identity -> executor.recover(identity) } - executor.settleOpenLightningAttempts() - } + .collect { settleAttemptsLeftOpen() } } + // Attempts recovery left open while the node or Spark could not list payments are settled once both can. + scope.launch { lightningRepo.isSparkSynced.filter { it }.collect { settleAttemptsLeftOpen() } } + } + + private suspend fun settleAttemptsLeftOpen() { + executor.activeIdentity?.let { identity -> executor.recover(identity) } + executor.settleOpenLightningAttempts() } fun entry(id: String): PaykitAllowanceEntry? = _entries.value.firstOrNull { it.id == id } diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index a07a0520e6..6036008521 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -45,6 +45,7 @@ import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.WalletScope import to.bitkit.services.PaykitSdkOperationLock import to.bitkit.services.PaykitSdkService +import to.bitkit.services.SparkError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import to.bitkit.utils.SignedTransactionId @@ -55,6 +56,7 @@ import javax.inject.Singleton import kotlin.time.Clock import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus /** New proof kinds must be readable on both platforms before either platform writes them to a wallet backup. */ @Serializable @@ -759,9 +761,10 @@ class PaykitPaymentProofRepo @Inject constructor( suspend fun failLightningPayment(paymentHash: String, submissionError: Throwable): Boolean { val error = generateSequence(submissionError) { it.cause } - .firstOrNull { it is ServiceError.PaymentDeadlineExpired } + .firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused } ?: submissionError.asNodeException() ?: submissionError when (error) { + is SparkError.SendRefused, is NodeNotRunningError, is NodeRunTimeoutError, is ServiceError.NodeNotSetup, @@ -1294,25 +1297,47 @@ class PaykitPaymentProofRepo @Inject constructor( if (paymentHash == null) return val payment = payments.firstOrNull { it.direction == PaymentDirection.OUTBOUND && it.id.equals(paymentHash, ignoreCase = true) - } ?: return + } + if (payment == null) { + reconcileSparkLightningProof(proof, paymentHash) + return + } when (payment.status) { PaymentStatus.PENDING -> Unit - PaymentStatus.FAILED -> removeProofsLocked { - it.kind == PaykitPaymentProofKind.Lightning && - it.paymentIdentifier.equals(paymentHash, ignoreCase = true) - } - PaymentStatus.SUCCEEDED -> { - val preimage = (payment.kind as? PaymentKind.Bolt11)?.preimage - if (preimage != null && preimage.matchesPaymentHash(paymentHash)) { - val completed = proof.copy(proofData = preimage.lowercase()) - val proofs = loadProofs().toMutableList() - val index = proofs.indexOf(proof) - if (index >= 0) { - proofs[index] = completed - persistAndSubmit(listOf(completed), proofs) - } - } - } + PaymentStatus.FAILED -> removeLightningProofsLocked(paymentHash) + PaymentStatus.SUCCEEDED -> completeLightningProofLocked( + proof, + paymentHash, + (payment.kind as? PaymentKind.Bolt11)?.preimage, + ) + } + } + + private suspend fun reconcileSparkLightningProof(proof: PendingPaykitPaymentProof, paymentHash: String) { + val send = lightningRepo.sparkLightningSend(paymentHash) as? SparkLightningSend.Found ?: return + when (send.status) { + SparkPaymentStatus.PENDING -> Unit + SparkPaymentStatus.FAILED -> removeLightningProofsLocked(paymentHash) + SparkPaymentStatus.COMPLETED -> completeLightningProofLocked(proof, paymentHash, send.preimage) + } + } + + private suspend fun removeLightningProofsLocked(paymentHash: String) = removeProofsLocked { + it.kind == PaykitPaymentProofKind.Lightning && it.paymentIdentifier.equals(paymentHash, ignoreCase = true) + } + + private suspend fun completeLightningProofLocked( + proof: PendingPaykitPaymentProof, + paymentHash: String, + preimage: String?, + ) { + if (preimage == null || !preimage.matchesPaymentHash(paymentHash)) return + val completed = proof.copy(proofData = preimage.lowercase()) + val proofs = loadProofs().toMutableList() + val index = proofs.indexOf(proof) + if (index >= 0) { + proofs[index] = completed + persistAndSubmit(listOf(completed), proofs) } } diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index f6c18ad460..3ab203f5bb 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -81,6 +81,7 @@ class PrivatePaykitRepo @Inject constructor( private val settingsStore: SettingsStore, private val addressReservationRepo: PrivatePaykitAddressReservationRepo, private val lightningRepo: LightningRepo, + private val sparkRepo: SparkRepo, private val walletRepo: WalletRepo, private val publicPaykitRepo: PublicPaykitRepo, private val paymentRequestRepo: PaykitPaymentRequestRepo, @@ -2428,7 +2429,7 @@ class PrivatePaykitRepo @Inject constructor( it.kind is PaymentKind.Bolt11 } .map { it.id.lowercase() } - .toSet() + .toSet() + sparkRepo.attemptedLightningPaymentHashes() private suspend fun isReceivedInvoiceSettled(paymentHash: String): Boolean = paymentHash in receivedSettledPaymentHashes() @@ -2444,7 +2445,7 @@ class PrivatePaykitRepo @Inject constructor( it.kind is PaymentKind.Bolt11 } .map { it.id } - .toSet() + .toSet() + sparkRepo.receivedLightningPaymentHashes() private suspend fun rememberReceivedInvoicePaymentHash(paymentHash: String, publicKey: String) { if (paymentHash.isBlank()) return diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt new file mode 100644 index 0000000000..398d92f4b5 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -0,0 +1,874 @@ +package to.bitkit.repositories + +import breez_sdk_spark.ClaimDeferredReason +import breez_sdk_spark.ClaimDepositOutcome +import breez_sdk_spark.FeePolicy +import breez_sdk_spark.FetchClaimDepositQuoteResponse +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentDetails +import breez_sdk_spark.PaymentMethod +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.SdkEvent +import breez_sdk_spark.SdkException +import breez_sdk_spark.SendOnchainFeeQuote +import breez_sdk_spark.SendPaymentMethod +import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.LightningActivity +import com.synonym.bitkitcore.PaymentState +import com.synonym.bitkitcore.PaymentType +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.toImmutableList +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.lightningdevkit.ldknode.Event +import org.lightningdevkit.ldknode.PaymentFailureReason +import org.lightningdevkit.ldknode.PaymentId +import to.bitkit.async.appScope +import to.bitkit.data.CacheStore +import to.bitkit.di.BgDispatcher +import to.bitkit.env.Env +import to.bitkit.ext.create +import to.bitkit.ext.nowMillis +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.SparkExitBackupV1 +import to.bitkit.models.WalletScope +import to.bitkit.models.safe +import to.bitkit.services.SparkError +import to.bitkit.services.SparkService +import to.bitkit.utils.Logger +import to.bitkit.utils.ServiceError +import java.io.File +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Provider +import javax.inject.Singleton +import kotlin.time.Clock +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant +import breez_sdk_spark.PaymentType as SparkPaymentType + +/** + * Lightning without channels, through the Breez SDK on Spark. Savings to Spending funds this wallet, + * receives fall back to it when no channel has the inbound capacity, and sends fall back to it when no + * channel has the outbound capacity. Its payments surface as ldk-node [Event]s through [nodeEvents], so the + * receive and send flows built on node events work for both rails. + */ +@Singleton +class SparkRepo @Inject constructor( + @BgDispatcher private val bgDispatcher: CoroutineDispatcher, + private val sparkService: SparkService, + private val activityRepo: Provider, + private val cacheStore: CacheStore, + private val contactResolver: Provider, + private val clock: Clock, +) { + companion object { + private const val TAG = "SparkRepo" + private const val MSATS_PER_SAT = 1_000uL + + /** How often to look at a deposit until its Instant claim is decided. */ + private val CLAIM_POLL_INTERVAL = 5.seconds + + /** Looks for 5 minutes before telling the user Spark hasn't seen the deposit yet. */ + private const val CLAIM_POLL_ATTEMPTS = 60 + + private val SEND_STATUS_PRIORITY = listOf(PaymentStatus.COMPLETED, PaymentStatus.PENDING, PaymentStatus.FAILED) + + /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ + private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL + } + + private val scope = appScope(bgDispatcher, TAG) + + @Volatile + private var preparedWithdrawal: PreparedWithdrawal? = null + + /** Withdrawals this app sent, by txid, known before Spark lists them so their arrival reads as a transfer. */ + private val withdrawalTxids = ConcurrentHashMap.newKeySet() + + /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ + private val broadcastDeposits = ConcurrentHashMap() + + /** Sends recorded before Spark knew their fee; its completion event reports 0 until a later sync. */ + private val sendsRecordedWithoutFee = ConcurrentHashMap.newKeySet() + + private var eventsJob: Job? = null + + /** Watchers of the claims of deposits this app sent, by txid; they outlive the screens that start them. */ + private val claimJobs = ConcurrentHashMap() + + private val _depositClaims = MutableStateFlow>(emptyMap()) + + /** Where the claim of each deposit sent from the transfer flow stands, by txid. */ + val depositClaims: StateFlow> = _depositClaims.asStateFlow() + + private val _state = MutableStateFlow(SparkState(isSupported = sparkService.isSupported)) + val state: StateFlow = _state.asStateFlow() + + private val _nodeEvents = MutableSharedFlow(extraBufferCapacity = 64) + val nodeEvents: SharedFlow = _nodeEvents.asSharedFlow() + + private val _exitStateChanged = MutableSharedFlow(extraBufferCapacity = 1) + + /** Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. */ + val exitStateChanged: SharedFlow = _exitStateChanged.asSharedFlow() + + suspend fun start(walletIndex: Int): Result = withContext(bgDispatcher) { + if (!sparkService.isSupported) return@withContext Result.success(Unit) + runSuspendCatching { + if (eventsJob == null) eventsJob = scope.launch { sparkService.events.collect { onSdkEvent(it) } } + sparkService.connect(walletIndex) + importRestoredExitState(walletIndex) + _exitStateChanged.emit(Unit) + refresh() + syncActivities() + }.onFailure { + Logger.error("Failed to start Spark wallet", it, context = TAG) + } + } + + suspend fun stop() = withContext(bgDispatcher) { + runSuspendCatching { sparkService.disconnect() } + .onFailure { Logger.warn("Failed to stop Spark wallet", it, context = TAG) } + _state.update { it.copy(isReady = false, hasSynced = false) } + } + + suspend fun wipe(walletIndex: Int) = withContext(bgDispatcher) { + runSuspendCatching { sparkService.wipeStorage(walletIndex) } + .onFailure { Logger.error("Failed to wipe Spark wallet", it, context = TAG) } + _state.update { SparkState(isSupported = sparkService.isSupported) } + } + + fun canReceive(): Boolean = _state.value.isReady + + fun canSend(amountSats: ULong): Boolean = _state.value.isReady && _state.value.sendableSats >= amountSats + + suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = + withContext(bgDispatcher) { + runSuspendCatching { sparkService.receiveBolt11(amountSats, description, expirySecs) } + } + + /** Returns the Lightning routing fee plus Spark's 0.25% service fee for paying [bolt11]. */ + suspend fun estimateFeeSats(bolt11: String, amountSats: ULong?): Result = withContext(bgDispatcher) { + runSuspendCatching { + val method = sparkService.prepareSend(bolt11, amountSats).paymentMethod + (method as SendPaymentMethod.Bolt11Invoice).feeSats() + } + } + + private fun SendPaymentMethod.Bolt11Invoice.feeSats(): ULong = + sparkTransferFeeSats?.takeIf { sparkService.prefersSpark } ?: lightningFeeSats + + /** + * Pays [bolt11] and returns its payment hash, the id ldk-node payments use, so the send flow can match it. + * Fails with [SparkError.SendRefused] when nothing left the wallet: Spark was not connected, could not prepare the + * payment, or its fee was over [maxTotalFeeMsat]; and with [ServiceError.PaymentDeadlineExpired] past + * [paymentDeadlineAt]. A failure inside the send itself stays uncertain, as the payment may have been dispatched. + */ + suspend fun payInvoice( + bolt11: String, + amountSats: ULong?, + paymentDeadlineAt: Instant? = null, + maxTotalFeeMsat: ULong? = null, + ): Result = withContext(bgDispatcher) { + runSuspendCatching { + ensurePaymentDeadline(paymentDeadlineAt) + if (!sparkService.isConnected) throw SparkError.SendRefused("Spark is not connected") + val prepared = runSuspendCatching { sparkService.prepareSend(bolt11, amountSats) } + .getOrElse { throw SparkError.SendRefused("Spark could not prepare the payment", it) } + val method = prepared.paymentMethod as? SendPaymentMethod.Bolt11Invoice + ?: throw SparkError.SendRefused("Unexpected Spark payment method '${prepared.paymentMethod}'") + val feeSats = method.feeSats() + if (maxTotalFeeMsat != null && feeSats.safe() * MSATS_PER_SAT.safe() > maxTotalFeeMsat) { + throw SparkError.SendRefused("Spark fee '$feeSats' sats is over the limit '$maxTotalFeeMsat' msat") + } + ensurePaymentDeadline(paymentDeadlineAt) + val payment = sparkService.send(prepared) + Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) + method.invoiceDetails.paymentHash + }.onFailure { + Logger.error("Failed to pay invoice with Spark", it, context = TAG) + } + } + + private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) { + if (paymentDeadlineAt != null && clock.now() > paymentDeadlineAt) throw ServiceError.PaymentDeadlineExpired() + } + + /** The most an Instant claim of a deposit of [amountSats] may cost: the ceiling the user accepts. */ + suspend fun estimateDepositClaimFeeSats(amountSats: ULong): Result = withContext(bgDispatcher) { + runSuspendCatching { SparkService.maxDepositClaimFeeSats(sparkService.fastestFeeRate(), amountSats) } + } + + /** What Spark keeps to claim a deposit at 3 confirmations, at the current half-hour fee rate. */ + suspend fun estimateMatureClaimFeeSats(): Result = withContext(bgDispatcher) { + runSuspendCatching { SparkService.matureDepositClaimFeeSats(sparkService.halfHourFeeRate()) } + } + + /** + * Follows the claim of the deposit in [txid] that the user sent at [speed]. Instant claims it early as soon as + * Spark offers that within [ceilingSats], and asks the user when it costs more; Later leaves it to the claim at + * maturity. Runs in the app scope, so leaving the transfer screens does not drop an Instant claim. + */ + fun followDepositClaim(txid: String, speed: SparkClaimSpeed, ceilingSats: ULong) { + claimJobs.remove(txid)?.cancel() + when (speed) { + SparkClaimSpeed.Later -> setDepositClaim(txid, SparkDepositClaim.Later) + SparkClaimSpeed.Instant -> { + setDepositClaim(txid, SparkDepositClaim.Looking) + claimJobs[txid] = scope.launch { claimInstantly(txid, ceilingSats) } + } + } + } + + /** Accepts the repriced Instant claim of [txid], at the fee the provider asks now. */ + fun payRepricedClaim(txid: String) { + val repriced = _depositClaims.value[txid] as? SparkDepositClaim.Repriced ?: return + followDepositClaim(txid, SparkClaimSpeed.Instant, repriced.offer.earlyFeeSats) + } + + /** Leaves the deposit in [txid] to the claim at 3 confirmations. */ + fun waitForMatureClaim(txid: String) { + claimJobs.remove(txid)?.cancel() + setDepositClaim(txid, SparkDepositClaim.Later) + } + + private suspend fun claimInstantly(txid: String, ceilingSats: ULong) { + var isSeen = false + repeat(CLAIM_POLL_ATTEMPTS) { + runSuspendCatching { refresh() } + .onFailure { Logger.warn("Failed to refresh Spark state", it, context = TAG) } + if (isClaimed(txid)) { + setDepositClaim(txid, SparkDepositClaim.Claimed) + return + } + if (_depositClaims.value[txid] != SparkDepositClaim.Adding) { + val offer = depositClaimOffer(txid) + .onFailure { Logger.warn("Failed to quote Spark deposit '$txid'", it, context = TAG) } + .getOrNull() + if (offer != null) isSeen = true + val claim = when (val step = SparkClaimStep.of(offer, ceilingSats)) { + SparkClaimStep.KeepLooking -> null + SparkClaimStep.Adding -> SparkDepositClaim.Adding + SparkClaimStep.Unavailable -> SparkDepositClaim.Unavailable + is SparkClaimStep.Ask -> SparkDepositClaim.Repriced(step.offer) + is SparkClaimStep.ClaimEarly -> claimEarly(step.offer).getOrNull()?.toDepositClaim(step.offer) + } + if (claim != null) setDepositClaim(txid, claim) + if (claim?.isFinal == true) return + } + delay(CLAIM_POLL_INTERVAL) + } + if (_depositClaims.value[txid] == SparkDepositClaim.Adding) return + Logger.warn("Stopped looking for the Instant claim of Spark deposit '$txid'", context = TAG) + setDepositClaim(txid, if (isSeen) SparkDepositClaim.Unavailable else SparkDepositClaim.NotSeen) + } + + private fun isClaimed(txid: String): Boolean = + _state.value.deposits.any { it.isClaimed && it.txid.equals(txid, ignoreCase = true) } + + private fun setDepositClaim(txid: String, claim: SparkDepositClaim) { + Logger.debug("Set claim of Spark deposit '$txid' to '$claim'", context = TAG) + _depositClaims.update { it + (txid to claim) } + } + + /** How the deposit in [txid] can be claimed, or null while Spark has not seen it yet. */ + suspend fun depositClaimOffer(txid: String): Result = withContext(bgDispatcher) { + runSuspendCatching { + val deposit = sparkService.listUnclaimedDeposits().firstOrNull { it.txid.equals(txid, ignoreCase = true) } + ?: return@runSuspendCatching null + SparkClaimOffer.from(deposit.txid, deposit.vout, sparkService.fetchClaimQuote(deposit.txid, deposit.vout)) + } + } + + /** Accepts the early claim of [offer] at its quoted fee. */ + suspend fun claimEarly(offer: SparkClaimOffer.Choice): Result = withContext(bgDispatcher) { + runSuspendCatching { + try { + SparkEarlyClaim.from(sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats)) + } catch (_: SdkException.DepositClaimInProgress) { + SparkEarlyClaim.Claimed + } + }.onSuccess { + Logger.info("Early claim of Spark deposit '${offer.txid}': '$it'", context = TAG) + refresh() + }.onFailure { + Logger.error("Failed to claim Spark deposit '${offer.txid}' early", it, context = TAG) + } + } + + suspend fun depositAddress(): Result = withContext(bgDispatcher) { + runSuspendCatching { sparkService.depositAddress() } + } + + /** Moves the whole Spark balance to the on-chain [address], fees included, for Spending to Savings. */ + suspend fun withdrawAll(address: String): Result = withContext(bgDispatcher) { + runSuspendCatching { + val payment = sparkService.send(prepareWithdrawAll(address)) + preparedWithdrawal = null + (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } + refresh() + }.onFailure { + Logger.error("Failed to withdraw from Spark", it, context = TAG) + } + } + + /** The fee [withdrawAll] pays at its speed, which comes out of the balance it moves. */ + suspend fun estimateWithdrawAllFeeSats(address: String): Result = withContext(bgDispatcher) { + runSuspendCatching { + val speed = prepareWithdrawAll(address).withdrawalQuote().speedMedium + speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe() + } + } + + /** + * Reuses the provider's withdrawal quote while it holds for the same address and balance, so the fee the confirm + * screen shows is the one the withdrawal pays; asking for a second quote while one held took minutes on regtest. + */ + private suspend fun prepareWithdrawAll(address: String): PrepareSendPaymentResponse { + val balanceSats = _state.value.balanceSats + val nowSecs = clock.now().epochSeconds.toULong() + preparedWithdrawal + ?.takeIf { it.address == address && it.balanceSats == balanceSats } + ?.takeIf { it.response.withdrawalQuote().expiresAt > nowSecs.safe() + QUOTE_EXPIRY_MARGIN_SECS.safe() } + ?.let { return it.response } + return sparkService.prepareSend(address, balanceSats, FeePolicy.FEES_INCLUDED) + .also { preparedWithdrawal = PreparedWithdrawal(address, balanceSats, it) } + } + + private fun PrepareSendPaymentResponse.withdrawalQuote(): SendOnchainFeeQuote = + (paymentMethod as SendPaymentMethod.BitcoinAddress).feeQuote + + /** + * Lists a deposit the app just broadcast as pending right away, then syncs so Spark sees it sooner than its + * minute-long background sync; Spark's own deposit state replaces it once listed. + */ + fun onDepositBroadcast(txid: String, amountSats: ULong) { + broadcastDeposits[txid] = amountSats + _state.update { it.withBroadcastDeposits() } + scope.launch { + runSuspendCatching { + sparkService.syncWallet() + refresh() + }.onFailure { Logger.warn("Failed to sync Spark after deposit '$txid'", it, context = TAG) } + } + } + + private fun SparkState.withBroadcastDeposits(): SparkState { + val known = deposits.map { it.txid }.toSet() + val local = broadcastDeposits.filterKeys { it !in known } + .map { (txid, amount) -> SparkDeposit(txid = txid, amountSats = amount, isClaimed = false) } + if (local.isEmpty()) return this + val all = local + deposits + return copy( + deposits = all.toImmutableList(), + pendingDepositSats = all.filterNot { it.isClaimed }.sumOf { it.amountSats }, + ) + } + + /** The exit data backup, or null while Spark is not connected and there is nothing to back up. */ + suspend fun exitBackup(): Result = withContext(bgDispatcher) { + runSuspendCatching { + val network = sparkService.networkName + if (!sparkService.isConnected || network == null) return@runSuspendCatching null + SparkExitBackupV1(createdAt = nowMillis(), network = network, exitState = sparkService.exportExitState()) + } + } + + /** + * Puts a restored exit data backup back: at once while Spark is connected, otherwise right after it connects, + * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. + */ + suspend fun restoreExitBackup(backup: SparkExitBackupV1, walletIndex: Int): Result = + withContext(bgDispatcher) { + runSuspendCatching { + if (backup.network != sparkService.networkName) { + Logger.warn("Skipped Spark exit data from network '${backup.network}'", context = TAG) + return@runSuspendCatching + } + File(Env.sparkExitRestorePath(walletIndex)).writeText(backup.exitState) + if (sparkService.isConnected) importRestoredExitState(walletIndex) + } + } + + private suspend fun importRestoredExitState(walletIndex: Int) { + val file = File(Env.sparkExitRestorePath(walletIndex)) + if (!file.exists()) return + runSuspendCatching { sparkService.importExitState(file.readText()) } + .onSuccess { + file.delete() + Logger.info( + "Imported Spark exit data: '${it.importedLeaves}' leaves, '${it.skippedForeignLeaves}' foreign, " + + "'${it.skippedConflictingLeaves}' conflicting, '${it.skippedChains}' already held", + context = TAG, + ) + } + .onFailure { Logger.error("Failed to import Spark exit data", it, context = TAG) } + } + + suspend fun refreshState(): Result = withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext Result.success(Unit) + runSuspendCatching { refresh() }.onFailure { Logger.warn("Failed to refresh Spark state", it, context = TAG) } + } + + private suspend fun refresh() { + val info = sparkService.getInfo() + val pending = sparkService.listUnclaimedDeposits().map { + SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) + } + val payments = sparkService.listPayments() + val claimed = payments + .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } + .mapNotNull { payment -> + val deposit = payment.details as? PaymentDetails.Deposit ?: return@mapNotNull null + SparkDeposit( + txid = deposit.txId, + amountSats = payment.amount.toLong().toULong(), + isClaimed = true, + feeSats = payment.fees.toLong().toULong(), + claimedAt = payment.timestamp, + ) + } + (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } + _state.update { + it.copy( + isReady = true, + balanceSats = info.balanceSats, + pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, + deposits = (pending + claimed).toImmutableList(), + withdrawals = payments.toWithdrawals(), + recoverableFundsSats = info.recoverableFundsSats, + ).withBroadcastDeposits() + } + payments.filter { it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0 }.forEach { recordActivity(it) } + markTransfers(payments) + } + + private fun List.toWithdrawals() = filter { it.status != PaymentStatus.FAILED } + .mapNotNull { payment -> + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@mapNotNull null + SparkWithdrawal( + txid = withdraw.txId, + amountSats = payment.amount.toLong().toULong(), + feeSats = payment.fees.toLong().toULong(), + ) + } + .toImmutableList() + + /** + * Marks the on-chain receive [txid] as a transfer from Spending when it is a Spark withdrawal, so it shows no + * Received sheet and reads as a transfer in Activity. Returns whether it is one. + */ + suspend fun markWithdrawalAsTransfer(txid: String): Boolean = withContext(bgDispatcher) { + val isWithdrawal = txid in withdrawalTxids || _state.value.withdrawals.any { it.txid == txid } + if (!isWithdrawal) return@withContext false + val activities = activityRepo.get() + activities.getOnchainActivityByTxId(txid)?.takeUnless { it.isTransfer }?.let { + activities.updateActivity(it.id, Activity.Onchain(it.copy(isTransfer = true))) + } + true + } + + private suspend fun markTransfers(payments: List) { + val activities = activityRepo.get() + payments.filter { it.status != PaymentStatus.FAILED } + .mapNotNull { (it.details as? PaymentDetails.Withdraw)?.txId } + .forEach { txid -> + val activity = activities.getOnchainActivityByTxId(txid)?.takeUnless { it.isTransfer } ?: return@forEach + activities.updateActivity(activity.id, Activity.Onchain(activity.copy(isTransfer = true))) + } + } + + /** + * The completion event of a Spark Lightning send that has already settled. A Spark-to-Spark payment settles inside + * the send call, so its event can fire before the caller starts watching for it. + */ + suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext null + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrNull() + ?.firstOrNull { + val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash + it.paymentType == SparkPaymentType.SEND && hash.equals(paymentHash, ignoreCase = true) + } + ?.toNodeEvent() + } + + /** + * False while Spark is supported but not connected or not yet synced, since its payment list is read from local + * storage that a restored wallet fills only on its first sync, so a missing payment proves nothing until then. + */ + fun canListPayments(): Boolean = + !sparkService.isSupported || (sparkService.isConnected && _state.value.hasSynced) + + /** + * Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. + * [SparkLightningSend.Unavailable] while Spark is supported but cannot list its payments, so a send it may hold + * is never read as one it never made. + */ + suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { + if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound + if (!canListPayments()) return@withContext SparkLightningSend.Unavailable + val payments = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrElse { return@withContext SparkLightningSend.Unavailable } + payments + .filter { + val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash + it.paymentType == SparkPaymentType.SEND && hash.equals(paymentHash, ignoreCase = true) + } + // A retry of a failed send shares its hash, so the outcome that settles it wins. + .minByOrNull { SEND_STATUS_PRIORITY.indexOf(it.status) } + ?.let { SparkLightningSend.Found(it.status, (it.details as PaymentDetails.Lightning).htlcDetails.preimage) } + ?: SparkLightningSend.NotFound + } + + /** Payment hashes of the Lightning payments Spark received. */ + suspend fun receivedLightningPaymentHashes(): Set = + lightningPaymentHashes { it.paymentType == SparkPaymentType.RECEIVE && it.status == PaymentStatus.COMPLETED } + + /** Payment hashes of the Lightning payments Spark sent or is sending. */ + suspend fun attemptedLightningPaymentHashes(): Set = + lightningPaymentHashes { it.paymentType == SparkPaymentType.SEND && it.status != PaymentStatus.FAILED } + + private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set = withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext emptySet() + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrDefault(emptyList()) + .filter(filter) + .mapNotNull { (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash?.lowercase() } + .toSet() + } + + private suspend fun syncActivities() { + sparkService.listPayments().forEach { recordActivity(it) } + } + + private suspend fun onSdkEvent(event: SdkEvent) { + runSuspendCatching { + when (event) { + is SdkEvent.Synced -> { + _state.update { it.copy(hasSynced = true) } + refresh() + } + is SdkEvent.PaymentSucceeded -> onPayment(event.payment) + is SdkEvent.PaymentFailed -> onPayment(event.payment) + is SdkEvent.PaymentPending -> recordActivity(event.payment) + is SdkEvent.UnclaimedDeposits -> Logger.warn( + "Found '${event.unclaimedDeposits.size}' unclaimed Spark deposits", + context = TAG, + ) + is SdkEvent.NewDeposits -> refresh() + is SdkEvent.UnilateralExitStateChanged -> _exitStateChanged.emit(Unit) + is SdkEvent.ClaimedDeposits -> refresh() + else -> Unit + } + }.onFailure { + Logger.error("Failed to handle Spark event '$event'", it, context = TAG) + } + } + + private suspend fun onPayment(payment: Payment) { + refresh() + recordActivity(payment) + payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + } + + private suspend fun recordActivity(payment: Payment) { + val lightning = payment.details as? PaymentDetails.Lightning ?: return + if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { + return + } + val id = lightning.htlcDetails.paymentHash + val existing = (activityRepo.get().getActivity(id).getOrNull() as? Activity.Lightning)?.v1 + val activity = LightningActivity.create( + id = id, + txType = when (payment.paymentType) { + SparkPaymentType.SEND -> PaymentType.SENT + SparkPaymentType.RECEIVE -> PaymentType.RECEIVED + }, + status = when (payment.status) { + PaymentStatus.COMPLETED -> PaymentState.SUCCEEDED + PaymentStatus.PENDING -> PaymentState.PENDING + PaymentStatus.FAILED -> PaymentState.FAILED + }, + value = payment.amount.toLong().toULong(), + invoice = lightning.invoice, + timestamp = payment.timestamp, + fee = payment.fees.toLong().toULong(), + message = lightning.description.orEmpty(), + preimage = lightning.htlcDetails.preimage, + contact = existing?.contact ?: receivedContact(payment, id), + seenAt = existing?.seenAt, + ) + activityRepo.get().upsertActivity(Activity.Lightning(activity)) + if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { + sendsRecordedWithoutFee.add(payment.id) + } else { + sendsRecordedWithoutFee.remove(payment.id) + } + } + + private suspend fun receivedContact(payment: Payment, paymentHash: String): String? { + if (payment.paymentType != SparkPaymentType.RECEIVE || payment.status == PaymentStatus.FAILED) return null + if (cacheStore.data.first().isContactDetached(paymentHash, WalletScope.default)) return null + return runSuspendCatching { contactResolver.get().contactPublicKeyForPrivateInvoicePaymentHash(paymentHash) } + .onFailure { Logger.warn("Failed to resolve contact of Spark receive '$paymentHash'", it, context = TAG) } + .getOrNull() + } + + private fun Payment.toNodeEvent(): Event? { + val lightning = details as? PaymentDetails.Lightning ?: return null + val hash = lightning.htlcDetails.paymentHash + val amountMsat = amount.toLong().toULong() * MSATS_PER_SAT + return when (paymentType to status) { + SparkPaymentType.RECEIVE to PaymentStatus.COMPLETED -> + Event.PaymentReceived(hash, hash, amountMsat, emptyList()) + SparkPaymentType.SEND to PaymentStatus.COMPLETED -> + Event.PaymentSuccessful( + hash, + hash, + lightning.htlcDetails.preimage, + fees.toLong().toULong() * MSATS_PER_SAT + ) + SparkPaymentType.SEND to PaymentStatus.FAILED -> + Event.PaymentFailed(hash, hash, PaymentFailureReason.UNEXPECTED_ERROR) + else -> null + } + } +} + +private class PreparedWithdrawal( + val address: String, + val balanceSats: ULong, + val response: PrepareSendPaymentResponse, +) + +data class SparkState( + val isSupported: Boolean = false, + val isReady: Boolean = false, + /** Spark synced its payments at least once since it connected, so its payment list is complete. */ + val hasSynced: Boolean = false, + val balanceSats: ULong = 0uL, + /** Deposits seen on-chain that Spark claims into [balanceSats] after 3 confirmations. */ + val pendingDepositSats: ULong = 0uL, + val deposits: ImmutableList = persistentListOf(), + val withdrawals: ImmutableList = persistentListOf(), + val recoverableFundsSats: ULong = 0uL, +) { + /** The most Spark can send once its service fee is paid, so a payment near the full balance isn't offered. */ + val sendableSats: ULong get() = SparkFees.sendableSats(balanceSats) +} + +object SparkFees { + /** Spark keeps 0.25% of a Lightning send as its service fee, on top of routing. */ + const val SERVICE_FEE_PPM = 2_500uL + + private const val PPM = 1_000_000uL + + /** The largest amount whose fee, rounded up, fits beside it: `amount + ceil(amount * ppm / 1e6) <= balance`. */ + fun sendableSats(balanceSats: ULong): ULong { + val sendable = balanceSats.safe() * PPM.safe() / (PPM + SERVICE_FEE_PPM) + return if (sendable == 0uL || sendable.safe() + serviceFeeSats(sendable).safe() <= balanceSats) { + sendable + } else { + sendable - 1uL + } + } + + fun serviceFeeSats(amountSats: ULong): ULong = (amountSats.safe() * SERVICE_FEE_PPM.safe() + (PPM - 1uL)) / PPM +} + +/** Spark's record of a Lightning send. */ +sealed interface SparkLightningSend { + /** Spark is supported but cannot list its payments yet. */ + data object Unavailable : SparkLightningSend + + data object NotFound : SparkLightningSend + + data class Found(val status: PaymentStatus, val preimage: String?) : SparkLightningSend +} + +/** A Transfer to Savings out of Spark, with what Spark kept for it. */ +data class SparkWithdrawal( + val txid: String, + val amountSats: ULong, + val feeSats: ULong, +) + +/** An on-chain deposit into Spark: pending until Spark claims it after 3 confirmations. */ +data class SparkDeposit( + val txid: String, + val amountSats: ULong, + val isClaimed: Boolean, + val feeSats: ULong = 0uL, + val claimedAt: ULong? = null, +) + +/** + * How a deposit into Spark can be claimed. The provider decides per deposit whether to credit it early, at 0 + * confirmations or 1-2, for a fee above the standard claim's at 3 confirmations. + */ +sealed interface SparkClaimOffer { + val txid: String + val vout: UInt + + /** No early claim is offered, so Spark claims it at [confirmations] for [feeSats]. */ + data class Standard( + override val txid: String, + override val vout: UInt, + val feeSats: ULong, + val confirmations: UInt, + ) : SparkClaimOffer + + /** The early claim fits this wallet's fee cap, so Spark claims it at [confirmations] by itself. */ + data class Automatic( + override val txid: String, + override val vout: UInt, + val feeSats: ULong, + val confirmations: UInt, + ) : SparkClaimOffer + + /** The early claim costs more than the cap, so it waits for the user to accept [earlyFeeSats]. */ + data class Choice( + override val txid: String, + override val vout: UInt, + val earlyFeeSats: ULong, + val earlyConfirmations: UInt, + val standardFeeSats: ULong, + val standardConfirmations: UInt, + ) : SparkClaimOffer + + companion object { + fun from(txid: String, vout: UInt, quote: FetchClaimDepositQuoteResponse): SparkClaimOffer { + val mature = quote.mature + val early = quote.instant + ?: return Standard(txid, vout, mature.feeSats, mature.confirmationsRequired) + val cap = early.maxFeeSats + if (cap != null && early.feeSats <= cap) { + return Automatic(txid, vout, early.feeSats, early.confirmationsRequired) + } + return Choice( + txid = txid, + vout = vout, + earlyFeeSats = early.feeSats, + earlyConfirmations = early.confirmationsRequired, + standardFeeSats = mature.feeSats, + standardConfirmations = mature.confirmationsRequired, + ) + } + } +} + +/** What accepting an early claim did. */ +sealed interface SparkEarlyClaim { + /** The claim is submitted and the deposit reaches the balance shortly. */ + data object Claimed : SparkEarlyClaim + + /** Not offered at this depth yet; Spark claims it early once a confirmation brings the offer. */ + data object Waiting : SparkEarlyClaim + + /** The provider now asks [requiredFeeSats], more than was accepted. */ + data class Repriced(val requiredFeeSats: ULong) : SparkEarlyClaim + + /** The provider declined it, so Spark claims the deposit at 3 confirmations. */ + data object Declined : SparkEarlyClaim + + companion object { + fun from(outcome: ClaimDepositOutcome): SparkEarlyClaim = when (outcome) { + is ClaimDepositOutcome.Settled, ClaimDepositOutcome.Submitted -> Claimed + is ClaimDepositOutcome.Deferred -> when (val reason = outcome.reason) { + ClaimDeferredReason.NoEarlyClaimAvailable -> Waiting + is ClaimDeferredReason.MaxFeeExceeded -> Repriced(reason.requiredFeeSats) + is ClaimDeferredReason.ProviderDeclined -> Declined + } + } + } +} + +/** How fast the user wants a deposit in the spending balance. */ +enum class SparkClaimSpeed { + /** Pays the provider to add it before confirmations, up to the ceiling the user accepted. */ + Instant, + + /** Waits for 3 confirmations, at the lower fee of the claim at maturity. */ + Later, +} + +/** Where the claim of a deposit the user sent stands. */ +sealed interface SparkDepositClaim { + /** Spark has not listed the deposit yet, or offers no early claim at this depth. */ + data object Looking : SparkDepositClaim + + /** The early claim is under way and the deposit reaches the balance shortly. */ + data object Adding : SparkDepositClaim + + /** The deposit is in the spending balance. */ + data object Claimed : SparkDepositClaim + + /** The early claim now costs more than the user accepted; it waits for the user to pay it or wait. */ + data class Repriced(val offer: SparkClaimOffer.Choice) : SparkDepositClaim + + /** No early claim for this deposit, so Spark adds it after 3 confirmations. */ + data object Unavailable : SparkDepositClaim + + /** The user chose to wait for 3 confirmations. */ + data object Later : SparkDepositClaim + + /** Spark did not list the deposit in time; it still adds it after 3 confirmations. */ + data object NotSeen : SparkDepositClaim + + /** Whether nothing more is asked of the provider for this deposit. */ + val isFinal: Boolean get() = this !is Looking && this !is Adding +} + +/** What an Instant transfer does with the claim [SparkClaimOffer] Spark has for its deposit. */ +sealed interface SparkClaimStep { + /** Not listed yet: look again. */ + data object KeepLooking : SparkClaimStep + + /** The early claim fits the user's cap, so Spark makes it by itself. */ + data object Adding : SparkClaimStep + + /** No early claim on offer. */ + data object Unavailable : SparkClaimStep + + /** Within the ceiling the user accepted: claim it now. */ + data class ClaimEarly(val offer: SparkClaimOffer.Choice) : SparkClaimStep + + /** Above the ceiling: ask the user. */ + data class Ask(val offer: SparkClaimOffer.Choice) : SparkClaimStep + + companion object { + fun of(offer: SparkClaimOffer?, ceilingSats: ULong): SparkClaimStep = when (offer) { + null -> KeepLooking + is SparkClaimOffer.Automatic -> Adding + is SparkClaimOffer.Standard -> Unavailable + is SparkClaimOffer.Choice if offer.earlyFeeSats <= ceilingSats -> ClaimEarly(offer) + is SparkClaimOffer.Choice -> Ask(offer) + } + } +} + +/** What accepting the early claim of [offer] leaves the deposit at. */ +fun SparkEarlyClaim.toDepositClaim(offer: SparkClaimOffer.Choice): SparkDepositClaim = when (this) { + SparkEarlyClaim.Claimed -> SparkDepositClaim.Adding + SparkEarlyClaim.Waiting -> SparkDepositClaim.Looking + is SparkEarlyClaim.Repriced -> SparkDepositClaim.Repriced(offer.copy(earlyFeeSats = requiredFeeSats)) + SparkEarlyClaim.Declined -> SparkDepositClaim.Unavailable +} diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index e67c95d1a2..d988881a95 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -15,7 +15,9 @@ import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -76,6 +78,7 @@ class WalletRepo @Inject constructor( private val activityRepo: ActivityRepo, private val hwWalletRepo: HwWalletRepo, private val connectionRecovery: WalletConnectionRecovery, + private val sparkRepo: SparkRepo, ) { private val repoScope = appScope(bgDispatcher, TAG) @@ -115,6 +118,16 @@ class WalletRepo @Inject constructor( _balanceState.update { state -> state.copy(hardwareWallets = wallets.map { it.toBalance() }) } } } + repoScope.launch { + sparkRepo.state.map { it.isReady }.distinctUntilChanged().collect { isReady -> + if (isReady && walletExists()) refreshBip21() + } + } + repoScope.launch { + sparkRepo.state.map { it.balanceSats to it.pendingDepositSats }.distinctUntilChanged().collect { + if (walletExists()) syncBalances() + } + } } private suspend fun updateReceiveState( @@ -414,7 +427,8 @@ class WalletRepo @Inject constructor( fun refreshMaxSendLightning() { val state = lightningRepo.lightningState.value if (!state.nodeLifecycleState.isRunning()) return - _balanceState.update { it.copy(maxSendLightningSats = state.channels.totalNextOutboundHtlcLimitSats()) } + val maxSendSats = maxOf(state.channels.totalNextOutboundHtlcLimitSats(), sparkRepo.state.value.sendableSats) + _balanceState.update { it.copy(maxSendLightningSats = maxSendSats) } } suspend fun syncBalances() { @@ -991,11 +1005,15 @@ class WalletRepo @Inject constructor( } } + /** Spark receives any amount without inbound liquidity, so no channel or CJIT is needed. */ + fun canReceiveWithSpark(): Boolean = sparkRepo.canReceive() + suspend fun inboundLiquiditySats(): ULong = withContext(bgDispatcher) { return@withContext currentReadyChannels().calculateRemoteBalance() } private fun canCreateLightningInvoice(amountSats: ULong?): Boolean { + if (sparkRepo.canReceive()) return true val readyChannels = currentReadyChannels() return ReceiveLiquidityDecision.canCreateLightningInvoice( hasReadyChannels = readyChannels.isNotEmpty(), diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index c0ff8e83b1..d30f8f2af4 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -32,6 +32,7 @@ import org.lightningdevkit.ldknode.CoinSelectionAlgorithm import org.lightningdevkit.ldknode.Config import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.ElectrumSyncConfig +import org.lightningdevkit.ldknode.EsploraSyncConfig import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.FeeRate import org.lightningdevkit.ldknode.KeychainKind @@ -398,6 +399,20 @@ class LightningService internal constructor( } private suspend fun Builder.configureChainSource(customServerUrl: String? = null) { + Env.regtestEsploraUrl?.let { esploraUrl -> + Logger.info("Using onchain source Esplora url: '$esploraUrl'", context = TAG) + setChainSourceEsplora( + serverUrl = esploraUrl, + config = EsploraSyncConfig( + BackgroundSyncConfig( + onchainWalletSyncIntervalSecs = Env.walletSyncIntervalSecs, + lightningWalletSyncIntervalSecs = Env.walletSyncIntervalSecs, + feeRateCacheUpdateIntervalSecs = Env.walletSyncIntervalSecs, + ), + ), + ) + return + } val serverUrl = customServerUrl ?: settingsStore.data.first().electrumServer Logger.info("Using onchain source Electrum Sever url: $serverUrl", context = TAG) setChainSourceElectrum( diff --git a/app/src/main/java/to/bitkit/services/MigrationService.kt b/app/src/main/java/to/bitkit/services/MigrationService.kt index 9e47625fde..b68150ae07 100644 --- a/app/src/main/java/to/bitkit/services/MigrationService.kt +++ b/app/src/main/java/to/bitkit/services/MigrationService.kt @@ -999,6 +999,8 @@ class MigrationService internal constructor( isBiometricEnabled = settings.biometrics ?: current.isBiometricEnabled, quickPayIntroSeen = settings.quickpayIntroSeen ?: current.quickPayIntroSeen, hasSeenShopIntro = settings.shopIntroSeen ?: current.hasSeenShopIntro, + hasSeenTransferIntro = settings.transferIntroSeen ?: current.hasSeenTransferIntro, + hasSeenSpendingIntro = settings.spendingIntroSeen ?: current.hasSeenSpendingIntro, hasSeenSavingsIntro = settings.savingsIntroSeen ?: current.hasSeenSavingsIntro, ) } @@ -2144,6 +2146,8 @@ data class RNSettings( val hideBalanceOnOpen: Boolean? = null, val quickpayIntroSeen: Boolean? = null, val shopIntroSeen: Boolean? = null, + val transferIntroSeen: Boolean? = null, + val spendingIntroSeen: Boolean? = null, val savingsIntroSeen: Boolean? = null, val selectedAddressType: String? = null, val addressTypesToMonitor: List? = null, diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt new file mode 100644 index 0000000000..e11294d0b8 --- /dev/null +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -0,0 +1,266 @@ +package to.bitkit.services + +import breez_sdk_spark.BreezSdk +import breez_sdk_spark.ClaimDepositOutcome +import breez_sdk_spark.ClaimDepositRequest +import breez_sdk_spark.Config +import breez_sdk_spark.ConnectRequest +import breez_sdk_spark.DepositInfo +import breez_sdk_spark.EventListener +import breez_sdk_spark.FeePolicy +import breez_sdk_spark.FetchClaimDepositQuoteRequest +import breez_sdk_spark.FetchClaimDepositQuoteResponse +import breez_sdk_spark.GetInfoRequest +import breez_sdk_spark.GetInfoResponse +import breez_sdk_spark.ImportUnilateralExitStateRequest +import breez_sdk_spark.ImportUnilateralExitStateResponse +import breez_sdk_spark.ListPaymentsRequest +import breez_sdk_spark.ListUnclaimedDepositsRequest +import breez_sdk_spark.MaxFee +import breez_sdk_spark.MaxOnchainFee +import breez_sdk_spark.OnchainConfirmationSpeed +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentRequest +import breez_sdk_spark.PrepareSendPaymentRequest +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.ReceivePaymentMethod +import breez_sdk_spark.ReceivePaymentRequest +import breez_sdk_spark.SdkEvent +import breez_sdk_spark.Seed +import breez_sdk_spark.SendPaymentMethod +import breez_sdk_spark.SendPaymentOptions +import breez_sdk_spark.SendPaymentRequest +import breez_sdk_spark.SyncWalletRequest +import breez_sdk_spark.connect +import breez_sdk_spark.defaultConfig +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.lightningdevkit.ldknode.Network +import to.bitkit.data.keychain.Keychain +import to.bitkit.env.Env +import to.bitkit.models.safe +import to.bitkit.utils.AppError +import to.bitkit.utils.Logger +import to.bitkit.utils.ServiceError +import java.io.File +import java.math.BigInteger +import javax.inject.Inject +import javax.inject.Singleton +import breez_sdk_spark.Network as SparkNetwork + +/** + * Wraps the Breez SDK on Spark, which keeps Lightning available without channels after Blocktank stopped + * selling them. The Spark wallet derives its keys from the Bitkit seed on its own path (`m/8797555'`). + */ +@Singleton +class SparkService @Inject constructor( + private val keychain: Keychain, +) { + companion object { + private const val TAG = "SparkService" + + /** + * Bitkit's settings over the SDK's [defaults]. Breez's real-time data sync server and its Lightning address + * (LNURL) server stay off on every network. + */ + internal fun configure(defaults: Config, apiKey: String?): Config = defaults.apply { + this.apiKey = apiKey + realTimeSyncServerUrl = null + lnurlDomain = null + // Lowering it below the spread keeps the deposit from being claimed early, and does not hold back its + // claim at maturity. + maxDepositClaimFee = MaxFee( + onchain = MaxOnchainFee.NetworkRecommended(DEPOSIT_CLAIM_FEE_LEEWAY_SAT_PER_VB), + proportionalPpm = null, + ) + } + + /** Leeway in sat/vB over the recommended fee that an automatic deposit claim may pay. */ + private const val DEPOSIT_CLAIM_FEE_LEEWAY_SAT_PER_VB = 2uL + + /** Share of a deposit, in parts per million, that an Instant claim may pay on top of its on-chain fee. */ + private const val DEPOSIT_CLAIM_FEE_PPM = 2_000u + + private const val PPM_DIVISOR = 1_000_000uL + + /** Size of the transaction that claims a deposit, which prices the on-chain part of its fee. */ + private const val CLAIM_TX_SIZE_VBYTES = 99uL + + /** + * The most an Instant claim of a deposit of [amountSats] may cost, at the fastest recommended fee rate + * [fastestFeeRate]: the ceiling the user accepts. The provider quotes the real fee only once the deposit + * exists. + */ + fun maxDepositClaimFeeSats(fastestFeeRate: ULong, amountSats: ULong): ULong { + val rate = fastestFeeRate.safe() + DEPOSIT_CLAIM_FEE_LEEWAY_SAT_PER_VB.safe() + val onchain = rate.safe() * CLAIM_TX_SIZE_VBYTES.safe() + val proportional = amountSats.safe() * DEPOSIT_CLAIM_FEE_PPM.toULong().safe() / PPM_DIVISOR + return onchain.safe() + proportional.safe() + } + + /** What Spark keeps to claim a deposit at 3 confirmations, at the half-hour fee rate [halfHourFeeRate]. */ + fun matureDepositClaimFeeSats(halfHourFeeRate: ULong): ULong = + halfHourFeeRate.safe() * CLAIM_TX_SIZE_VBYTES.safe() + + /** + * Returns as soon as the payment starts, like ldk-node, so its completion reaches callers as an event they + * are already watching for; waiting for completion here fired that event before they watched. + */ + fun bolt11SendOptions(prefersSpark: Boolean): SendPaymentOptions = + SendPaymentOptions.Bolt11Invoice(preferSpark = prefersSpark, completionTimeoutSecs = null) + } + + private val mutex = Mutex() + private var sdk: BreezSdk? = null + private var listenerId: String? = null + + private val _events = MutableSharedFlow(extraBufferCapacity = 64) + val events: SharedFlow = _events.asSharedFlow() + + /** Spark runs on mainnet with a Breez API key, and on Lightspark's hosted regtest, which needs none. */ + val isSupported: Boolean + get() = when (Env.network) { + Network.BITCOIN -> Env.breezApiKey != null + Network.REGTEST -> true + else -> false + } + + val isConnected: Boolean get() = sdk != null + + /** + * Spark's regtest has no Lightning network, so there a Lightning invoice from another Spark wallet is paid as a + * Spark transfer, which lets two dev builds pay each other's invoices. + */ + val prefersSpark: Boolean get() = Env.network == Network.REGTEST + + suspend fun connect(walletIndex: Int) = mutex.withLock { + if (sdk != null) return@withLock + val network = sparkNetwork() ?: throw SparkError.Unsupported() + val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() + val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val config = configure(defaultConfig(network), Env.breezApiKey) + val storageDir = File(Env.sparkStoragePath(walletIndex)).apply { mkdirs() }.path + val connected = connect(ConnectRequest(config, Seed.Mnemonic(mnemonic, passphrase), storageDir)) + listenerId = connected.addEventListener( + object : EventListener { + override suspend fun onEvent(event: SdkEvent) { + _events.emit(event) + } + }, + ) + sdk = connected + Logger.info("Connected Spark wallet on '$network'", context = TAG) + } + + suspend fun disconnect() = mutex.withLock { + val current = sdk ?: return@withLock + listenerId?.let { current.removeEventListener(it) } + current.disconnect() + sdk = null + listenerId = null + Logger.info("Disconnected Spark wallet", context = TAG) + } + + suspend fun wipeStorage(walletIndex: Int) { + disconnect() + File(Env.sparkStoragePath(walletIndex)).deleteRecursively() + } + + /** Syncs with Spark now instead of waiting for the SDK's next background sync. */ + suspend fun syncWallet() { + requireSdk().syncWallet(SyncWalletRequest) + } + + suspend fun getInfo(): GetInfoResponse = requireSdk().getInfo(GetInfoRequest(ensureSynced = false)) + + suspend fun receiveBolt11(amountSats: ULong?, description: String, expirySecs: UInt): String { + val method = ReceivePaymentMethod.Bolt11Invoice(description, amountSats, expirySecs, null, null) + return requireSdk().receivePayment(ReceivePaymentRequest(method)).paymentRequest + } + + /** Returns the static on-chain address that funds the Spark wallet, claimed automatically once confirmed. */ + suspend fun depositAddress(): String { + val method = ReceivePaymentMethod.BitcoinAddress(newAddress = null) + return requireSdk().receivePayment(ReceivePaymentRequest(method)).paymentRequest + } + + suspend fun prepareSend( + paymentRequest: String, + amountSats: ULong?, + feePolicy: FeePolicy? = null, + ): PrepareSendPaymentResponse = + requireSdk().prepareSendPayment( + PrepareSendPaymentRequest( + paymentRequest = PaymentRequest.Input(input = paymentRequest), + amount = amountSats?.let { BigInteger.valueOf(it.toLong()) }, + tokenIdentifier = null, + conversionOptions = null, + feePolicy = feePolicy, + ), + ) + + suspend fun send(prepared: PrepareSendPaymentResponse): Payment { + val options = when (prepared.paymentMethod) { + is SendPaymentMethod.Bolt11Invoice -> bolt11SendOptions(prefersSpark) + is SendPaymentMethod.BitcoinAddress -> SendPaymentOptions.BitcoinAddress(OnchainConfirmationSpeed.MEDIUM) + else -> null + } + return requireSdk().sendPayment(SendPaymentRequest(prepared, options)).payment + } + + /** The fastest recommended fee rate, in sat/vB, from the SDK's own fee source. */ + suspend fun fastestFeeRate(): ULong = requireSdk().recommendedFees().fastestFee + + /** The half-hour recommended fee rate, in sat/vB, from the SDK's own fee source. */ + suspend fun halfHourFeeRate(): ULong = requireSdk().recommendedFees().halfHourFee + + suspend fun listUnclaimedDeposits(): List = + requireSdk().listUnclaimedDeposits(ListUnclaimedDepositsRequest).deposits + + /** Quotes the early and the standard claim of a deposit; the early quote asks the provider on every call. */ + suspend fun fetchClaimQuote(txid: String, vout: UInt): FetchClaimDepositQuoteResponse = + requireSdk().fetchClaimDepositQuote(FetchClaimDepositQuoteRequest(txid, vout)) + + /** + * Claims a deposit with its own fee ceiling of [maxFeeSats], which the SDK keeps on the deposit, so an early + * claim not offered at this depth is still made once the provider offers it. + */ + suspend fun claimDeposit(txid: String, vout: UInt, maxFeeSats: ULong): ClaimDepositOutcome = + requireSdk().claimDeposit( + ClaimDepositRequest(txid, vout, MaxFee(MaxOnchainFee.Fixed(maxFeeSats), proportionalPpm = null)), + ).outcome + + suspend fun listPayments(): List = requireSdk().listPayments(ListPaymentsRequest()).payments + + /** Exports what a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. */ + suspend fun exportExitState(): String = requireSdk().exportUnilateralExitState().exitState + + /** Merges an exported exit state back in, without contacting the Spark operators. */ + suspend fun importExitState(exitState: String): ImportUnilateralExitStateResponse = + requireSdk().importUnilateralExitState(ImportUnilateralExitStateRequest(exitState)) + + /** The Spark network this build runs on, as exit data backups record it. */ + val networkName: String? get() = sparkNetwork()?.name?.lowercase() + + private fun requireSdk(): BreezSdk = sdk ?: throw SparkError.NotConnected() + + private fun sparkNetwork(): SparkNetwork? = when (Env.network) { + Network.BITCOIN if Env.breezApiKey != null -> SparkNetwork.MAINNET + Network.REGTEST -> SparkNetwork.REGTEST + else -> null + } +} + +sealed class SparkError(message: String, cause: Throwable? = null) : AppError(message, cause) { + class Unsupported : SparkError("Spark is not available on this network or build") + class NotConnected : SparkError("Spark wallet is not connected") + + /** + * Spark refused a Lightning payment before anything left the wallet: it was not connected, could not prepare the + * payment, or its fee was over the caller's limit. A Paykit request or allowance attempt can then end as failed. + */ + class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) +} diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 64a589f578..c0789dd495 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -4,6 +4,7 @@ package to.bitkit.ui import android.Manifest import android.content.Intent import android.os.Build +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box @@ -140,12 +141,21 @@ import to.bitkit.ui.screens.transfer.SavingsAvailabilityScreen import to.bitkit.ui.screens.transfer.SavingsConfirmScreen import to.bitkit.ui.screens.transfer.SavingsIntroScreen import to.bitkit.ui.screens.transfer.SavingsProgressScreen +import to.bitkit.ui.screens.transfer.SettingUpScreen +import to.bitkit.ui.screens.transfer.SparkFundingViewModel +import to.bitkit.ui.screens.transfer.SpendingAmountScreen +import to.bitkit.ui.screens.transfer.SpendingConfirmScreen +import to.bitkit.ui.screens.transfer.SpendingIntroScreen +import to.bitkit.ui.screens.transfer.TransferIntroScreen +import to.bitkit.ui.screens.transfer.TransferLearnMoreScreen import to.bitkit.ui.screens.transfer.external.ExternalAmountScreen import to.bitkit.ui.screens.transfer.external.ExternalConfirmScreen import to.bitkit.ui.screens.transfer.external.ExternalConnectionScreen import to.bitkit.ui.screens.transfer.external.ExternalNodeViewModel import to.bitkit.ui.screens.transfer.external.ExternalSuccessScreen import to.bitkit.ui.screens.transfer.external.LnurlChannelScreen +import to.bitkit.ui.screens.transfer.hardware.SpendingHwSignScreen +import to.bitkit.ui.screens.transfer.hardware.SpendingHwSignedScreen import to.bitkit.ui.screens.trezor.TrezorScreen import to.bitkit.ui.screens.wallets.HardwareWalletScreen import to.bitkit.ui.screens.wallets.HomeScreen @@ -194,6 +204,7 @@ import to.bitkit.ui.settings.lightning.ChannelDetailScreen import to.bitkit.ui.settings.lightning.CloseConnectionScreen import to.bitkit.ui.settings.lightning.LightningConnectionsScreen import to.bitkit.ui.settings.lightning.LightningConnectionsViewModel +import to.bitkit.ui.settings.lightning.SparkDetailScreen import to.bitkit.ui.settings.pin.PinManagementScreen import to.bitkit.ui.settings.quickPay.QuickPayIntroScreen import to.bitkit.ui.settings.quickPay.QuickPaySettingsScreen @@ -1026,6 +1037,34 @@ private fun RootNavHost( navigationWithDefaultTransitions( startDestination = Routes.SavingsIntro, ) { + deepLinkableComposable { + TransferIntroScreen( + onContinueClick = { + navController.navigateToTransferFunding() + settingsViewModel.setHasSeenTransferIntro(true) + }, + onBackClick = { navController.popBackStack() }, + ) + } + deepLinkableComposable { + SpendingIntroScreen( + onContinueClick = { + navController.navigateTo(Routes.SparkFundingNav) + settingsViewModel.setHasSeenSpendingIntro(true) + }, + onBackClick = { navController.popBackStack() }, + ) + } + deepLinkableComposable { entry -> + val walletId = entry.toRoute().walletId + SpendingIntroScreen( + onContinueClick = { + navController.navigateTo(Routes.SpendingAmountHw(walletId)) + settingsViewModel.setHasSeenSpendingIntro(true) + }, + onBackClick = { navController.popBackStack() }, + ) + } deepLinkableComposable { SavingsIntroScreen( onContinueClick = { @@ -1067,11 +1106,105 @@ private fun RootNavHost( ) } deepLinkableComposable { + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() FundingScreen( + canFundWithSpark = sparkState.isReady, + onTransfer = { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) }, + onFund = { + scope.launch { + navController.navigateToHome() + delay(500) // Wait for nav to actually finish + appViewModel.showSheet(Sheet.Receive()) + } + }, onManual = { navController.navigateTo(Routes.ExternalNav) }, onBackClick = { navController.popBackStack() }, ) } + navigationWithDefaultTransitions( + startDestination = Routes.SpendingAmount, + ) { + deepLinkableComposable { + val parentEntry = remember(it) { navController.getBackStackEntry(Routes.SparkFundingNav) } + val connectivityState by appViewModel.isOnline.collectAsStateWithLifecycle() + SpendingAmountScreen( + viewModel = hiltViewModel(parentEntry), + isOffline = connectivityState != ConnectivityState.CONNECTED, + onBackClick = { navController.popBackStack() }, + onQuoteReady = { navController.navigateTo(Routes.SpendingConfirm) }, + ) + } + deepLinkableComposable { entry -> + val walletId = entry.toRoute().walletId + val parentEntry = remember(entry) { navController.getBackStackEntry(Routes.SparkFundingNav) } + val viewModel = hiltViewModel(parentEntry) + val connectivityState by appViewModel.isOnline.collectAsStateWithLifecycle() + LaunchedEffect(walletId) { viewModel.useHardwareWallet(walletId) } + SpendingAmountScreen( + viewModel = viewModel, + isOffline = connectivityState != ConnectivityState.CONNECTED, + onBackClick = { navController.popBackStack() }, + onQuoteReady = { navController.navigateTo(Routes.SpendingHwSign(walletId)) }, + ) + } + composableWithDefaultTransitions { entry -> + val walletId = entry.toRoute().walletId + val parentEntry = remember(entry) { navController.getBackStackEntry(Routes.SparkFundingNav) } + SpendingHwSignScreen( + walletId = walletId, + viewModel = hiltViewModel(parentEntry), + onBackClick = { navController.popBackStack() }, + onLearnMoreClick = { navController.navigateTo(Routes.TransferLearnMore) }, + onSent = { + navController.navigateTo(Routes.SpendingHwSigned) { + popUpTo { inclusive = true } + } + }, + ) + } + composableWithDefaultTransitions { + val parentEntry = remember(it) { navController.getBackStackEntry(Routes.SparkFundingNav) } + SpendingHwSignedScreen( + viewModel = hiltViewModel(parentEntry), + onContinue = { + navController.navigateTo(Routes.SettingUp) { + popUpTo { inclusive = true } + } + }, + onCloseClick = { navController.navigateToHome() }, + ) + } + composableWithDefaultTransitions { + val parentEntry = remember(it) { navController.getBackStackEntry(Routes.SparkFundingNav) } + val connectivityState by appViewModel.isOnline.collectAsStateWithLifecycle() + SpendingConfirmScreen( + viewModel = hiltViewModel(parentEntry), + isOffline = connectivityState != ConnectivityState.CONNECTED, + onBackClick = { navController.popBackStack() }, + onLearnMoreClick = { navController.navigateTo(Routes.TransferLearnMore) }, + onSent = { navController.navigateToSettingUp() }, + ) + } + composableWithDefaultTransitions { + val parentEntry = remember(it) { navController.getBackStackEntry(Routes.SparkFundingNav) } + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + TransferLearnMoreScreen( + viewModel = hiltViewModel(parentEntry), + spendingBalanceSats = sparkState.balanceSats.toLong(), + onBackClick = { navController.popBackStack() }, + onContinueClick = { navController.popBackStack() }, + ) + } + composableWithDefaultTransitions { + val parentEntry = remember(it) { navController.getBackStackEntry(Routes.SparkFundingNav) } + BackHandler { navController.navigateToHome() } + SettingUpScreen( + viewModel = hiltViewModel(parentEntry), + onContinueClick = { navController.navigateToHome() }, + ) + } + } navigationWithDefaultTransitions( startDestination = ExternalConnection(), ) { @@ -1202,6 +1335,8 @@ private fun NavGraphBuilder.home( ) } deepLinkableComposable { + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() val onchainActivities by activityListViewModel.onchainActivities.collectAsStateWithLifecycle() val forceCloseRemainingDuration by appViewModel.forceCloseRemainingDuration.collectAsStateWithLifecycle() @@ -1210,18 +1345,27 @@ private fun NavGraphBuilder.home( onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { navController.navToActivityDetail(it) }, onEmptyActivityRowClick = { appViewModel.showSheet(Sheet.Receive()) }, - onTransferToSpendingClick = { appViewModel.showSheet(Sheet.TransferUnavailable) }, + onTransferToSpendingClick = { + if (sparkState.isReady) { + navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) + } else { + appViewModel.showSheet(Sheet.TransferUnavailable) + } + }, onBackClick = { navController.popBackStack() }, forceCloseRemainingDuration = forceCloseRemainingDuration, ) } deepLinkableComposable { val hasSeenSavingsIntro by settingsViewModel.hasSeenSavingsIntro.collectAsStateWithLifecycle() + val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() val lightningActivities by activityListViewModel.lightningActivities.collectAsStateWithLifecycle() SpendingWalletScreen( channels = lightningState.channels, + hasSparkBalance = sparkState.balanceSats > 0uL, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { navController.navToActivityDetail(it) }, @@ -1233,16 +1377,30 @@ private fun NavGraphBuilder.home( navController.navigateToTransferSavingsAvailability() } }, - onTransferFromSavingsClick = { appViewModel.showSheet(Sheet.TransferUnavailable) }, + onTransferFromSavingsClick = { + if (sparkState.isReady) { + navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) + } else { + appViewModel.showSheet(Sheet.TransferUnavailable) + } + }, onBackClick = { navController.popBackStack() }, ) } deepLinkableComposable { val walletId = it.toRoute().walletId + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() HardwareWalletScreen( walletId = walletId, onActivityItemClick = { navController.navToActivityDetail(it) }, - onTransferToSpendingClick = { appViewModel.showSheet(Sheet.TransferUnavailable) }, + onTransferToSpendingClick = { walletId -> + if (sparkState.isReady) { + navController.navigateToTransferSpendingStart(hasSeenSpendingIntro, walletId) + } else { + appViewModel.showSheet(Sheet.TransferUnavailable) + } + }, onBackClick = { navController.popBackStack() }, ) } @@ -1831,6 +1989,20 @@ private fun NavGraphBuilder.lightningConnections( navController = navController, ) } + deepLinkableComposable { + val hasSeenSavingsIntro = settingsViewModel?.hasSeenSavingsIntro + ?.collectAsStateWithLifecycle()?.value == true + SparkDetailScreen( + onBack = { navController.popBackStack() }, + onTransferToSavings = { + if (hasSeenSavingsIntro) { + navController.navigateToTransferSavingsAvailability() + } else { + navController.navigateToTransferSavingsIntro() + } + }, + ) + } deepLinkableComposable { val route = it.toRoute() CloseConnectionScreen( @@ -2112,6 +2284,29 @@ internal fun receiveSheetPresentationKey(sheet: Sheet.Receive): String = sheet.p fun NavController.navigateToTransferFunding() = navigateTo(Routes.Funding) +fun NavController.navigateToTransferIntro() = navigateTo(Routes.TransferIntro) + +fun NavController.navigateToTransferSpendingStart(hasSeenSpendingIntro: Boolean) = + navigateTo(transferSpendingStartRoute(hasSeenSpendingIntro)) + +internal fun transferSpendingStartRoute(hasSeenSpendingIntro: Boolean): Routes = when { + hasSeenSpendingIntro -> Routes.SparkFundingNav + else -> Routes.SpendingIntro +} + +fun NavController.navigateToTransferSpendingStart(hasSeenSpendingIntro: Boolean, walletId: String) = + navigateTo(transferSpendingStartRoute(hasSeenSpendingIntro, walletId)) + +internal fun transferSpendingStartRoute(hasSeenSpendingIntro: Boolean, walletId: String): Routes = when { + hasSeenSpendingIntro -> Routes.SpendingAmountHw(walletId) + else -> Routes.SpendingIntroHw(walletId) +} + +/** Shows the transfer's progress in place of its confirm screen, so going back cannot swipe it again. */ +fun NavController.navigateToSettingUp() = navigateTo(Routes.SettingUp) { + popUpTo { inclusive = true } +} + fun NavController.navToActivityDetail(activity: Activity) = navigateTo( Routes.ActivityDetail( id = activity.rawId(), @@ -2273,6 +2468,9 @@ sealed interface Routes { @Serializable data class ChannelDetail(val channelId: String) : Routes.DeepLinkable + @Serializable + data object SparkDetail : Routes.DeepLinkable + @Serializable data class CloseConnection(val channelId: String) : Routes.DeepLinkable @@ -2300,6 +2498,15 @@ sealed interface Routes { @Serializable data object TransferRoot : Routes.DeepLinkable + @Serializable + data object TransferIntro : Routes.DeepLinkable + + @Serializable + data object SpendingIntro : Routes.DeepLinkable + + @Serializable + data class SpendingIntroHw(val walletId: String) : Routes.DeepLinkable + @Serializable data object SavingsIntro : Routes.DeepLinkable @@ -2321,6 +2528,30 @@ sealed interface Routes { @Serializable data object ExternalNav : Routes.DeepLinkable + @Serializable + data object SparkFundingNav : Routes.InternalOnly + + @Serializable + data object SpendingAmount : Routes.DeepLinkable + + @Serializable + data class SpendingAmountHw(val walletId: String) : Routes.DeepLinkable + + @Serializable + data class SpendingHwSign(val walletId: String) : Routes.InternalOnly + + @Serializable + data object SpendingHwSigned : Routes.InternalOnly + + @Serializable + data object SpendingConfirm : Routes.InternalOnly + + @Serializable + data object TransferLearnMore : Routes.InternalOnly + + @Serializable + data object SettingUp : Routes.InternalOnly + @Serializable data class ExternalConnection(val scannedNodeUri: String? = null) : Routes.DeepLinkable 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 9f3b092b64..2a56a23f92 100644 --- a/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt +++ b/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt @@ -1,6 +1,7 @@ package to.bitkit.ui.components import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight @@ -17,6 +18,7 @@ fun RowScope.FeeInfo( label: String, amount: Long, modifier: Modifier = Modifier, + prefix: String? = null, ) { Column( modifier = modifier @@ -29,7 +31,10 @@ fun RowScope.FeeInfo( color = Colors.White64, ) Spacer(modifier = Modifier.height(8.dp)) - MoneySSB(sats = amount, showSymbol = true) + Row { + prefix?.let { BodySSB(text = "$it ", color = Colors.White64) } + MoneySSB(sats = amount, showSymbol = true) + } Spacer(modifier = Modifier.weight(1f)) HorizontalDivider(modifier = Modifier.padding(top = 16.dp)) } 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 2b604ebe71..bdcb5d046b 100644 --- a/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt +++ b/app/src/main/java/to/bitkit/ui/components/LightningChannel.kt @@ -39,8 +39,10 @@ fun LightningChannel( modifier: Modifier = Modifier, status: ChannelStatusUi = ChannelStatusUi.PENDING, showLabels: Boolean = false, + showReceiving: Boolean = true, ) { - val spendingColor = if (status == ChannelStatusUi.CLOSED) Colors.Gray5 else Colors.Purple50 + val isEmptySpendingBar = !showReceiving && 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 receivingAvailableColor = if (status == ChannelStatusUi.CLOSED) Colors.Gray3 else Colors.White @@ -58,7 +60,9 @@ fun LightningChannel( modifier = Modifier.fillMaxWidth(), ) { Caption13Up(text = stringResource(R.string.lightning__spending_label), color = Colors.White64) - Caption13Up(text = stringResource(R.string.lightning__receiving_label), color = Colors.White64) + if (showReceiving) { + Caption13Up(text = stringResource(R.string.lightning__receiving_label), color = Colors.White64) + } } Spacer(modifier = Modifier.height(8.dp)) } @@ -78,17 +82,19 @@ fun LightningChannel( color = spendingAvailableColor, ) } - Row(verticalAlignment = CenterVertically) { - Icon( - painter = painterResource(R.drawable.ic_received), - contentDescription = null, - tint = receivingAvailableColor, - modifier = Modifier.size(14.dp) - ) - MoneyCaptionB( - sats = remoteBalance, - color = receivingAvailableColor, - ) + if (showReceiving) { + Row(verticalAlignment = CenterVertically) { + Icon( + painter = painterResource(R.drawable.ic_received), + contentDescription = null, + tint = receivingAvailableColor, + modifier = Modifier.size(14.dp) + ) + MoneyCaptionB( + sats = remoteBalance, + color = receivingAvailableColor, + ) + } } } Spacer(modifier = Modifier.height(8.dp)) @@ -102,16 +108,17 @@ fun LightningChannel( modifier = Modifier .weight(1f) .fillMaxHeight() - .background(spendingColor, RoundedCornerShape(topStart = 8.dp, bottomStart = 8.dp)) + .background(spendingColor, if (showReceiving) SpendingHalfShape else FullBarShape) ) { Box( modifier = Modifier .fillMaxHeight() .fillMaxWidth(spendingAvailableFraction) .align(Alignment.CenterEnd) - .background(spendingAvailableColor, RoundedCornerShape(topStart = 8.dp, bottomStart = 8.dp)) + .background(spendingAvailableColor, if (showReceiving) SpendingHalfShape else FullBarShape) ) } + if (!showReceiving) return@Row Spacer(modifier = Modifier.width(4.dp)) Box( modifier = Modifier @@ -130,6 +137,9 @@ fun LightningChannel( } } +private val SpendingHalfShape = RoundedCornerShape(topStart = 8.dp, bottomStart = 8.dp) +private val FullBarShape = RoundedCornerShape(8.dp) + // region preview @Preview(showBackground = true) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt index 24a4810270..8af2625d6c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt @@ -3,9 +3,16 @@ package to.bitkit.ui.screens.transfer import android.content.Intent import androidx.annotation.DrawableRes import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag @@ -16,12 +23,13 @@ import androidx.compose.ui.unit.dp import androidx.core.net.toUri import to.bitkit.R import to.bitkit.env.Env +import to.bitkit.ui.LocalBalances import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.Display -import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.RectangleButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn @@ -31,48 +39,87 @@ import to.bitkit.ui.utils.withAccent @Composable fun FundingScreen( + canFundWithSpark: Boolean = false, + onTransfer: () -> Unit = {}, + onFund: () -> Unit = {}, onManual: () -> Unit = {}, onBackClick: () -> Unit = {}, ) { val context = LocalContext.current + val hasSavings = LocalBalances.current.maxSendOnchainSats > 0uL + var showNoFundsAlert by remember { mutableStateOf(false) } ScreenColumn { AppTopBar( titleText = stringResource(R.string.lightning__funding__nav_title), onBackClick = onBackClick, actions = { DrawerNavIcon() }, ) - VerticalSpacer(32.dp) - Display( - text = stringResource(R.string.lightning__funding__title).withAccent(accentColor = Colors.Purple), - modifier = Modifier.padding(horizontal = 16.dp), - ) - VerticalSpacer(8.dp) - BodyM( - text = stringResource(R.string.lightning__transfer_unavailable__text), - color = Colors.White64, - modifier = Modifier.padding(horizontal = 16.dp), - ) - VerticalSpacer(32.dp) - RectangleButton( - label = stringResource(R.string.lightning__funding_advanced__button2), - icon = R.drawable.ic_pencil_full, - iconTint = Colors.Purple, - iconSize = 13.37.dp, - onClick = onManual, + Column( modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp) - .testTag("FundManual") - ) - UnavailableOption(R.string.lightning__funding__button1, R.drawable.ic_transfer, 20.dp, "FundTransfer") - UnavailableOption( - R.string.lightning__funding__button_hw, - R.drawable.ic_device_tablet_speaker, - 16.25.dp, - "FundHardware" - ) - UnavailableOption(R.string.lightning__funding__button2, R.drawable.ic_qr_purple, 13.75.dp, "FundReceive") - FillHeight() + .weight(1f) + .verticalScroll(rememberScrollState()) + ) { + VerticalSpacer(32.dp) + Display( + text = stringResource(R.string.lightning__funding__title).withAccent(accentColor = Colors.Purple), + modifier = Modifier.padding(horizontal = 16.dp), + ) + VerticalSpacer(8.dp) + BodyM( + text = stringResource( + if (canFundWithSpark) { + R.string.lightning__funding__text + } else { + R.string.lightning__transfer_unavailable__text + } + ), + color = Colors.White64, + modifier = Modifier.padding(horizontal = 16.dp), + ) + VerticalSpacer(24.dp) + // Spark keeps Spending fundable from savings or another wallet without a channel. + if (canFundWithSpark) { + FundingOption( + R.string.lightning__funding__button1, + R.drawable.ic_transfer, + 20.dp, + "FundTransfer", + { if (hasSavings) onTransfer() else showNoFundsAlert = true }, + ) + FundingOption( + R.string.lightning__funding__button2, + R.drawable.ic_qr_purple, + 13.75.dp, + "FundReceive", + onFund + ) + } + VerticalSpacer(8.dp) + RectangleButton( + label = stringResource(R.string.lightning__funding_advanced__button2), + icon = R.drawable.ic_pencil_full, + iconTint = Colors.Purple, + iconSize = 13.37.dp, + onClick = onManual, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + .testTag("FundManual") + ) + if (!canFundWithSpark) { + FundingOption(R.string.lightning__funding__button1, R.drawable.ic_transfer, 20.dp, "FundTransfer") + } + FundingOption( + R.string.lightning__funding__button_hw, + R.drawable.ic_device_tablet_speaker, + 16.25.dp, + "FundHardware" + ) + if (!canFundWithSpark) { + FundingOption(R.string.lightning__funding__button2, R.drawable.ic_qr_purple, 13.75.dp, "FundReceive") + } + VerticalSpacer(32.dp) + } SecondaryButton( text = stringResource(R.string.common__learn_more), onClick = { @@ -83,15 +130,29 @@ fun FundingScreen( .testTag("FundLearnMore") ) VerticalSpacer(16.dp) + if (showNoFundsAlert) { + AppAlertDialog( + title = stringResource(R.string.lightning__no_funds__title), + text = stringResource(R.string.lightning__no_funds__description), + confirmText = stringResource(R.string.lightning__no_funds__fund_wallet), + confirmTextColor = Colors.Purple, + onConfirm = { + showNoFundsAlert = false + onFund() + }, + onDismiss = { showNoFundsAlert = false }, + ) + } } } @Composable -private fun UnavailableOption( +private fun FundingOption( @StringRes label: Int, @DrawableRes icon: Int, iconSize: Dp, testTag: String, + onClick: (() -> Unit)? = null, ) { VerticalSpacer(8.dp) RectangleButton( @@ -99,8 +160,8 @@ private fun UnavailableOption( icon = icon, iconTint = Colors.Purple, iconSize = iconSize, - enabled = false, - onClick = {}, + enabled = onClick != null, + onClick = { onClick?.invoke() }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) @@ -115,3 +176,11 @@ private fun Preview() { FundingScreen() } } + +@Preview(showSystemUi = true) +@Composable +private fun PreviewSpark() { + AppThemeSurface { + FundingScreen(canFundWithSpark = true) + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt index 1116b50a89..b2c7f99962 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt @@ -27,6 +27,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList +import kotlinx.collections.immutable.toImmutableSet import to.bitkit.R import to.bitkit.ext.amountOnClose import to.bitkit.ext.filterOpen @@ -47,6 +48,7 @@ import to.bitkit.ui.theme.Colors import to.bitkit.ui.transferViewModel import to.bitkit.ui.utils.withAccent import to.bitkit.ui.walletViewModel +import to.bitkit.viewmodels.SavingsSelection @Composable fun SavingsAdvancedScreen( @@ -60,7 +62,11 @@ fun SavingsAdvancedScreen( val lightningState by wallet.lightningState.collectAsStateWithLifecycle() val openChannels = lightningState.channels.filterOpen() + val sparkState by wallet.sparkState.collectAsStateWithLifecycle() + val sparkSats = sparkState.balanceSats + var selectedChannelIds by remember { mutableStateOf(setOf()) } + var isSparkSelected by remember { mutableStateOf(true) } // Select all open channels on init LaunchedEffect(Unit) { @@ -85,13 +91,20 @@ fun SavingsAdvancedScreen( }.toImmutableList() } + val sparkItem = sparkSats.takeIf { it > 0uL }?.let { SparkUiState(balance = it, isSelected = isSparkSelected) } + SavingsAdvancedContent( channelItems = channelItems, + sparkItem = sparkItem, onChannelItemClick = { channelId -> toggleChannel(channelId) }, + onSparkItemClick = { isSparkSelected = !isSparkSelected }, onAmountClick = { currency.switchUnit() }, onContinueClick = { - transfer.setSelectedChannelIds( - selectedChannelIds.takeUnless { it.size == openChannels.size } ?: emptySet() + transfer.setSavingsSelection( + SavingsSelection( + channelIds = selectedChannelIds.takeUnless { it.size == openChannels.size }?.toImmutableSet(), + includesSpark = isSparkSelected, + ) ) onContinueClick() }, @@ -102,12 +115,15 @@ fun SavingsAdvancedScreen( @Composable private fun SavingsAdvancedContent( channelItems: ImmutableList, + sparkItem: SparkUiState? = null, onChannelItemClick: (String) -> Unit = {}, + onSparkItemClick: () -> Unit = {}, onAmountClick: () -> Unit = {}, onContinueClick: () -> Unit = {}, onBackClick: () -> Unit = {}, ) { - val totalAmount = channelItems.filter { it.isSelected }.sumOf { it.balance } + val sparkAmount = sparkItem?.takeIf { it.isSelected }?.balance ?: 0uL + val totalAmount = channelItems.filter { it.isSelected }.sumOf { it.balance } + sparkAmount ScreenColumn { AppTopBar( @@ -132,6 +148,16 @@ private fun SavingsAdvancedContent( LazyColumn( modifier = Modifier.weight(1f) ) { + sparkItem?.let { spark -> + item(key = SPARK_ITEM_KEY) { + ChannelItem( + channelName = stringResource(R.string.lightning__spark), + balanceSat = spark.balance, + iSelected = spark.isSelected, + onClick = onSparkItemClick, + ) + } + } itemsIndexed( items = channelItems.sortedBy { it.channelId }, key = { _, channel -> channel.channelId }, @@ -153,7 +179,7 @@ private fun SavingsAdvancedContent( PrimaryButton( text = stringResource(R.string.common__continue), onClick = onContinueClick, - enabled = channelItems.any { it.isSelected }, + enabled = channelItems.any { it.isSelected } || sparkItem?.isSelected == true, ) Spacer(modifier = Modifier.height(16.dp)) @@ -196,6 +222,14 @@ fun ChannelItem( } } +private const val SPARK_ITEM_KEY = "spark" + +@Immutable +private data class SparkUiState( + val balance: ULong, + val isSelected: Boolean, +) + @Immutable private data class TransferChannelUiState( val channelId: String, @@ -225,6 +259,7 @@ private fun SavingsAdvancedScreenPreview() { isSelected = false, ), ), + sparkItem = SparkUiState(balance = 12_000u, isSelected = true), ) } } diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 4b18c10d88..743cdc390a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -6,15 +6,19 @@ import androidx.compose.animation.fadeOut import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize 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.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -33,10 +37,11 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import org.lightningdevkit.ldknode.ChannelDetails import to.bitkit.R import to.bitkit.ext.amountOnClose import to.bitkit.ext.filterOpen +import to.bitkit.ext.totalNextOutboundHtlcLimitSats +import to.bitkit.models.safe import to.bitkit.ui.components.AmountSlider import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Caption13Up @@ -58,6 +63,7 @@ import to.bitkit.ui.theme.Colors import to.bitkit.ui.transferViewModel import to.bitkit.ui.utils.withAccent import to.bitkit.ui.walletViewModel +import to.bitkit.viewmodels.SavingsSelection import to.bitkit.viewmodels.SavingsSwapQuote import to.bitkit.viewmodels.SavingsTransferMode @@ -75,20 +81,23 @@ fun SavingsConfirmScreen( val lightningState by wallet.lightningState.collectAsStateWithLifecycle() val openChannels = lightningState.channels.filterOpen() - val hasMultiple = openChannels.size > 1 + val sparkState by wallet.sparkState.collectAsStateWithLifecycle() + val sparkSats = sparkState.balanceSats - val selectedChannelIds by transfer.selectedChannelIdsState.collectAsStateWithLifecycle() - val selectedChannels: List? = selectedChannelIds - .takeIf { it.isNotEmpty() } - ?.let { list -> openChannels.filter { channel -> list.contains(channel.channelId) } } + // Spark counts as one more item: the selection list is offered once there are two to choose from. + val hasMultiple = openChannels.size + (if (sparkSats > 0uL) 1 else 0) > 1 - val hasSelected = selectedChannelIds.isNotEmpty() + val selection by transfer.savingsSelection.collectAsStateWithLifecycle() + val hasSelected = !selection.isAll - val channels = selectedChannels ?: openChannels + val channels = selection.channels(openChannels) + val withdrawsSpark = selection.withdrawsSpark(sparkSats) - val amount = channels.sumOf { it.amountOnClose } + val channelsAmount = channels.sumOf { it.amountOnClose } + val sparkAmount = if (withdrawsSpark) sparkSats else 0uL val swapState by transfer.savingsSwapState.collectAsStateWithLifecycle() + val sparkFeeSats by transfer.sparkWithdrawFeeSats.collectAsStateWithLifecycle() // Pull the latest node balances so a just-received payment is reflected in the amounts below. LaunchedEffect(Unit) { @@ -96,13 +105,20 @@ fun SavingsConfirmScreen( } // Present the swap fee before the user commits. Recomputed when the amount changes. - LaunchedEffect(amount) { - if (amount > 0uL) transfer.loadSavingsSwapQuote(amount) + // A zero amount clears an earlier quote, so a Spark-only transfer never swaps channel funds. + LaunchedEffect(channelsAmount) { + transfer.loadSavingsSwapQuote(channelsAmount, channels.totalNextOutboundHtlcLimitSats()) + } + + LaunchedEffect(withdrawsSpark, sparkSats) { + if (withdrawsSpark) transfer.loadSparkWithdrawFee(sparkSats) } Box { SavingsConfirmContent( - fallbackAmount = amount, + fallbackAmount = channelsAmount, + sparkAmount = sparkAmount, + sparkFeeSats = sparkFeeSats.takeIf { withdrawsSpark }, isSwapEnabled = swapState.isSwapEnabled, quote = swapState.quote, isQuoteLoading = swapState.isLoading, @@ -114,13 +130,13 @@ fun SavingsConfirmScreen( onBackClick = onBackClick, onAmountClick = { currency.switchUnit() }, onAdvancedClick = onAdvancedClick, - onSelectAllClick = { transfer.setSelectedChannelIds(emptySet()) }, + onSelectAllClick = { transfer.setSavingsSelection(SavingsSelection()) }, onSwipeConfirm = { - transfer.onTransferToSavingsConfirm(channels) + transfer.onTransferToSavingsConfirm(channels, withdrawsSpark) onConfirm() }, onCloseConfirm = { - transfer.onTransferToSavingsConfirm(channels, SavingsTransferMode.CLOSE) + transfer.onTransferToSavingsConfirm(channels, withdrawsSpark, SavingsTransferMode.CLOSE) onConfirm() }, ) @@ -140,6 +156,8 @@ fun SavingsConfirmScreen( @Composable private fun SavingsConfirmContent( fallbackAmount: ULong, + sparkAmount: ULong, + sparkFeeSats: ULong?, isSwapEnabled: Boolean, quote: SavingsSwapQuote?, isQuoteLoading: Boolean, @@ -156,7 +174,9 @@ private fun SavingsConfirmContent( onCloseConfirm: () -> Unit = {}, ) { val scope = rememberCoroutineScope() - val headlineAmount = quote?.amountSat ?: fallbackAmount + val headlineAmount = (quote?.amountSat ?: fallbackAmount).safe() + sparkAmount.safe() + val sparkReceive = sparkAmount.safe() - (sparkFeeSats ?: 0uL).safe() + val receiveAmount = (quote?.receiveSat ?: 0uL).safe() + sparkReceive.safe() // Only show the swap-pricing spinner while swaps are enabled and a quote is still being fetched; // otherwise the swipe just falls back to closing the channel and there is nothing to wait for. val isPricingSwap = isSwapEnabled && quote == null && isQuoteLoading @@ -170,99 +190,127 @@ private fun SavingsConfirmContent( modifier = Modifier .padding(horizontal = 16.dp) .fillMaxSize() - ) { - VerticalSpacer(32.dp) - Display(text = stringResource(R.string.lightning__transfer__confirm).withAccent()) - VerticalSpacer(32.dp) - - Caption13Up(text = stringResource(R.string.lightning__savings_confirm__label), color = Colors.White64) - VerticalSpacer(8.dp) - MoneyDisplay(sats = headlineAmount.toLong(), onClick = onAmountClick) - - if (quote != null) { - VerticalSpacer(24.dp) - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.height(IntrinsicSize.Min), - ) { - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__network_fee), - amount = quote.networkFeeSat.toLong(), - ) - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__service_fee), - amount = quote.swapFeeSat.toLong(), - ) - } - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.height(IntrinsicSize.Min), - ) { - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__amount), - amount = quote.amountSat.toLong(), - ) - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__receive), - amount = quote.receiveSat.toLong(), - ) - } - - // Adjust how much to move to savings, bounded to a payable range. - if (maxSat > minSat) { - VerticalSpacer(28.dp) - AmountSlider( - value = quote.amountSat.toLong(), - min = minSat.toLong(), - max = maxSat.toLong(), - onValueChange = onAmountChange, - ) - } - } - - if (hasMultiple) { - VerticalSpacer(24.dp) - if (hasSelected) { - PrimaryButton( - text = stringResource(R.string.lightning__savings_confirm__transfer_all), - size = ButtonSize.Small, - fullWidth = false, - onClick = { onSelectAllClick() }, - ) - } else { - PrimaryButton( - text = stringResource(R.string.common__advanced), - size = ButtonSize.Small, - fullWidth = false, - onClick = { onAdvancedClick() }, - ) - } - } - - // Flexible middle: the piggybank fills the remaining space, so it shrinks when the - // fees/slider are shown (no squished buttons) and fills the gap while the quote loads. - Box( + BoxWithConstraints( modifier = Modifier .weight(1f) .fillMaxWidth() - .padding(vertical = 16.dp), - contentAlignment = Alignment.Center, ) { - if (isPricingSwap) { - GradientCircularProgressIndicator( - modifier = Modifier.size(48.dp), - strokeWidth = 3.dp, + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + ) { + VerticalSpacer(32.dp) + Display(text = stringResource(R.string.lightning__transfer__confirm).withAccent()) + VerticalSpacer(32.dp) + + Caption13Up( + text = stringResource(R.string.lightning__savings_confirm__label), + color = Colors.White64, ) - } else { - Image( - painter = painterResource(R.drawable.piggybank), - contentDescription = null, - contentScale = ContentScale.Fit, + VerticalSpacer(8.dp) + MoneyDisplay(sats = headlineAmount.toLong(), onClick = onAmountClick) + + if (quote != null) { + VerticalSpacer(24.dp) + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.height(IntrinsicSize.Min), + ) { + FeeInfo( + label = stringResource(R.string.lightning__savings_confirm__network_fee), + amount = quote.networkFeeSat.toLong(), + ) + FeeInfo( + label = stringResource(R.string.lightning__savings_confirm__service_fee), + amount = quote.swapFeeSat.toLong(), + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.height(IntrinsicSize.Min), + ) { + FeeInfo( + label = stringResource(R.string.lightning__savings_confirm__amount), + amount = headlineAmount.toLong(), + ) + FeeInfo( + label = stringResource(R.string.lightning__savings_confirm__receive), + amount = receiveAmount.toLong(), + ) + } + + // Adjust how much to move to savings, bounded to a payable range. + if (maxSat > minSat) { + VerticalSpacer(28.dp) + AmountSlider( + value = quote.amountSat.toLong(), + min = minSat.toLong(), + max = maxSat.toLong(), + onValueChange = onAmountChange, + ) + } + } + + if (sparkFeeSats != null) { + VerticalSpacer(if (quote != null) 0.dp else 24.dp) + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.height(IntrinsicSize.Min), + ) { + FeeInfo( + label = stringResource(R.string.lightning__savings_confirm__spark_fee), + amount = sparkFeeSats.toLong(), + ) + } + } + + if (hasMultiple) { + VerticalSpacer(24.dp) + if (hasSelected) { + PrimaryButton( + text = stringResource(R.string.lightning__savings_confirm__transfer_all), + size = ButtonSize.Small, + fullWidth = false, + onClick = { onSelectAllClick() }, + ) + } else { + PrimaryButton( + text = stringResource(R.string.common__advanced), + size = ButtonSize.Small, + fullWidth = false, + onClick = { onAdvancedClick() }, + ) + } + } + + // Flexible middle: the piggybank fills the remaining space, so it shrinks when the + // fees/slider are shown (no squished buttons) and fills the gap while the quote loads. + Box( modifier = Modifier - .fillMaxSize() - .graphicsLayer(scaleX = -1f), - ) + .weight(1f) + .fillMaxWidth() + .padding(vertical = 16.dp), + contentAlignment = Alignment.Center, + ) { + if (isPricingSwap) { + GradientCircularProgressIndicator( + modifier = Modifier.size(48.dp), + strokeWidth = 3.dp, + ) + } else { + Image( + painter = painterResource(R.drawable.piggybank), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .fillMaxSize() + .graphicsLayer(scaleX = -1f), + ) + } + } } } @@ -300,6 +348,8 @@ private fun SavingsConfirmScreenPreview() { AppThemeSurface { SavingsConfirmContent( fallbackAmount = 50_123u, + sparkAmount = 12_000u, + sparkFeeSats = 1_470u, isSwapEnabled = true, quote = SavingsSwapQuote( amountSat = 50_123u, diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt index cdf45cacdc..843ae080b3 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt @@ -59,6 +59,26 @@ fun SavingsProgressScreen( var progressState by remember { mutableStateOf(SavingsProgressState.PROGRESS) } val swapResult by transfer.savingsSwapResult.collectAsStateWithLifecycle() + // Spark's withdrawal failed: its balance stayed in Spending, so the transfer is not reported as done. + fun toastSparkFailure(movesChannels: Boolean) { + app.toast( + type = Toast.ToastType.ERROR, + title = resources.getString(R.string.common__error), + description = resources.getString( + if (movesChannels) { + R.string.lightning__savings_spark_failed_channels + } else { + R.string.lightning__savings_spark_failed + } + ), + ) + } + + fun showSparkFailure(movesChannels: Boolean) { + toastSparkFailure(movesChannels) + onTransferUnavailable() + } + // Effect to execute the transfer & update UI LaunchedEffect(Unit) { when (transfer.savingsTransferMode.value) { @@ -73,8 +93,17 @@ fun SavingsProgressScreen( SavingsTransferMode.CLOSE -> runChannelClose( transfer = transfer, wallet = wallet, - onSuccess = { progressState = SavingsProgressState.SUCCESS }, - onInterrupted = { progressState = SavingsProgressState.INTERRUPTED }, + onSuccess = { + if (transfer.isSparkWithdrawFailed.value) { + showSparkFailure(movesChannels = transfer.hasChannelsToClose()) + } else { + progressState = SavingsProgressState.SUCCESS + } + }, + onInterrupted = { + if (transfer.isSparkWithdrawFailed.value) toastSparkFailure(movesChannels = true) + progressState = SavingsProgressState.INTERRUPTED + }, onGiveUp = { app.showSheet(Sheet.ForceTransfer) }, ) } @@ -82,6 +111,11 @@ fun SavingsProgressScreen( LaunchedEffect(swapResult) { when (val result = swapResult) { + is SavingsSwapResult.Success if transfer.isSparkWithdrawFailed.value -> { + wallet.refreshState() + showSparkFailure(movesChannels = true) + } + is SavingsSwapResult.Success -> { wallet.refreshState() progressState = SavingsProgressState.SUCCESS @@ -90,6 +124,11 @@ fun SavingsProgressScreen( // The hold invoice is paid but the on-chain claim has not landed within the wait // window. The claim is auto-broadcast once the lockup appears, so the transfer is // committed and settling; show that honestly instead of a completed success. + SavingsSwapResult.Pending if transfer.isSparkWithdrawFailed.value -> { + wallet.refreshState() + showSparkFailure(movesChannels = true) + } + SavingsSwapResult.Pending -> { wallet.refreshState() progressState = SavingsProgressState.SETTLING @@ -123,11 +162,12 @@ private suspend fun runChannelClose( onInterrupted: () -> Unit, onGiveUp: () -> Unit, ) { + val closesChannels = transfer.hasChannelsToClose() val channelsFailedToCoopClose = transfer.closeSelectedChannels() if (channelsFailedToCoopClose.isEmpty()) { wallet.refreshState() - delay(5000) + if (closesChannels) delay(5000) onSuccess() return } diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt new file mode 100644 index 0000000000..2cfcd3cbfb --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt @@ -0,0 +1,269 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.collections.immutable.persistentListOf +import to.bitkit.R +import to.bitkit.models.formatToModernDisplay +import to.bitkit.repositories.SparkClaimOffer +import to.bitkit.repositories.SparkDepositClaim +import to.bitkit.ui.appViewModel +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +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.screens.transfer.components.ProgressSteps +import to.bitkit.ui.screens.transfer.components.TransferAnimationView +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.localizedRandom +import to.bitkit.ui.utils.withAccent + +/** Confirmations Spark waits for before it adds a deposit by itself. */ +private const val MATURE_CONFIRMATIONS = 3 + +/** About how long [MATURE_CONFIRMATIONS] take. */ +private const val MATURE_MINUTES = 30 + +@Composable +fun SettingUpScreen( + viewModel: SparkFundingViewModel, + onContinueClick: () -> Unit = {}, +) { + val app = appViewModel ?: return + val state by viewModel.uiState.collectAsStateWithLifecycle() + + DisposableEffect(Unit) { + app.enabledTransactionSheet(false) + onDispose { + app.enabledTransactionSheet(true) + } + } + + Content( + claim = state.claim, + onPayClick = viewModel::onPayRepriced, + onWaitClick = viewModel::onWait, + onContinueClick = onContinueClick, + ) +} + +@Composable +private fun Content( + claim: SparkDepositClaim, + onPayClick: () -> Unit = {}, + onWaitClick: () -> Unit = {}, + onContinueClick: () -> Unit = {}, +) { + val inProgress = claim != SparkDepositClaim.Claimed + ScreenColumn( + modifier = Modifier.testTag(if (inProgress) "LightningSettingUp" else "TransferSuccess") + ) { + AppTopBar( + titleText = when { + inProgress -> stringResource(R.string.lightning__transfer__nav_title) + else -> stringResource(R.string.lightning__transfer_success__nav_title) + }, + onBackClick = null, + actions = { DrawerNavIcon() }, + ) + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + ) { + VerticalSpacer(12.dp) + if (inProgress) { + Display( + text = stringResource(R.string.lightning__savings_progress__title) + .withAccent(accentColor = Colors.Purple), + modifier = Modifier.fillMaxWidth(), + ) + VerticalSpacer(8.dp) + BodyM( + text = claimText(claim), + color = Colors.White64, + modifier = Modifier + .fillMaxWidth() + .testTag("SettingUpText") + ) + } else { + Display( + text = stringResource(R.string.lightning__transfer_success__title_spending) + .withAccent(accentColor = Colors.Purple), + modifier = Modifier.fillMaxWidth(), + ) + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.lightning__transfer_success__text_spending), + color = Colors.White64, + modifier = Modifier.fillMaxWidth(), + ) + } + VerticalSpacer(28.dp) + if (inProgress) { + TransferAnimationView( + largeCircleRes = R.drawable.ln_sync_large, + smallCircleRes = R.drawable.ln_sync_small, + modifier = Modifier.weight(1f) + ) + VerticalSpacer(16.dp) + val steps = persistentListOf( + stringResource(R.string.lightning__setting_up__step_sent), + stringResource(R.string.lightning__setting_up__step_seen), + stringResource(R.string.lightning__setting_up__step_adding), + ) + ProgressSteps( + steps = steps, + activeStepIndex = claim.stepIndex(), + modifier = Modifier.align(alignment = Alignment.CenterHorizontally) + ) + VerticalSpacer(16.dp) + } else { + Image( + painter = painterResource(id = R.drawable.check), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .weight(1f) + .padding(16.dp) + ) + } + + if (claim is SparkDepositClaim.Repriced) { + PrimaryButton( + text = stringResource(R.string.lightning__setting_up__pay) + .replace("{amount}", claim.offer.earlyFeeSats.formatToModernDisplay()), + onClick = onPayClick, + modifier = Modifier.testTag("SettingUpPay") + ) + VerticalSpacer(16.dp) + SecondaryButton( + text = stringResource(R.string.lightning__spark_deposit__wait_button), + onClick = onWaitClick, + modifier = Modifier.testTag("SettingUpWait") + ) + } else { + val randomOkText = localizedRandom(R.string.common__ok_random) + PrimaryButton( + text = if (inProgress) stringResource(R.string.lightning__setting_up_button) else randomOkText, + onClick = onContinueClick, + modifier = Modifier.testTag("TransferSuccess-button") + ) + } + VerticalSpacer(16.dp) + } + } +} + +@Composable +private fun claimText(claim: SparkDepositClaim): String = when (claim) { + SparkDepositClaim.Looking -> stringResource(R.string.lightning__spark_deposit__looking) + SparkDepositClaim.Adding, SparkDepositClaim.Claimed -> stringResource(R.string.lightning__spark_deposit__claimed) + is SparkDepositClaim.Repriced -> stringResource(R.string.lightning__setting_up__repriced) + .replace("{amount}", claim.offer.earlyFeeSats.formatToModernDisplay()) + + SparkDepositClaim.Unavailable -> stringResource(R.string.lightning__setting_up__unavailable) + SparkDepositClaim.Later -> stringResource(R.string.lightning__spark_deposit__standard) + .replace("{standard}", MATURE_CONFIRMATIONS.toString()) + .replace("{minutes}", MATURE_MINUTES.toString()) + + SparkDepositClaim.NotSeen -> stringResource(R.string.lightning__setting_up__not_seen) +} + +private fun SparkDepositClaim.stepIndex(): Int = when (this) { + SparkDepositClaim.Looking, SparkDepositClaim.Later, SparkDepositClaim.NotSeen -> 1 + SparkDepositClaim.Adding, is SparkDepositClaim.Repriced, SparkDepositClaim.Unavailable -> 2 + SparkDepositClaim.Claimed -> 3 +} + +private val previewRepriced = SparkDepositClaim.Repriced( + SparkClaimOffer.Choice( + txid = "txid", + vout = 0u, + earlyFeeSats = 1_850uL, + earlyConfirmations = 0u, + standardFeeSats = 198uL, + standardConfirmations = 3u, + ) +) + +@Preview(name = "Looking", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewLooking() { + AppThemeSurface { Content(claim = SparkDepositClaim.Looking) } +} + +@Preview(name = "Looking", showSystemUi = true, showBackground = true, device = NEXUS_5) +@Composable +private fun PreviewLookingSmall() { + AppThemeSurface { Content(claim = SparkDepositClaim.Looking) } +} + +@Preview(name = "Adding", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewAdding() { + AppThemeSurface { Content(claim = SparkDepositClaim.Adding) } +} + +@Preview(name = "Repriced", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewRepriced() { + AppThemeSurface { Content(claim = previewRepriced) } +} + +@Preview(name = "Repriced", showSystemUi = true, showBackground = true, device = NEXUS_5) +@Composable +private fun PreviewRepricedSmall() { + AppThemeSurface { Content(claim = previewRepriced) } +} + +@Preview(name = "Unavailable", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewUnavailable() { + AppThemeSurface { Content(claim = SparkDepositClaim.Unavailable) } +} + +@Preview(name = "Later", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewLater() { + AppThemeSurface { Content(claim = SparkDepositClaim.Later) } +} + +@Preview(name = "Not seen", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewNotSeen() { + AppThemeSurface { Content(claim = SparkDepositClaim.NotSeen) } +} + +@Preview(name = "Success", showSystemUi = true, showBackground = true) +@Composable +private fun PreviewSuccess() { + AppThemeSurface { Content(claim = SparkDepositClaim.Claimed) } +} + +@Preview(name = "Success", showSystemUi = true, showBackground = true, device = NEXUS_5) +@Composable +private fun PreviewSuccessSmall() { + AppThemeSurface { Content(claim = SparkDepositClaim.Claimed) } +} 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 new file mode 100644 index 0000000000..a639272fc7 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt @@ -0,0 +1,454 @@ +package to.bitkit.ui.screens.transfer + +import android.content.Context +import androidx.compose.runtime.Immutable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.synonym.bitkitcore.FeeRates +import dagger.hilt.android.lifecycle.HiltViewModel +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import to.bitkit.R +import to.bitkit.ext.getSatsPerVByteFor +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.BITCOIN_SYMBOL +import to.bitkit.models.PrimaryDisplay +import to.bitkit.models.Toast +import to.bitkit.models.TransactionSpeed +import to.bitkit.models.formatMoney +import to.bitkit.models.formatToModernDisplay +import to.bitkit.models.safe +import to.bitkit.repositories.CurrencyRepo +import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.OnchainSendOutcome +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.repositories.SparkDepositClaim +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.WalletRepo +import to.bitkit.ui.screens.transfer.SparkFundingContract.Quote +import to.bitkit.ui.screens.transfer.SparkFundingContract.SideEffect +import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState +import to.bitkit.ui.screens.wallets.send.HwSendRequest +import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.utils.Logger +import javax.inject.Inject +import kotlin.math.roundToLong + +/** + * Transfer to Spending through Spark: sends savings to the Spark deposit address at the speed the user picks, then + * hands the deposit to [SparkRepo] to claim it Instant or Later. + */ +@HiltViewModel +class SparkFundingViewModel @Inject constructor( + @ApplicationContext private val context: Context, + private val walletRepo: WalletRepo, + private val lightningRepo: LightningRepo, + private val sparkRepo: SparkRepo, + private val currencyRepo: CurrencyRepo, + private val hwWalletRepo: HwWalletRepo, +) : ViewModel() { + companion object { + private const val TAG = "SparkFundingViewModel" + + /** Share of the most Savings can send that the 25% button picks. */ + private const val QUARTER = 0.25 + + /** Fast, so the deposit confirms soon whichever claim speed the user picks. */ + private val SPEED = TransactionSpeed.Fast + } + + private val _uiState = MutableStateFlow(UiState()) + val uiState = _uiState.asStateFlow() + + private val _effects = MutableSharedFlow(extraBufferCapacity = 1) + val effects = _effects.asSharedFlow() + + private var maxJob: Job? = null + private var quoteJob: Job? = null + + /** The fee rates the shown quote was priced at, so the transfer pays exactly what the screen shows. */ + private var quotedFeeRates: FeeRates? = null + + init { + viewModelScope.launch { + lightningRepo.lightningState.map { it.nodeStatus?.isRunning ?: false }.distinctUntilChanged() + .collect { isRunning -> _uiState.update { it.copy(isNodeRunning = isRunning) } } + } + viewModelScope.launch { + walletRepo.balanceState.map { it.maxSendOnchainSats }.distinctUntilChanged().collectLatest { + refreshMax() + } + } + viewModelScope.launch { + sparkRepo.depositClaims.collect { claims -> + _uiState.update { state -> state.copy(claim = state.txid?.let { claims[it] } ?: state.claim) } + } + } + } + + /** Sends from the hardware wallet [walletId] instead of Savings. */ + fun useHardwareWallet(walletId: String) { + if (_uiState.value.hwWalletId == walletId) return + _uiState.update { it.copy(hwWalletId = walletId, isMaxLoading = true) } + refreshMax() + } + + /** Works out the most Savings can send to Spark after the network fee; shown as available and used by Max. */ + fun refreshMax() { + maxJob?.cancel() + maxJob = viewModelScope.launch { + val max = runSuspendCatching { + val address = sparkRepo.depositAddress().getOrThrow() + val feeRates = lightningRepo.getFeeRates().getOrThrow() + _uiState.value.hwWalletId?.let { walletId -> + return@runSuspendCatching hwWalletRepo.maxSpendableFunding( + walletId = walletId, + address = address, + satsPerVByte = feeRates.satsPerVByte(), + ).getOrThrow().toLong() + } + val spendable = spendableSats() + if (spendable == 0uL) return@runSuspendCatching 0L + val fee = lightningRepo.estimateSendAllFee(address = address, speed = SPEED, feeRates = feeRates) + .getOrThrow() + (spendable.safe() - fee.safe()).toLong() + }.getOrElse { + Logger.warn("Failed to estimate the most Spark funding can send", it, context = TAG) + if (_uiState.value.hwWalletId != null) 0L else walletRepo.balanceState.value.maxSendOnchainSats.toLong() + } + _uiState.update { it.copy(maxSats = max, isMaxLoading = false) } + } + } + + fun onAmountChange(sats: Long) { + _uiState.update { it.copy(amountSats = sats, isMax = sats > 0 && sats == it.maxSats) } + } + + fun quarterSats(): Long = _uiState.value.maxSats.let { max -> minOf((max * QUARTER).roundToLong(), max) } + + fun onMaxExceeded() { + toast( + title = R.string.lightning__spending_amount__error_max__title, + description = context.getString(R.string.lightning__spending_amount__error_max__description) + .replace("{amount}", _uiState.value.maxSats.formatToModernDisplay()), + ) + } + + /** Prices the transfer and moves on to the confirm screen when Savings can cover it and Spark can add it. */ + fun onAmountContinue() { + if (_uiState.value.isLoading) return + _uiState.update { it.copy(isLoading = true) } + viewModelScope.launch { + val quote = quote().getOrElse { + Logger.error("Failed to price Spark funding", it, context = TAG) + toastQuoteError() + _uiState.update { state -> state.copy(isLoading = false) } + return@launch + } + _uiState.update { it.copy(isLoading = false) } + when { + !quote.isCovered -> toast( + title = R.string.lightning__spending_amount__error_balance__title, + description = context.getString(R.string.lightning__spending_amount__error_balance__description), + ) + + quote.amountSats <= quote.instantFeeSats -> toast( + title = R.string.lightning__spending_amount__error_min__title, + description = context.getString(R.string.lightning__spending_amount__error_min__description) + .replace("{amount}", quote.instantFeeSats.formatToModernDisplay()), + ) + + else -> { + showQuote(quote) + _effects.emit(SideEffect.AmountReady) + } + } + } + } + + /** Re-prices the confirm screen, so it never shows a stale quote. */ + fun onConfirmAppear() = requote() + + fun onSpeedChange(speed: SparkClaimSpeed) { + if (_uiState.value.isSending) return + _uiState.update { it.copy(speed = speed) } + requote() + } + + private fun requote() { + quoteJob?.cancel() + quoteJob = viewModelScope.launch { + _uiState.update { it.copy(isQuoting = true) } + quote() + .onSuccess { showQuote(it) } + .onFailure { + Logger.error("Failed to re-price Spark funding", it, context = TAG) + toastQuoteError() + } + _uiState.update { it.copy(isQuoting = false) } + } + } + + /** Prices again at swipe time, and asks for another swipe when the transfer got worse since it was shown. */ + fun onConfirm() { + val shown = _uiState.value + val shownQuote = shown.quote ?: return + if (shown.isSending || shown.isQuoting) return + quoteJob?.cancel() + _uiState.update { it.copy(isSending = true) } + viewModelScope.launch { + val quote = quote().getOrElse { + Logger.error("Failed to re-price Spark funding at swipe", it, context = TAG) + toastQuoteError() + _uiState.update { state -> state.copy(isSending = false) } + return@launch + } + showQuote(quote) + if (!quote.isCovered) { + Logger.info("Refused transfer that savings no longer cover", context = TAG) + toast( + title = R.string.lightning__spending_amount__error_balance__title, + description = context.getString(R.string.lightning__spending_amount__error_balance__description), + ) + _uiState.update { it.copy(isSending = false) } + return@launch + } + val totalRise = quote.totalSats - shownQuote.totalSats + val spendingDrop = shownQuote.toSpendingSats(shown.speed) - quote.toSpendingSats(shown.speed) + if (totalRise > 0 || spendingDrop > 0) { + Logger.info("Asking for another swipe, fees rose since shown", context = TAG) + toast( + title = R.string.lightning__spending_confirm__fees_changed_title, + description = context.getString(R.string.lightning__spending_confirm__fees_changed_network) + .replace("{amount}", formatPrimaryAmount(maxOf(totalRise, spendingDrop))), + type = Toast.ToastType.INFO, + ) + _uiState.update { it.copy(isSending = false) } + return@launch + } + val walletId = shown.hwWalletId + if (walletId == null) { + send(quote) + return@launch + } + _uiState.update { it.copy(isSending = false) } + _effects.emit( + SideEffect.SignHw( + HwSendRequest( + walletId = walletId, + address = quote.address, + amountSats = quote.amountSats.toULong(), + satsPerVByte = quotedFeeRates?.satsPerVByte() ?: return@launch, + tags = emptyList(), + isTransfer = true, + ) + ) + ) + } + } + + /** Hands the deposit the hardware wallet broadcast in [txid] to Spark, as [send] does for Savings. */ + fun onHwBroadcast(txid: String, amountSats: ULong) { + val state = _uiState.value + val quote = state.quote ?: return + viewModelScope.launch { + withContext(NonCancellable) { + sparkRepo.onDepositBroadcast(txid, amountSats) + sparkRepo.followDepositClaim(txid, state.speed, quote.instantFeeSats.toULong()) + } + Logger.info("Funded Spark from a hardware wallet with '$amountSats' sats in '$txid'", context = TAG) + _uiState.update { it.copy(txid = txid, claim = sparkRepo.depositClaims.value[txid] ?: it.claim) } + _effects.emit(SideEffect.Sent) + } + } + + private suspend fun send(quote: Quote) { + val state = _uiState.value + runSuspendCatching { + val outcome = lightningRepo.sendOnChain( + address = quote.address, + sats = quote.amountSats.toULong(), + speed = SPEED, + feeRates = quotedFeeRates, + isTransfer = true, + isMaxAmount = state.isMax, + ).getOrThrow() + check(outcome is OnchainSendOutcome.Accepted) { "Spark funding was not accepted: '$outcome'" } + withContext(NonCancellable) { + runSuspendCatching { + lightningRepo.completeAcceptedTransferFollowup(orderId = null, txid = outcome.txid) + }.onFailure { Logger.warn("Failed to finish Spark funding locally", it, context = TAG) } + sparkRepo.onDepositBroadcast(outcome.txid, outcome.amountSats ?: quote.amountSats.toULong()) + sparkRepo.followDepositClaim(outcome.txid, state.speed, quote.instantFeeSats.toULong()) + } + Logger.info("Funded Spark with '${quote.amountSats}' sats in '${outcome.txid}'", context = TAG) + _uiState.update { + it.copy(txid = outcome.txid, claim = sparkRepo.depositClaims.value[outcome.txid] ?: it.claim) + } + _effects.emit(SideEffect.Sent) + }.onFailure { + Logger.error("Failed to fund Spark", it, context = TAG) + toast( + title = R.string.lightning__close_error, + description = context.getString(R.string.wallet__send_error_create_tx), + ) + } + _uiState.update { it.copy(isSending = false) } + } + + fun onPayRepriced() { + val txid = _uiState.value.txid ?: return + sparkRepo.payRepricedClaim(txid) + } + + fun onWait() { + val txid = _uiState.value.txid ?: return + sparkRepo.waitForMatureClaim(txid) + } + + private suspend fun quote(): Result = runSuspendCatching { + val state = _uiState.value + val address = sparkRepo.depositAddress().getOrThrow() + val feeRates = lightningRepo.getFeeRates().getOrThrow() + state.hwWalletId?.let { return@runSuspendCatching hwQuote(it, address, feeRates) } + val spendable = spendableSats() + val networkFee = if (state.isMax) { + lightningRepo.estimateSendAllFee(address = address, speed = SPEED, feeRates = feeRates).getOrThrow() + } else { + lightningRepo.calculateTotalFee( + amountSats = state.amountSats.toULong(), + address = address, + speed = SPEED, + feeRates = feeRates, + ).getOrThrow() + } + val amount = if (state.isMax) (spendable.safe() - networkFee.safe()) else state.amountSats.toULong() + val instantFee = sparkRepo.estimateDepositClaimFeeSats(amount).getOrThrow() + val laterFee = sparkRepo.estimateMatureClaimFeeSats().getOrThrow() + quotedFeeRates = feeRates + Quote( + address = address, + amountSats = amount.toLong(), + networkFeeSats = networkFee.toLong(), + instantFeeSats = instantFee.toLong(), + laterFeeSats = laterFee.toLong(), + spendableSats = spendable.toLong(), + ) + } + + private suspend fun hwQuote(walletId: String, address: String, feeRates: FeeRates): Quote { + val amount = _uiState.value.amountSats.toULong() + val satsPerVByte = feeRates.satsPerVByte() + val max = hwWalletRepo.maxSpendableFunding(walletId, address, satsPerVByte).getOrThrow() + val networkFee = hwWalletRepo.estimateFundingMiningFee(walletId, address, amount, satsPerVByte).getOrThrow() + val instantFee = sparkRepo.estimateDepositClaimFeeSats(amount).getOrThrow() + val laterFee = sparkRepo.estimateMatureClaimFeeSats().getOrThrow() + quotedFeeRates = feeRates + return Quote( + address = address, + amountSats = amount.toLong(), + networkFeeSats = networkFee.toLong(), + instantFeeSats = instantFee.toLong(), + laterFeeSats = laterFee.toLong(), + // Max is what the device can send once its own fee is paid, so it covers any amount up to it. + spendableSats = (max.safe() + networkFee.safe()).toLong(), + ) + } + + private fun FeeRates.satsPerVByte(): ULong = getSatsPerVByteFor(SPEED).toULong() + + private fun showQuote(quote: Quote) { + _uiState.update { it.copy(quote = quote, amountSats = quote.amountSats) } + } + + private suspend fun spendableSats(): ULong = + lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats + + private fun toastQuoteError() = toast( + title = R.string.lightning__spending_confirm__quote_error_title, + description = context.getString(R.string.lightning__spending_confirm__quote_error_text), + ) + + private fun toast(title: Int, description: String, type: Toast.ToastType = Toast.ToastType.WARNING) { + viewModelScope.launch { + ToastEventBus.send( + type = type, + title = context.getString(title), + description = description, + visibilityTime = Toast.VISIBILITY_TIME_SHORT, + ) + } + } + + 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() + return "$BITCOIN_SYMBOL ${sats.formatMoney(state.displayUnit)}" + } +} + +interface SparkFundingContract { + @Immutable + data class UiState( + val isNodeRunning: Boolean = false, + /** The hardware wallet the transfer sends from, or null for Savings. */ + val hwWalletId: String? = null, + val isLoading: Boolean = false, + val isMaxLoading: Boolean = true, + val maxSats: Long = 0, + val amountSats: Long = 0, + val isMax: Boolean = false, + val speed: SparkClaimSpeed = SparkClaimSpeed.Instant, + val quote: Quote? = null, + val isQuoting: Boolean = false, + val isSending: Boolean = false, + val txid: String? = null, + val claim: SparkDepositClaim = SparkDepositClaim.Looking, + ) + + /** What the transfer costs, priced together so the confirm screen's tiles always agree. */ + @Immutable + data class Quote( + val address: String, + val amountSats: Long, + val networkFeeSats: Long, + /** The most an Instant claim may cost: the ceiling the user accepts. */ + val instantFeeSats: Long, + /** What the claim at 3 confirmations costs at the current half-hour fee rate. */ + val laterFeeSats: Long, + val spendableSats: Long, + ) { + val totalSats: Long get() = amountSats + networkFeeSats + + /** Whether Savings can pay the amount and its network fee. */ + val isCovered: Boolean get() = totalSats <= spendableSats + + fun claimFeeSats(speed: SparkClaimSpeed): Long = when (speed) { + SparkClaimSpeed.Instant -> instantFeeSats + SparkClaimSpeed.Later -> laterFeeSats + } + + fun toSpendingSats(speed: SparkClaimSpeed): Long = (amountSats - claimFeeSats(speed)).coerceAtLeast(0) + } + + sealed interface SideEffect { + data object AmountReady : SideEffect + data object Sent : SideEffect + + /** Priced and checked; the hardware wallet signs [request] next. */ + data class SignHw(val request: HwSendRequest) : SideEffect + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt new file mode 100644 index 0000000000..dde1890aee --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt @@ -0,0 +1,327 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +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.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.material3.HorizontalDivider +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.repositories.CurrencyState +import to.bitkit.ui.LocalCurrencies +import to.bitkit.ui.components.ConnectionIssuesView +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.FillWidth +import to.bitkit.ui.components.MoneySSB +import to.bitkit.ui.components.NumberPad +import to.bitkit.ui.components.NumberPadActionButton +import to.bitkit.ui.components.NumberPadTextField +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.SyncNodeView +import to.bitkit.ui.components.Text13Up +import to.bitkit.ui.components.UnitButton +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.screens.transfer.SparkFundingContract.SideEffect +import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import to.bitkit.viewmodels.AmountInputEffect +import to.bitkit.viewmodels.AmountInputViewModel +import to.bitkit.viewmodels.previewAmountInputViewModel + +@Suppress("ViewModelForwarding") +@Composable +fun SpendingAmountScreen( + viewModel: SparkFundingViewModel, + isOffline: Boolean, + onBackClick: () -> Unit = {}, + onQuoteReady: () -> Unit = {}, + currencies: CurrencyState = LocalCurrencies.current, + amountInputViewModel: AmountInputViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val amountUiState by amountInputViewModel.uiState.collectAsStateWithLifecycle() + val currentMaxSats by rememberUpdatedState(uiState.maxSats) + val currentCurrencies by rememberUpdatedState(currencies) + + LaunchedEffect(isOffline) { + viewModel.refreshMax() + } + + LaunchedEffect(amountUiState.sats) { + viewModel.onAmountChange(amountUiState.sats) + } + + LaunchedEffect(viewModel, onQuoteReady) { + viewModel.effects.collect { + if (it == SideEffect.AmountReady) onQuoteReady() + } + } + + LaunchedEffect(Unit) { + amountInputViewModel.effect.collect { + when (it) { + AmountInputEffect.MaxExceeded -> { + amountInputViewModel.setSats(currentMaxSats, currentCurrencies) + viewModel.onMaxExceeded() + } + } + } + } + + Box { + Content( + uiState = uiState, + amountInputViewModel = amountInputViewModel, + currencies = currencies, + onBackClick = onBackClick, + onClickQuarter = { amountInputViewModel.setSats(viewModel.quarterSats(), currencies) }, + onClickMaxAmount = { amountInputViewModel.setSats(uiState.maxSats, currencies) }, + onConfirmAmount = viewModel::onAmountContinue, + ) + AnimatedVisibility( + visible = isOffline, + enter = fadeIn(), + exit = fadeOut(), + ) { + ConnectionIssuesView( + titleText = stringResource(R.string.lightning__transfer__nav_title), + modifier = Modifier.statusBarsPadding() + ) + } + } +} + +@Suppress("ViewModelForwarding") +@Composable +private fun Content( + uiState: UiState, + amountInputViewModel: AmountInputViewModel, + onBackClick: () -> Unit, + onClickQuarter: () -> Unit, + onClickMaxAmount: () -> Unit, + onConfirmAmount: () -> Unit, + currencies: CurrencyState = LocalCurrencies.current, +) { + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__transfer__nav_title), + onBackClick = onBackClick, + actions = { DrawerNavIcon() }, + ) + + if (uiState.isNodeRunning) { + SpendingAmountNodeRunning( + uiState = uiState, + amountInputViewModel = amountInputViewModel, + currencies = currencies, + onClickQuarter = onClickQuarter, + onClickMaxAmount = onClickMaxAmount, + onConfirmAmount = onConfirmAmount, + ) + } else { + SyncNodeView( + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) + } + } +} + +@Suppress("ViewModelForwarding") +@Composable +private fun SpendingAmountNodeRunning( + uiState: UiState, + amountInputViewModel: AmountInputViewModel, + currencies: CurrencyState, + onClickQuarter: () -> Unit, + onClickMaxAmount: () -> Unit, + onConfirmAmount: () -> Unit, +) { + LaunchedEffect(uiState.maxSats, uiState.isMaxLoading) { + if (!uiState.isMaxLoading) amountInputViewModel.setMaxAmount(uiState.maxSats) + } + + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .fillMaxSize() + .testTag(if (uiState.hwWalletId != null) "HardwareTransferAmount" else "SpendingAmount") + ) { + val amountUiState by amountInputViewModel.uiState.collectAsStateWithLifecycle() + val isHardware = uiState.hwWalletId != null + val tag = if (isHardware) "HardwareTransferAmount" else "SpendingAmount" + val isReady = !uiState.isLoading && !uiState.isMaxLoading + val hasFunds = uiState.maxSats > 0 + + VerticalSpacer(32.dp) + + Display( + text = stringResource(R.string.lightning__spending_amount__title) + .withAccent(accentColor = Colors.Purple), + modifier = Modifier.fillMaxWidth() + ) + + VerticalSpacer(32.dp) + + NumberPadTextField( + viewModel = amountInputViewModel, + currencies = currencies, + showSecondaryField = false, + modifier = Modifier + .fillMaxWidth() + .testTag("${tag}NumberField") + ) + + // Keys shrink on short screens, so Continue stays visible below the pad. + Column( + verticalArrangement = Arrangement.Bottom, + modifier = Modifier + .weight(1f) + .fillMaxWidth() + ) { + Row( + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.testTag( + if (isHardware) "HardwareTransferAmountNumberPad" else "SendAmountNumberPad" + ) + ) { + Column { + Text13Up( + text = stringResource(R.string.wallet__send_available), + color = Colors.White64, + modifier = Modifier.testTag("${tag}Available") + ) + VerticalSpacer(8.dp) + MoneySSB( + sats = uiState.maxSats, + showSymbol = true, + modifier = Modifier.testTag("${tag}Unit") + ) + } + FillWidth() + UnitButton( + color = Colors.Purple, + onClick = { amountInputViewModel.switchUnit(currencies) }, + modifier = Modifier.testTag( + if (isHardware) "HardwareTransferAmountUnitButton" else "SpendingNumberPadUnit" + ) + ) + NumberPadActionButton( + text = stringResource(R.string.lightning__spending_amount__quarter), + color = Colors.Purple, + enabled = isReady && hasFunds, + onClick = onClickQuarter, + modifier = Modifier.testTag("${tag}Quarter") + ) + NumberPadActionButton( + text = stringResource(R.string.common__max), + color = Colors.Purple, + enabled = isReady && hasFunds, + onClick = onClickMaxAmount, + modifier = Modifier.testTag("${tag}Max") + ) + } + + HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) + + NumberPad( + viewModel = amountInputViewModel, + currencies = currencies, + enabled = isReady && hasFunds, + modifier = Modifier + .weight(1f) + .heightIn(max = NUMBER_PAD_MAX_HEIGHT) + ) + } + + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onConfirmAmount, + enabled = isReady && amountUiState.sats > 0 && amountUiState.sats <= uiState.maxSats, + isLoading = uiState.isLoading, + modifier = Modifier.testTag("${tag}Continue") + ) + + VerticalSpacer(16.dp) + } +} + +/** The number pad's height at its ideal key size. */ +private val NUMBER_PAD_MAX_HEIGHT = 300.dp + +@Preview(showSystemUi = true) +@Preview(showSystemUi = true, device = "id:pixel_9_pro_xl", name = "Large") +@Preview(showSystemUi = true, device = NEXUS_5, name = "Small") +@Composable +private fun Preview() { + AppThemeSurface { + Content( + uiState = UiState(isNodeRunning = true, isMaxLoading = false, maxSats = 158_234), + amountInputViewModel = previewAmountInputViewModel(), + currencies = CurrencyState(), + onBackClick = {}, + onClickQuarter = {}, + onClickMaxAmount = {}, + onConfirmAmount = {}, + ) + } +} + +@Preview(showSystemUi = true, name = "No funds") +@Composable +private fun PreviewNoFunds() { + AppThemeSurface { + Content( + uiState = UiState(isNodeRunning = true, isMaxLoading = false, maxSats = 0), + amountInputViewModel = previewAmountInputViewModel(), + currencies = CurrencyState(), + onBackClick = {}, + onClickQuarter = {}, + onClickMaxAmount = {}, + onConfirmAmount = {}, + ) + } +} + +@Preview(showSystemUi = true) +@Composable +private fun PreviewInitializing() { + AppThemeSurface { + Content( + uiState = UiState(), + amountInputViewModel = previewAmountInputViewModel(), + currencies = CurrencyState(), + onBackClick = {}, + onClickQuarter = {}, + onClickMaxAmount = {}, + onConfirmAmount = {}, + ) + } +} 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 new file mode 100644 index 0000000000..a5d2e52b50 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingConfirmScreen.kt @@ -0,0 +1,367 @@ +package to.bitkit.ui.screens.transfer + +import androidx.activity.compose.BackHandler +import androidx.annotation.DrawableRes +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +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.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.ui.components.BodyMSB +import to.bitkit.ui.components.BodySSB +import to.bitkit.ui.components.ButtonSize +import to.bitkit.ui.components.ConnectionIssuesView +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.FeeInfo +import to.bitkit.ui.components.FillWidth +import to.bitkit.ui.components.HorizontalSpacer +import to.bitkit.ui.components.MoneySSB +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.SwipeToConfirm +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.screens.transfer.SparkFundingContract.Quote +import to.bitkit.ui.screens.transfer.SparkFundingContract.SideEffect +import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState +import to.bitkit.ui.shared.modifiers.clickableAlpha +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +private const val SWIPE_ROTATION_DEGREES = 14f + +@Composable +fun SpendingConfirmScreen( + viewModel: SparkFundingViewModel, + isOffline: Boolean, + onBackClick: () -> Unit = {}, + onLearnMoreClick: () -> Unit = {}, + onSent: () -> Unit = {}, +) { + val state by viewModel.uiState.collectAsStateWithLifecycle() + + BackHandler(enabled = state.isSending) {} + + LaunchedEffect(Unit) { + viewModel.onConfirmAppear() + } + + LaunchedEffect(viewModel, onSent) { + viewModel.effects.collect { + if (it == SideEffect.Sent) onSent() + } + } + + Box { + Content( + state = state, + onBackClick = { if (!state.isSending) onBackClick() }, + onLearnMoreClick = { if (!state.isSending) onLearnMoreClick() }, + onSpeedChange = viewModel::onSpeedChange, + onConfirm = viewModel::onConfirm, + ) + AnimatedVisibility( + visible = isOffline, + enter = fadeIn(), + exit = fadeOut(), + ) { + ConnectionIssuesView( + titleText = stringResource(R.string.lightning__transfer__nav_title), + modifier = Modifier.statusBarsPadding() + ) + } + } +} + +@Composable +private fun Content( + state: UiState, + onBackClick: () -> Unit = {}, + onLearnMoreClick: () -> Unit = {}, + onSpeedChange: (SparkClaimSpeed) -> Unit = {}, + onConfirm: () -> Unit = {}, +) { + val swipeProgress = remember { mutableFloatStateOf(0f) } + val quote = state.quote + + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__transfer__nav_title), + onBackClick = onBackClick, + actions = { if (!state.isSending) DrawerNavIcon() }, + ) + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .fillMaxSize() + .testTag("SpendingConfirm") + ) { + BoxWithConstraints( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + ) { + VerticalSpacer(32.dp) + Display( + stringResource(R.string.lightning__transfer__confirm).withAccent(accentColor = Colors.Purple) + ) + VerticalSpacer(8.dp) + + SpendingFeeGrid(quote = quote, speed = state.speed) + + VerticalSpacer(16.dp) + + SpendingSpeedRows(quote = quote, speed = state.speed, onSpeedChange = onSpeedChange) + + VerticalSpacer(16.dp) + + PrimaryButton( + text = stringResource(R.string.common__learn_more), + size = ButtonSize.Small, + fullWidth = false, + onClick = onLearnMoreClick, + modifier = Modifier.testTag("SpendingConfirmMore") + ) + + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + Image( + painter = painterResource(id = R.drawable.coin_stack_x), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .padding(horizontal = 44.dp, vertical = 8.dp) + .graphicsLayer { rotationZ = swipeProgress.floatValue * SWIPE_ROTATION_DEGREES } + ) + } + } + } + + val canConfirm = quote != null && quote.toSpendingSats(state.speed) > 0 && !state.isQuoting + SwipeToConfirm( + text = stringResource(R.string.lightning__transfer__swipe), + loading = state.isSending || state.isQuoting || quote == null, + confirmed = state.isSending, + enabled = canConfirm, + color = Colors.Purple, + progress = swipeProgress, + onConfirm = { if (canConfirm) onConfirm() }, + ) + VerticalSpacer(16.dp) + } + } +} + +/** The four fee tiles of a transfer to spending, at the selected claim [speed]. */ +@Composable +internal fun SpendingFeeGrid(quote: Quote?, speed: SparkClaimSpeed, modifier: Modifier = Modifier) { + Column(modifier = modifier) { + val claimPrefix = when (speed) { + SparkClaimSpeed.Instant -> stringResource(R.string.lightning__spending_confirm__up_to) + SparkClaimSpeed.Later -> stringResource(R.string.lightning__spending_confirm__about) + } + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.height(IntrinsicSize.Min) + ) { + FeeInfo( + label = stringResource(R.string.lightning__spending_confirm__network_fee), + amount = quote?.networkFeeSats ?: 0, + modifier = Modifier.testTag("SpendingConfirmNetworkFee") + ) + FeeInfo( + label = stringResource(R.string.lightning__spending_confirm__spending_fee), + amount = quote?.claimFeeSats(speed) ?: 0, + prefix = claimPrefix, + modifier = Modifier.testTag("SpendingConfirmSpendingFee") + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.height(IntrinsicSize.Min) + ) { + FeeInfo( + label = stringResource(R.string.lightning__spending_confirm__amount), + amount = quote?.toSpendingSats(speed) ?: 0, + prefix = claimPrefix.takeIf { speed == SparkClaimSpeed.Later }, + modifier = Modifier.testTag("SpendingConfirmAmount") + ) + FeeInfo( + label = stringResource(R.string.lightning__spending_confirm__total), + amount = quote?.totalSats ?: 0, + modifier = Modifier.testTag("SpendingConfirmTotal") + ) + } + } +} + +/** The Instant and Later rows a transfer to spending picks its claim speed with. */ +@Composable +internal fun SpendingSpeedRows( + quote: Quote?, + speed: SparkClaimSpeed, + onSpeedChange: (SparkClaimSpeed) -> Unit, + modifier: Modifier = Modifier, +) { + Column(modifier = modifier) { + SpeedItem( + title = stringResource(R.string.fee__instant__title), + description = stringResource(R.string.lightning__spending_confirm__instant_text), + feePrefix = stringResource(R.string.lightning__spending_confirm__up_to), + feeSats = quote?.instantFeeSats, + icon = R.drawable.ic_speed_fast, + iconColor = Colors.Purple, + isSelected = speed == SparkClaimSpeed.Instant, + onClick = { onSpeedChange(SparkClaimSpeed.Instant) }, + modifier = Modifier.testTag("SpendingConfirmInstant") + ) + SpeedItem( + title = stringResource(R.string.common__later), + description = stringResource(R.string.lightning__spending_confirm__later_text), + feePrefix = stringResource(R.string.lightning__spending_confirm__about), + feeSats = quote?.laterFeeSats, + icon = R.drawable.ic_speed_normal, + iconColor = Colors.Purple, + isSelected = speed == SparkClaimSpeed.Later, + onClick = { onSpeedChange(SparkClaimSpeed.Later) }, + modifier = Modifier.testTag("SpendingConfirmLater") + ) + HorizontalDivider() + } +} + +@Composable +private fun SpeedItem( + title: String, + description: String, + feePrefix: String, + feeSats: Long?, + @DrawableRes icon: Int, + iconColor: Color, + isSelected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier + .clickableAlpha(onClick = onClick) + .then(if (isSelected) Modifier.background(Colors.White06) else Modifier) + ) { + HorizontalDivider() + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .padding(horizontal = 16.dp) + .height(72.dp) + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = iconColor, + modifier = Modifier.size(32.dp), + ) + HorizontalSpacer(16.dp) + Column { + BodyMSB(title, color = MaterialTheme.colorScheme.primary) + BodySSB(description, color = MaterialTheme.colorScheme.secondary) + } + FillWidth() + if (feeSats != null) { + Row { + BodySSB("$feePrefix ", color = Colors.White64) + MoneySSB(sats = feeSats, showSymbol = true) + } + } + } + } +} + +private val previewQuote = Quote( + address = "bcrt1q", + amountSats = 50_000, + networkFeeSats = 577, + instantFeeSats = 1_350, + laterFeeSats = 198, + spendableSats = 158_234, +) + +@Preview(showSystemUi = true, showBackground = true, name = "Instant") +@Composable +private fun PreviewInstant() { + AppThemeSurface { + Content(state = UiState(amountSats = 50_000, quote = previewQuote)) + } +} + +@Preview(showSystemUi = true, showBackground = true, name = "Later") +@Composable +private fun PreviewLater() { + AppThemeSurface { + Content(state = UiState(amountSats = 50_000, quote = previewQuote, speed = SparkClaimSpeed.Later)) + } +} + +@Preview(showSystemUi = true, showBackground = true, name = "Loading") +@Composable +private fun PreviewLoading() { + AppThemeSurface { + Content(state = UiState(amountSats = 50_000, isQuoting = true)) + } +} + +@Preview(showSystemUi = true, showBackground = true, name = "Small screen", device = NEXUS_5) +@Composable +private fun PreviewSmall() { + AppThemeSurface { + Content(state = UiState(amountSats = 50_000, quote = previewQuote)) + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingIntroScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingIntroScreen.kt new file mode 100644 index 0000000000..7a94031b47 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingIntroScreen.kt @@ -0,0 +1,80 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon +import to.bitkit.ui.shared.util.screen +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +@Composable +fun SpendingIntroScreen( + onContinueClick: () -> Unit = {}, + onBackClick: () -> Unit = {}, +) { + Box( + contentAlignment = Alignment.TopCenter, + modifier = Modifier + .screen() + ) { + Image( + painter = painterResource(id = R.drawable.coin_stack_x), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .padding(top = 130.dp) + .fillMaxWidth() + ) + AppTopBar( + titleText = stringResource(R.string.lightning__transfer__nav_title), + onBackClick = onBackClick, + actions = { DrawerNavIcon() }, + ) + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 32.dp) + .align(Alignment.BottomCenter) + ) { + Display(stringResource(R.string.lightning__spending_intro__title).withAccent(accentColor = Colors.Purple)) + Spacer(modifier = Modifier.height(8.dp)) + BodyM(stringResource(R.string.lightning__spending_intro__text), color = Colors.White64) + + Spacer(modifier = Modifier.height(32.dp)) + PrimaryButton( + text = stringResource(R.string.lightning__spending_intro__button), + onClick = onContinueClick, + modifier = Modifier.testTag("SpendingIntro-button") + ) + Spacer(modifier = Modifier.height(16.dp)) + } + } +} + +@Preview(showSystemUi = true, showBackground = true) +@Composable +private fun SpendingIntroScreenPreview() { + AppThemeSurface { + SpendingIntroScreen() + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/TransferIntroScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/TransferIntroScreen.kt new file mode 100644 index 0000000000..45192970ba --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/TransferIntroScreen.kt @@ -0,0 +1,85 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +@Composable +fun TransferIntroScreen( + onContinueClick: () -> Unit = {}, + onBackClick: () -> Unit, +) { + Box( + contentAlignment = Alignment.TopCenter, + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background) + .systemBarsPadding() + ) { + Image( + painter = painterResource(id = R.drawable.lightning), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .padding(top = 130.dp) + .fillMaxWidth() + ) + AppTopBar( + titleText = null, + onBackClick = onBackClick, + actions = { DrawerNavIcon() }, + ) + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 32.dp) + .align(Alignment.BottomCenter) + ) { + Display(stringResource(R.string.lightning__transfer_intro__title).withAccent(accentColor = Colors.Purple)) + Spacer(modifier = Modifier.height(8.dp)) + BodyM(stringResource(R.string.lightning__transfer_intro__text), color = Colors.White64) + + Spacer(modifier = Modifier.height(32.dp)) + PrimaryButton( + text = stringResource(R.string.lightning__transfer_intro__button), + onClick = onContinueClick, + modifier = Modifier.testTag("TransferIntro-button") + ) + Spacer(modifier = Modifier.height(16.dp)) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + TransferIntroScreen(onBackClick = {}) + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/TransferLearnMoreScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/TransferLearnMoreScreen.kt new file mode 100644 index 0000000000..bba6afc6fe --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/TransferLearnMoreScreen.kt @@ -0,0 +1,112 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.BodyMB +import to.bitkit.ui.components.ChannelStatusUi +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.LightningChannel +import to.bitkit.ui.components.PrimaryButton +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.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +/** Explains Instant and Later, and shows the spending balance this transfer leads to. */ +@Composable +fun TransferLearnMoreScreen( + viewModel: SparkFundingViewModel, + spendingBalanceSats: Long, + onContinueClick: () -> Unit = {}, + onBackClick: () -> Unit = {}, +) { + val state by viewModel.uiState.collectAsStateWithLifecycle() + val toSpending = state.quote?.toSpendingSats(state.speed) ?: 0 + + Content( + balanceSats = spendingBalanceSats + toSpending, + onBackClick = onBackClick, + onContinueClick = onContinueClick, + ) +} + +@Composable +private fun Content( + balanceSats: Long, + onBackClick: () -> Unit = {}, + onContinueClick: () -> Unit = {}, +) { + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__transfer__nav_title), + onBackClick = onBackClick, + actions = { DrawerNavIcon() }, + ) + Column( + modifier = Modifier + .fillMaxWidth() + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp) + ) { + VerticalSpacer(32.dp) + Display( + text = stringResource(R.string.lightning__spending_learn_more__title) + .withAccent(accentColor = Colors.Purple) + ) + VerticalSpacer(8.dp) + BodyM(text = stringResource(R.string.lightning__spending_learn_more__text), color = Colors.White64) + VerticalSpacer(16.dp) + BodyM(text = stringResource(R.string.lightning__spark_trust), color = Colors.White64) + VerticalSpacer(32.dp) + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + BodyMB(text = stringResource(R.string.lightning__spending_label)) + VerticalSpacer(16.dp) + + LightningChannel( + capacity = balanceSats, + localBalance = balanceSats, + remoteBalance = 0L, + status = ChannelStatusUi.OPEN, + showLabels = true, + showReceiving = false, + modifier = Modifier.testTag("TransferLearnMoreBalance") + ) + + VerticalSpacer(32.dp) + PrimaryButton( + text = stringResource(R.string.common__understood), + onClick = onContinueClick, + modifier = Modifier.testTag("LiquidityContinue") + ) + VerticalSpacer(16.dp) + } + } +} + +@Preview(showSystemUi = true) +@Preview(showSystemUi = true, device = NEXUS_5, name = "Small") +@Composable +private fun Preview() { + AppThemeSurface { + Content(balanceSats = 48_650L) + } +} 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 new file mode 100644 index 0000000000..d8702be5b4 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignScreen.kt @@ -0,0 +1,270 @@ +package to.bitkit.ui.screens.transfer.hardware + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.models.HwWalletVendor +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.ui.components.ButtonSize +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.components.illustrationRes +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.screens.transfer.SparkFundingContract.Quote +import to.bitkit.ui.screens.transfer.SparkFundingContract.SideEffect +import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState +import to.bitkit.ui.screens.transfer.SparkFundingViewModel +import to.bitkit.ui.screens.transfer.SpendingFeeGrid +import to.bitkit.ui.screens.transfer.SpendingSpeedRows +import to.bitkit.ui.screens.wallets.send.HwSendRequest +import to.bitkit.ui.screens.wallets.send.HwSendViewModel +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +@Composable +fun SpendingHwSignScreen( + walletId: String, + viewModel: SparkFundingViewModel, + onBackClick: () -> Unit, + onLearnMoreClick: () -> Unit, + onSent: () -> Unit, + hwSendViewModel: HwSendViewModel = hiltViewModel(), +) { + val state by viewModel.uiState.collectAsStateWithLifecycle() + val hwState by hwSendViewModel.uiState.collectAsStateWithLifecycle() + val wallets by hwSendViewModel.wallets.collectAsStateWithLifecycle() + val vendor = remember(wallets, walletId) { + wallets.firstOrNull { it.id == walletId }?.vendor ?: HwWalletVendor.TREZOR + } + var request by remember { mutableStateOf(null) } + val isBusy = state.isSending || hwState.isSigning + + BackHandler(enabled = !hwState.canLeave || state.isSending) {} + + LaunchedEffect(walletId) { + hwSendViewModel.warmUp(walletId) + viewModel.onConfirmAppear() + } + + LaunchedEffect(viewModel, hwSendViewModel) { + viewModel.effects.collect { + when (it) { + is SideEffect.SignHw -> { + request = it.request + hwSendViewModel.signAndBroadcast(it.request) + } + + SideEffect.Sent -> onSent() + SideEffect.AmountReady -> Unit + } + } + } + + LaunchedEffect(hwSendViewModel) { + hwSendViewModel.results.collect { + viewModel.onHwBroadcast(it.txId, it.amountSats) + hwSendViewModel.completeBroadcast() + } + } + + DisposableEffect(hwSendViewModel) { + onDispose { hwSendViewModel.cancel() } + } + + Content( + state = state, + vendor = vendor, + isSigning = isBusy, + hasPendingBroadcast = hwState.hasPendingBroadcast, + onBackClick = { if (hwState.canLeave && !state.isSending) onBackClick() }, + onLearnMoreClick = { if (!isBusy) onLearnMoreClick() }, + onSpeedChange = { if (!isBusy) viewModel.onSpeedChange(it) }, + onOpenConnect = { + // A pending broadcast resumes only for the exact request it was signed for. + val pending = request?.takeIf { hwState.hasPendingBroadcast } + if (pending != null) hwSendViewModel.signAndBroadcast(pending) else viewModel.onConfirm() + }, + ) + + if (hwState.isPassphraseRequired) { + HwPassphrasePromptSheet( + isVerifying = hwState.isVerifyingPassphrase, + onSubmit = { passphrase -> + hwSendViewModel.submitPassphrase( + walletId = walletId, + passphrase = passphrase, + onReady = { request?.let { hwSendViewModel.signAndBroadcast(it) } }, + ) + }, + onDismiss = hwSendViewModel::dismissPassphrase, + ) + } +} + +@Composable +private fun Content( + state: UiState, + vendor: HwWalletVendor = HwWalletVendor.TREZOR, + isSigning: Boolean = false, + hasPendingBroadcast: Boolean = false, + onBackClick: () -> Unit = {}, + onLearnMoreClick: () -> Unit = {}, + onSpeedChange: (SparkClaimSpeed) -> Unit = {}, + onOpenConnect: () -> Unit = {}, +) { + val quote = state.quote + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__transfer__nav_title), + onBackClick = onBackClick, + actions = { if (!isSigning) DrawerNavIcon() }, + ) + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .fillMaxSize() + .testTag("HardwareTransferSign") + ) { + BoxWithConstraints( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + ) { + VerticalSpacer(32.dp) + Display( + text = stringResource( + if (hasPendingBroadcast) { + R.string.lightning__transfer_hw__signed_title + } else { + R.string.lightning__transfer_hw__sign_title + } + ).withAccent(accentColor = Colors.Purple), + modifier = Modifier.fillMaxWidth() + ) + VerticalSpacer(8.dp) + + SpendingFeeGrid(quote = quote, speed = state.speed) + + VerticalSpacer(16.dp) + + SpendingSpeedRows(quote = quote, speed = state.speed, onSpeedChange = onSpeedChange) + + VerticalSpacer(16.dp) + + PrimaryButton( + text = stringResource(R.string.common__learn_more), + size = ButtonSize.Small, + fullWidth = false, + enabled = !isSigning && !hasPendingBroadcast, + onClick = onLearnMoreClick, + modifier = Modifier.testTag("HardwareTransferSignLearnMore") + ) + + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + Image( + painter = painterResource(id = vendor.illustrationRes()), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier.padding(vertical = 8.dp) + ) + } + } + } + + val canSign = quote != null && quote.toSpendingSats(state.speed) > 0 && !state.isQuoting + PrimaryButton( + text = stringResource( + if (hasPendingBroadcast) R.string.common__retry else R.string.lightning__transfer_hw__open_connect + ), + onClick = onOpenConnect, + enabled = canSign && !isSigning, + isLoading = isSigning || state.isQuoting, + modifier = Modifier.testTag("HardwareTransferOpenTrezorConnect") + ) + VerticalSpacer(16.dp) + } + } +} + +private val previewQuote = Quote( + address = "bcrt1q", + amountSats = 50_000, + networkFeeSats = 1_141, + instantFeeSats = 1_350, + laterFeeSats = 198, + spendableSats = 120_000, +) + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content(state = UiState(quote = previewQuote, hwWalletId = "trezor")) + } +} + +@Preview(showSystemUi = true, device = NEXUS_5, name = "Small") +@Composable +private fun PreviewSmall() { + AppThemeSurface { + Content(state = UiState(quote = previewQuote, hwWalletId = "trezor")) + } +} + +@Preview(showSystemUi = true, name = "Signing") +@Composable +private fun PreviewSigning() { + AppThemeSurface { + Content(state = UiState(quote = previewQuote, hwWalletId = "trezor"), isSigning = true) + } +} + +@Preview(showSystemUi = true, name = "Pending broadcast") +@Composable +private fun PreviewPendingBroadcast() { + AppThemeSurface { + Content(state = UiState(quote = previewQuote, hwWalletId = "trezor"), hasPendingBroadcast = true) + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignedScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignedScreen.kt new file mode 100644 index 0000000000..5ef98966a4 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/hardware/SpendingHwSignedScreen.kt @@ -0,0 +1,111 @@ +package to.bitkit.ui.screens.transfer.hardware + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.coroutines.delay +import to.bitkit.R +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.HardwareTransferIllustration +import to.bitkit.ui.components.SIGNED_VISUAL_TOP_RATIO +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.screens.transfer.SparkFundingContract.Quote +import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState +import to.bitkit.ui.screens.transfer.SparkFundingViewModel +import to.bitkit.ui.screens.transfer.SpendingFeeGrid +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import kotlin.time.Duration.Companion.seconds + +/** How long the signed confirmation shows before the transfer's progress takes over. */ +private val SIGNED_AUTO_NAV_DELAY = 1.seconds + +@Composable +fun SpendingHwSignedScreen( + viewModel: SparkFundingViewModel, + onContinue: () -> Unit, + onCloseClick: () -> Unit, +) { + val state by viewModel.uiState.collectAsStateWithLifecycle() + + LaunchedEffect(Unit) { + delay(SIGNED_AUTO_NAV_DELAY) + onContinue() + } + + Content( + state = state, + onBackClick = onCloseClick, + ) +} + +@Composable +private fun Content( + state: UiState, + onBackClick: () -> Unit = {}, +) { + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__transfer__nav_title), + onBackClick = onBackClick, + actions = { DrawerNavIcon() }, + ) + Box(modifier = Modifier.fillMaxSize()) { + HardwareTransferIllustration( + drawableRes = R.drawable.check, + topRatio = SIGNED_VISUAL_TOP_RATIO, + ) + + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .fillMaxSize() + .testTag("HardwareTransferSigned") + ) { + VerticalSpacer(32.dp) + Display( + text = stringResource(R.string.lightning__transfer_hw__signed_title) + .withAccent(accentColor = Colors.Purple), + modifier = Modifier.fillMaxWidth() + ) + VerticalSpacer(16.dp) + + SpendingFeeGrid(quote = state.quote, speed = state.speed) + } + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content( + state = UiState( + quote = Quote( + address = "bcrt1q", + amountSats = 50_000, + networkFeeSats = 1_141, + instantFeeSats = 1_350, + laterFeeSats = 198, + spendableSats = 120_000, + ), + ), + ) + } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt index d398093032..5f23a8830e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt @@ -166,6 +166,8 @@ import to.bitkit.ui.navToActivityDetail import to.bitkit.ui.navigateTo import to.bitkit.ui.navigateToAllActivity import to.bitkit.ui.navigateToProfile +import to.bitkit.ui.navigateToTransferFunding +import to.bitkit.ui.navigateToTransferIntro import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.screens.wallets.activity.components.ActivityListSimple import to.bitkit.ui.screens.wallets.activity.utils.previewActivityItems @@ -237,6 +239,8 @@ fun HomeScreen( ) { val context = LocalContext.current val resources = LocalResources.current + val hasSeenTransferIntro by settingsViewModel.hasSeenTransferIntro.collectAsStateWithLifecycle() + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() val hasSeenShopIntro by settingsViewModel.hasSeenShopIntro.collectAsStateWithLifecycle() val hasSeenProfileIntro by settingsViewModel.hasSeenProfileIntro.collectAsStateWithLifecycle() val profileNavigationScope = rememberCoroutineScope() @@ -312,7 +316,11 @@ fun HomeScreen( appViewModel.showSheet(Sheet.Hardware()) } - Suggestion.LIGHTNING -> appViewModel.showSheet(Sheet.TransferUnavailable) + Suggestion.LIGHTNING -> when { + !sparkState.isReady -> appViewModel.showSheet(Sheet.TransferUnavailable) + !hasSeenTransferIntro -> rootNavController.navigateToTransferIntro() + else -> rootNavController.navigateToTransferFunding() + } Suggestion.BACK_UP -> { appViewModel.showSheet(Sheet.Backup(BackupRoute.Intro)) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt index 2f2a40b2ad..169ae8b03a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/SpendingWalletScreen.kt @@ -69,16 +69,17 @@ fun SpendingWalletScreen( onTransferFromSavingsClick: () -> Unit, onBackClick: () -> Unit, balances: BalanceState = LocalBalances.current, + hasSparkBalance: Boolean = false, ) { val showEmptyState by remember(balances.totalLightningSats, lightningActivities.size) { val hasLnFunds = balances.totalLightningSats == 0uL val hasActivity = lightningActivities.isNotEmpty() mutableStateOf(hasLnFunds && !hasActivity) } - val canTransfer by remember(balances.totalLightningSats, channels.size) { + val canTransfer by remember(balances.totalLightningSats, channels.size, hasSparkBalance) { val hasLnBalance = balances.totalLightningSats > 0uL val hasChannels = channels.isNotEmpty() - mutableStateOf(hasLnBalance && hasChannels) + mutableStateOf(hasLnBalance && (hasChannels || hasSparkBalance)) } val canTransferFromSavings by remember(showEmptyState, balances.totalOnchainSats) { mutableStateOf(showEmptyState && balances.totalOnchainSats > 0uL) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt index 273465d5a0..2131aec56b 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVM.kt @@ -38,6 +38,12 @@ class EditInvoiceVM @Inject constructor( amountSats: ULong, ) { viewModelScope.launch { + if (walletRepo.canReceiveWithSpark()) { + editInvoiceEffect( + EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(ReceiveAdditionalLiquidityAction.None) + ) + return@launch + } _isLoading.update { true } val inboundCapacitySats = walletRepo.inboundLiquiditySats() val action = ReceiveLiquidityDecision.additionalLiquidityAction( diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt index 2b96dce0ba..e7855cca87 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt @@ -122,6 +122,7 @@ fun ReceiveQrScreen( onVerifyHardwareAddress: () -> Unit = {}, showPaymentRequestContacts: Boolean = false, onClickPaymentRequestContacts: () -> Unit = {}, + canReceiveWithSpark: Boolean = false, ) { SetMaxBrightness() @@ -134,8 +135,9 @@ fun ReceiveQrScreen( hasReadyChannels, readyInboundLiquiditySats, walletState.bip21AmountSats, + canReceiveWithSpark, ) { - ReceiveLiquidityDecision.canCreateLightningInvoice( + canReceiveWithSpark || ReceiveLiquidityDecision.canCreateLightningInvoice( hasReadyChannels = hasReadyChannels, inboundCapacitySats = readyInboundLiquiditySats, invoiceAmountSats = walletState.bip21AmountSats, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt index f0de3aaead..11306c9312 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt @@ -84,6 +84,7 @@ fun ReceiveSheet( } var editInvoiceSourceTab by remember { mutableStateOf(ReceiveTab.SAVINGS) } val lightningState: LightningState by wallet.lightningState.collectAsStateWithLifecycle() + val sparkState by wallet.sparkState.collectAsStateWithLifecycle() val paymentRequestTargets by appViewModel.eligiblePaymentRequestTargets.collectAsStateWithLifecycle() val paymentRequestContacts by appViewModel.pubkyContacts.collectAsStateWithLifecycle() var paymentRequestDraft by remember { @@ -148,6 +149,7 @@ fun ReceiveSheet( onUsdtSelected = onUsdtSelected, walletState = walletState, lightningState = lightningState, + canReceiveWithSpark = sparkState.isReady, onClickReceiveCjit = { navController.navigateTo(ReceiveRoute.TransferUnavailable) }, onClickEditInvoice = { editInvoiceSourceTab = it diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 3cd0b4f7d3..709311f041 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -464,7 +464,7 @@ class HwSendViewModel @Inject constructor( amount = request.amountSats, fee = result.miningFeeSats, feeRate = result.feeRate, - isTransfer = false, + isTransfer = request.isTransfer, channelId = null, walletId = request.walletId, ) @@ -584,6 +584,8 @@ data class HwSendRequest( val paymentRequestId: PaykitPaymentRequestId? = null, val paymentIdentity: String? = null, val paymentDeadlineAt: Instant? = null, + /** Marks the payment's activity as a transfer between the user's own balances. */ + val isTransfer: Boolean = false, ) private data class PendingHwSendBroadcast( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/ChannelDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/ChannelDetailScreen.kt index 4ed56e3571..9796edd72b 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/ChannelDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/ChannelDetailScreen.kt @@ -522,14 +522,14 @@ private fun ChannelDetailContent( } @Composable -private fun SectionTitle(text: String) { +internal fun SectionTitle(text: String) { VerticalSpacer(32.dp) Caption13Up(text = text, color = Colors.White64) VerticalSpacer(8.dp) } @Composable -private fun SectionRow( +internal fun SectionRow( name: String, valueContent: @Composable () -> Unit, modifier: Modifier = Modifier, 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 8dc0a62774..e1f37f26b3 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,5 +1,6 @@ package to.bitkit.ui.settings.lightning +import android.content.Intent import androidx.annotation.DrawableRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image @@ -38,6 +39,7 @@ 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 @@ -51,11 +53,13 @@ import to.bitkit.ui.Routes import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.Caption13Up +import to.bitkit.ui.components.CaptionB import to.bitkit.ui.components.ChannelStatusUi import to.bitkit.ui.components.Display import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.GradientCircularProgressIndicator import to.bitkit.ui.components.LightningChannel +import to.bitkit.ui.components.MoneyCaptionB import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.SyncNodeView @@ -70,6 +74,7 @@ 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 @@ -102,6 +107,8 @@ fun LightningConnectionsScreen( onClickChannel = { channelUi -> navController.navigateTo(Routes.ChannelDetail(channelUi.details.channelId)) }, + onClickSpark = { navController.navigateTo(Routes.SparkDetail) }, + onOpenTx = { txId -> context.startActivity(Intent(Intent.ACTION_VIEW, getBlockExplorerUrl(txId).toUri())) }, onRefresh = { viewModel.onPullToRefresh() }, @@ -116,6 +123,8 @@ private fun Content( onClickAddConnection: () -> Unit = {}, onClickExportLogs: () -> Unit = {}, onClickChannel: (ChannelUi) -> Unit = {}, + onClickSpark: () -> Unit = {}, + onOpenTx: (String) -> Unit = {}, onRefresh: () -> Unit = {}, ) { var showClosed by remember { mutableStateOf(false) } @@ -150,7 +159,8 @@ private fun Content( onRefresh = onRefresh, modifier = Modifier.fillMaxSize() ) { - val isEmpty = uiState.openChannels.isEmpty() && + val isEmpty = uiState.spark == null && + uiState.openChannels.isEmpty() && uiState.pendingConnections.isEmpty() && uiState.closedChannels.isEmpty() @@ -161,7 +171,11 @@ private fun Content( .fillMaxSize() ) { VerticalSpacer(16.dp) - LightningBalancesSection(uiState.localBalance, uiState.remoteBalance) + LightningBalancesSection( + uiState.localBalance, + uiState.remoteBalance, + isReceivingUnlimited = uiState.isSparkReceiving + ) HorizontalDivider(modifier = Modifier.padding(top = 16.dp)) EmptyStateContent(modifier = Modifier.weight(1f)) @@ -183,7 +197,11 @@ private fun Content( .verticalScroll(rememberScrollState()) ) { VerticalSpacer(16.dp) - LightningBalancesSection(uiState.localBalance, uiState.remoteBalance) + LightningBalancesSection( + uiState.localBalance, + uiState.remoteBalance, + isReceivingUnlimited = uiState.isSparkReceiving + ) HorizontalDivider(modifier = Modifier.padding(top = 16.dp)) if (!uiState.isNodeRunning) { @@ -191,6 +209,12 @@ private fun Content( 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) @@ -269,7 +293,7 @@ private fun Content( } @Composable -private fun LightningBalancesSection(localBalance: ULong, remoteBalance: ULong) { +private fun LightningBalancesSection(localBalance: ULong, remoteBalance: ULong, isReceivingUnlimited: Boolean = false) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, @@ -285,12 +309,20 @@ private fun LightningBalancesSection(localBalance: ULong, remoteBalance: ULong) balance = remoteBalance, icon = R.drawable.ic_received, color = Colors.White, + // Spark receives without inbound liquidity, so no channel caps receiving. + valueText = stringResource(R.string.lightning__spark_receiving_unlimited).takeIf { isReceivingUnlimited }, ) } } @Composable -private fun BalanceColumn(label: String, balance: ULong, @DrawableRes icon: Int, color: Color) { +private fun BalanceColumn( + label: String, + balance: ULong, + @DrawableRes icon: Int, + color: Color, + valueText: String? = null, +) { Column { Caption13Up(text = label, color = Colors.White64) VerticalSpacer(8.dp) @@ -303,7 +335,7 @@ private fun BalanceColumn(label: String, balance: ULong, @DrawableRes icon: Int, tint = color, modifier = Modifier.size(22.dp) ) - Title(text = balance.toLong().formatToModernDisplay(), color = color) + Title(text = valueText ?: balance.toLong().formatToModernDisplay(), color = color) } } } @@ -374,6 +406,106 @@ private fun ChannelItem( } } +@Composable +private fun SparkItem( + spark: SparkUi, + onClick: () -> Unit, + onOpenTx: (String) -> Unit, +) { + Column( + modifier = Modifier + .fillMaxWidth() + .clickableAlpha { onClick() } + .testTag("SparkConnection") + ) { + VerticalSpacer(16.dp) + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth() + ) { + BodyMSB( + text = stringResource(R.string.lightning__spark_provider_value), + modifier = Modifier.weight(1f) + ) + Icon( + painter = painterResource(R.drawable.ic_chevron_right), + contentDescription = null, + tint = Colors.White64, + modifier = Modifier.size(24.dp) + ) + } + VerticalSpacer(8.dp) + LightningChannel( + capacity = spark.balanceSats.toLong(), + localBalance = spark.balanceSats.toLong(), + remoteBalance = 0L, + status = ChannelStatusUi.OPEN, + showReceiving = false, + ) + 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, + txid: String, + amountSats: ULong, + onOpenTx: (String) -> Unit, + modifier: Modifier = Modifier, + confirmations: UInt? = null, +) { + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + modifier = modifier + .fillMaxWidth() + .padding(top = 12.dp) + .clickableAlpha { onOpenTx(txid) } + ) { + Column(modifier = Modifier.weight(1f)) { + CaptionB(text = title) + CaptionB( + text = txid, + color = Colors.White64, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + } + Column( + horizontalAlignment = Alignment.End, + 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, + ) + } + } + } +} + @Composable private fun SyncingRow(modifier: Modifier = Modifier) { Row( 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 eb8d40dd1a..2687b39880 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 @@ -21,19 +21,26 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event +import org.lightningdevkit.ldknode.Network import org.lightningdevkit.ldknode.OutPoint import to.bitkit.R import to.bitkit.di.BgDispatcher +import to.bitkit.env.Env import to.bitkit.ext.amountOnClose import to.bitkit.ext.calculateRemoteBalance import to.bitkit.ext.createChannelDetails import to.bitkit.ext.filterOpen import to.bitkit.ext.filterPending import to.bitkit.models.Toast +import to.bitkit.models.safe import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LogsRepo +import to.bitkit.repositories.SparkDeposit +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState +import to.bitkit.repositories.SparkWithdrawal import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.Logger import javax.inject.Inject @@ -47,6 +54,7 @@ class LightningConnectionsViewModel @Inject constructor( private val blocktankRepo: BlocktankRepo, private val logsRepo: LogsRepo, private val activityRepo: ActivityRepo, + private val sparkRepo: SparkRepo, ) : ViewModel() { companion object { @@ -92,9 +100,10 @@ class LightningConnectionsViewModel @Inject constructor( combine( lightningRepo.lightningState, lightningRepo.lastKnownChannels, - ) { lightningState, channels -> - lightningState.nodeLifecycleState.isRunning() to channels - }.collect { (isNodeRunning, channels) -> + sparkRepo.state, + ) { lightningState, channels, sparkState -> + Triple(lightningState.nodeLifecycleState.isRunning(), channels, sparkState) + }.collect { (isNodeRunning, channels, sparkState) -> val connectionText = context.getString(R.string.lightning__connection) _uiState.update { @@ -106,8 +115,10 @@ class LightningConnectionsViewModel @Inject constructor( pendingConnections = channels.filterPending() .map { it.mapToUiModel(channels, connectionText) } .reversed().toImmutableList(), - localBalance = calculateLocalBalance(channels), + localBalance = calculateLocalBalance(channels).safe() + sparkState.balanceSats.safe(), remoteBalance = channels.calculateRemoteBalance(), + spark = sparkState.toUi(lightningRepo), + isSparkReceiving = sparkState.isReady, ) } } @@ -141,6 +152,7 @@ class LightningConnectionsViewModel @Inject constructor( } suspend fun refreshObservedState() { + sparkRepo.refreshState() lightningRepo.sync() blocktankRepo.refreshOrders() loadClosedChannels() @@ -217,8 +229,39 @@ data class LightningConnectionsUiState( val closedChannels: ImmutableList = persistentListOf(), val localBalance: ULong = 0u, val remoteBalance: ULong = 0u, + val spark: SparkUi? = null, + val isSparkReceiving: Boolean = false, ) +/** The Spark wallet shown as a connection, present once it holds a balance or a deposit. */ +data class SparkUi( + val balanceSats: ULong, + val deposits: ImmutableList = persistentListOf(), + val withdrawals: ImmutableList = persistentListOf(), +) { + 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, +) + +internal suspend fun SparkState.toUi(lightningRepo: LightningRepo): SparkUi? { + if (!isReady) return null + // On regtest Spark always shows, so testers reach its deposit address to fund it from the faucet. + if (balanceSats == 0uL && deposits.isEmpty() && Env.network != Network.REGTEST) return null + return SparkUi( + balanceSats = balanceSats, + deposits = deposits.map { + SparkDepositUi(it, if (it.isClaimed) null else lightningRepo.onchainConfirmations(it.txid)) + }.toImmutableList(), + withdrawals = withdrawals, + ) +} + data class ChannelUi( val name: String, val details: ChannelDetails, 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 new file mode 100644 index 0000000000..e78fc3abaa --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -0,0 +1,209 @@ +package to.bitkit.ui.settings.lightning + +import android.content.Intent +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +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.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.collections.immutable.persistentListOf +import to.bitkit.R +import to.bitkit.ext.setClipboardText +import to.bitkit.repositories.SparkDeposit +import to.bitkit.repositories.SparkWithdrawal +import to.bitkit.ui.components.BodyS +import to.bitkit.ui.components.CaptionB +import to.bitkit.ui.components.ChannelStatusUi +import to.bitkit.ui.components.LightningChannel +import to.bitkit.ui.components.MoneyCaptionB +import to.bitkit.ui.components.PrimaryButton +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.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.getBlockExplorerUrl + +@Composable +fun SparkDetailScreen( + onBack: () -> Unit, + onTransferToSavings: () -> Unit, + viewModel: SparkDetailViewModel = hiltViewModel(), +) { + val context = LocalContext.current + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + + Content( + uiState = uiState, + onBack = onBack, + onRefresh = viewModel::onPullToRefresh, + onOpenTx = { txId -> context.startActivity(Intent(Intent.ACTION_VIEW, getBlockExplorerUrl(txId).toUri())) }, + onCopyText = { context.setClipboardText(it) }, + onTransferToSavings = onTransferToSavings, + ) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun Content( + uiState: SparkDetailUiState, + onBack: () -> Unit = {}, + onRefresh: () -> Unit = {}, + onOpenTx: (String) -> Unit = {}, + onCopyText: (String) -> Unit = {}, + onTransferToSavings: () -> Unit = {}, +) { + val spark = uiState.spark ?: SparkUi(balanceSats = 0uL) + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark), + onBackClick = onBack, + actions = { DrawerNavIcon() }, + ) + PullToRefreshBox( + isRefreshing = uiState.isRefreshing, + onRefresh = onRefresh, + modifier = Modifier.weight(1f) + ) { + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .testTag("SparkScrollView") + ) { + VerticalSpacer(16.dp) + LightningChannel( + capacity = spark.balanceSats.toLong(), + localBalance = spark.balanceSats.toLong(), + remoteBalance = 0L, + status = ChannelStatusUi.OPEN, + showReceiving = false, + ) + VerticalSpacer(32.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) + + uiState.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"), + ) + } + + 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.withdrawals.isNotEmpty()) { + SectionTitle(stringResource(R.string.lightning__savings_confirm__label)) + spark.withdrawals.forEach { withdrawal -> + SparkTransactionRow( + title = stringResource(R.string.wallet__activity_transfer_to_savings), + txid = withdrawal.txid, + amountSats = withdrawal.amountSats, + onOpenTx = onOpenTx, + modifier = Modifier.testTag("SparkWithdrawal") + ) + SectionRow( + name = stringResource(R.string.wallet__activity_fee), + valueContent = { MoneyCaptionB(sats = withdrawal.feeSats.toLong(), symbol = true) }, + ) + } + } + + VerticalSpacer(32.dp) + } + } + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .navigationBarsPadding() + ) { + PrimaryButton( + text = stringResource(R.string.wallet__transfer_to_savings), + onClick = onTransferToSavings, + enabled = spark.balanceSats > 0uL, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkTransferToSavings") + ) + + VerticalSpacer(16.dp) + } + } +} + +@Preview +@Composable +private fun Preview() { + AppThemeSurface { + Content( + uiState = SparkDetailUiState( + spark = SparkUi( + balanceSats = 35_000uL, + 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)), + ), + ), + ) + } +} 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 new file mode 100644 index 0000000000..ac14080045 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -0,0 +1,64 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.runtime.Immutable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +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.repositories.LightningRepo +import to.bitkit.repositories.SparkRepo +import javax.inject.Inject +import kotlin.time.Duration.Companion.milliseconds + +@HiltViewModel +class SparkDetailViewModel @Inject constructor( + @BgDispatcher private val bgDispatcher: CoroutineDispatcher, + private val lightningRepo: LightningRepo, + private val sparkRepo: SparkRepo, +) : ViewModel() { + private val _uiState = MutableStateFlow(SparkDetailUiState()) + val uiState = _uiState.asStateFlow() + + init { + viewModelScope.launch(bgDispatcher) { + sparkRepo.state.collect { state -> _uiState.update { it.copy(spark = state.toUi(lightningRepo)) } } + } + if (Env.network == Network.REGTEST) { + viewModelScope.launch(bgDispatcher) { + sparkRepo.depositAddress().onSuccess { address -> + _uiState.update { + it.copy( + depositAddress = address + ) + } + } + } + } + } + + fun onPullToRefresh() { + viewModelScope.launch { + _uiState.update { it.copy(isRefreshing = true) } + sparkRepo.refreshState() + _uiState.update { it.copy(spark = sparkRepo.state.value.toUi(lightningRepo)) } + delay(500.milliseconds) + _uiState.update { it.copy(isRefreshing = false) } + } + } +} + +@Immutable +data class SparkDetailUiState( + val spark: SparkUi? = null, + val isRefreshing: Boolean = false, + /** 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/usecases/DeriveBalanceStateUseCase.kt b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt index 8e351ba227..56c740e63f 100644 --- a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt @@ -20,6 +20,7 @@ import to.bitkit.models.safe import to.bitkit.models.toBalance import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.utils.Logger import to.bitkit.utils.jsonLogOf @@ -33,6 +34,7 @@ class DeriveBalanceStateUseCase @Inject constructor( private val transferRepo: TransferRepo, private val settingsStore: SettingsStore, private val hwWalletRepo: HwWalletRepo, + private val sparkRepo: SparkRepo, ) { suspend operator fun invoke(): Result = withContext(bgDispatcher) { runCatching { @@ -50,16 +52,23 @@ class DeriveBalanceStateUseCase @Inject constructor( val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance()) val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe() val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe() - val totalLightningSats = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() + val sparkSats = sparkRepo.state.value.balanceSats + val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() + val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() val balanceState = BalanceState( totalOnchainSats = totalOnchainSats, channelFundableBalance = channelFundableBalance, totalLightningSats = totalLightningSats, - maxSendLightningSats = lightningRepo.getChannels().totalNextOutboundHtlcLimitSats(), + // A payment goes over one rail, so the larger of the two balances caps it; Spark keeps its fee. + maxSendLightningSats = maxOf( + lightningRepo.getChannels().totalNextOutboundHtlcLimitSats(), + sparkRepo.state.value.sendableSats, + ), maxSendOnchainSats = getMaxSendAmount(balanceDetails), balanceInTransferToSavings = toSavingsAmount.safe() - coopCloseSavingsSats.safe(), - balanceInTransferToSpending = pendingChannelsSats, + balanceInTransferToSpending = pendingChannelsSats.safe() + + sparkRepo.state.value.pendingDepositSats.safe(), hardwareWallets = hwWalletRepo.wallets.value.map { it.toBalance() }, ) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 95bcf05879..6fabcf9943 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -773,6 +773,7 @@ class AppViewModel @Inject constructor( observeReceiveSheetInvoice() observeLdkNodeEvents() observeLightningUsableChannels() + observeSparkReady() observePublicPaykitEndpoints() observePublicPaykitInvoiceExpiry() observePrivatePaykitContacts() @@ -850,6 +851,17 @@ class AppViewModel @Inject constructor( } } + private fun observeSparkReady() { + viewModelScope.launch { + lightningRepo.isSparkReady.filter { it }.collect { + refreshPaykitEndpointsAfterChannelAvailabilityChanged( + reason = "spark ready", + forceRefreshLightning = true, + ) + } + } + } + @OptIn(FlowPreview::class) private fun observePublicPaykitEndpoints() { viewModelScope.launch { @@ -1963,6 +1975,15 @@ class AppViewModel @Inject constructor( request, IncomingPaykitPaymentRequestFailureReason.EndpointNotPayable, ) + } else if ( + result != PublicPaykitPaymentResult.WaitingForUpdatedPaymentList && + requestedPaymentRequestId.value == request.id + ) { + finishFailedRequestedPaymentRequestPresentation( + request = request, + reason = result?.incomingPaymentRequestFailureReason + ?: IncomingPaykitPaymentRequestFailureReason.ResolutionFailed, + ) } else { deferPaymentRequestPresentation( request = request, @@ -1985,6 +2006,24 @@ class AppViewModel @Inject constructor( return true } + private fun finishFailedRequestedPaymentRequestPresentation( + request: PaykitPaymentRequest, + reason: IncomingPaykitPaymentRequestFailureReason, + ) { + paykitPaymentRequestDiagnostics.logPresentationRejection(request.counterparty, reason) + val restorePaymentRequestSheet = shouldRestorePaymentRequestSheet + paymentRequestPresentationGeneration++ + clearRequestedPaymentRequest() + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__payment_request), + description = context.getString(R.string.slashtags__error_pay_waiting_msg), + testTag = "PaymentRequestWaitingForDetailsToast", + ) + if (restorePaymentRequestSheet) showSheet(Sheet.PaymentRequests) + completePaymentRequestPresentation(request) + } + private fun finishPrivateLinkPendingPaymentRequestPresentation(request: PaykitPaymentRequest) { paykitPaymentRequestDiagnostics.logPresentationRejection( request.counterparty, @@ -7037,18 +7076,22 @@ class AppViewModel @Inject constructor( paymentDeadlineAt = paymentDeadlineAt, onBeforeSend = onBeforeSend, ).onSuccess { hash -> - // Wait until matching payment event is received (with timeout for hold invoices) - val result = lightningRepo.nodeEvents.watchUntil(LightningRepo.SEND_LN_TIMEOUT) { - when (it) { - is Event.PaymentSuccessful if it.paymentHash == hash -> WatchResult.Complete(Result.success(hash)) - is Event.PaymentFailed if it.paymentHash == hash -> WatchResult.Complete( - Result.failure( - LightningPaymentFailedError(reason = it.reason, paymentRequest = bolt11) - ) - ) + fun outcome(event: Event): Result? = when (event) { + is Event.PaymentSuccessful if event.paymentHash == hash -> Result.success(hash) + is Event.PaymentFailed if event.paymentHash == hash -> Result.failure( + LightningPaymentFailedError(reason = event.reason, paymentRequest = bolt11) + ) - else -> WatchResult.Continue() + else -> null + } + // Wait until matching payment event is received (with timeout for hold invoices) + val result = coroutineScope { + val watch = async(start = CoroutineStart.UNDISPATCHED) { + lightningRepo.nodeEvents.watchUntil(LightningRepo.SEND_LN_TIMEOUT) { + outcome(it)?.let { result -> WatchResult.Complete(result) } ?: WatchResult.Continue() + } } + lightningRepo.settledSparkSendEvent(hash)?.let(::outcome)?.also { watch.cancel() } ?: watch.await() } return result ?: Result.failure(PaymentPendingException(hash)) } diff --git a/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt index 350c2c716b..04605d199f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt @@ -18,6 +18,7 @@ import to.bitkit.models.BackupItemStatus import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.BackupRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkRepo import javax.inject.Inject @HiltViewModel @@ -25,6 +26,7 @@ class BackupsViewModel @Inject constructor( private val cacheStore: CacheStore, private val backupRepo: BackupRepo, private val lightningRepo: LightningRepo, + private val sparkRepo: SparkRepo, ) : ViewModel() { private val _uiState = MutableStateFlow(BackupStatusUiState()) @@ -37,7 +39,10 @@ class BackupsViewModel @Inject constructor( private fun collectState() { viewModelScope.launch { cacheStore.backupStatuses.collect { cachedStatuses -> - val categories = BackupCategory.entries.map { category -> + // Spark's exit data shows only where Spark runs. + val categories = BackupCategory.entries.filter { + it != BackupCategory.SPARK_EXIT || sparkRepo.state.value.isSupported + }.map { category -> val cachedStatus = cachedStatuses[category] ?: BackupItemStatus(synced = 0, required = 1) category.toUiState(cachedStatus) } diff --git a/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt index 2e25889872..16c4935219 100644 --- a/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt @@ -133,6 +133,24 @@ class SettingsViewModel @Inject constructor( } } + val hasSeenSpendingIntro = settingsStore.data.map { it.hasSeenSpendingIntro } + .asStateFlow(initialValue = false) + + fun setHasSeenSpendingIntro(value: Boolean) { + viewModelScope.launch { + settingsStore.update { it.copy(hasSeenSpendingIntro = value) } + } + } + + val hasSeenTransferIntro = settingsStore.data.map { it.hasSeenTransferIntro } + .asStateFlow(initialValue = false) + + fun setHasSeenTransferIntro(value: Boolean) { + viewModelScope.launch { + settingsStore.update { it.copy(hasSeenTransferIntro = value) } + } + } + val hasSeenSavingsIntro = settingsStore.data.map { it.hasSeenSavingsIntro } .asStateFlow(initialValue = false) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 2c9afacd1f..b11f8cc82c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -8,6 +8,7 @@ import com.synonym.bitkitcore.BoltzPairInfo import com.synonym.bitkitcore.BoltzSwapEvent import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.collections.immutable.ImmutableSet import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job @@ -36,8 +37,8 @@ import to.bitkit.ext.toUserMessage import to.bitkit.models.Toast import to.bitkit.models.TransferType import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo -import to.bitkit.repositories.WalletRepo import to.bitkit.services.BoltzService import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.Logger @@ -56,17 +57,24 @@ const val GIVE_UP_MS = 30 * 60 * 1000L // 30 minutes in ms class TransferViewModel @Inject constructor( @ApplicationContext private val context: Context, private val lightningRepo: LightningRepo, - private val walletRepo: WalletRepo, private val transferRepo: TransferRepo, private val boltzService: BoltzService, + private val sparkRepo: SparkRepo, private val clock: Clock, ) : ViewModel() { private val _isForceTransferLoading = MutableStateFlow(false) val isForceTransferLoading = _isForceTransferLoading.asStateFlow() - private val _selectedChannelIdsState = MutableStateFlow>(emptySet()) - val selectedChannelIdsState = _selectedChannelIdsState.asStateFlow() + private val _savingsSelection = MutableStateFlow(SavingsSelection()) + val savingsSelection = _savingsSelection.asStateFlow() + + private val _sparkWithdrawFeeSats = MutableStateFlow(null) + val sparkWithdrawFeeSats = _sparkWithdrawFeeSats.asStateFlow() + + private var sparkFeeJob: Job? = null + private var sparkFeeBalanceSats: ULong? = null + private var sparkAddress: String? = null private val isNodeRunning = lightningRepo.lightningState.map { it.nodeStatus?.isRunning ?: false } .stateIn(viewModelScope, SharingStarted.Lazily, false) @@ -74,6 +82,11 @@ class TransferViewModel @Inject constructor( // region Savings private var channelsToClose = emptyList() + private var withdrawsSpark = false + + /** Spark's part of the last Transfer to Savings failed, so its balance stayed in Spending. */ + private val _isSparkWithdrawFailed = MutableStateFlow(false) + val isSparkWithdrawFailed = _isSparkWithdrawFailed.asStateFlow() /** * How the LN -> onchain "transfer to savings" is executed. Closing a channel is the @@ -107,10 +120,16 @@ class TransferViewModel @Inject constructor( * thing that unlocks the swap, so every failure simply leaves it null and the transfer * falls back to closing a channel. * Cancels any in-flight quote so a slower earlier request cannot overwrite a newer one. + * [channelSendableSat] is what the selected channels can send, so Spark's balance never sizes the swap. */ - fun loadSavingsSwapQuote(requestedSat: ULong) { + fun loadSavingsSwapQuote(requestedSat: ULong, channelSendableSat: ULong) { if (!boltzService.isSwapSupported) return savingsSwapQuoteJob?.cancel() + if (requestedSat == 0uL) { + pendingSwapAmountSat = 0uL + _savingsSwapState.update { it.copy(isLoading = false, quote = null, minSat = 0uL, maxSat = 0uL) } + return + } savingsSwapQuoteJob = viewModelScope.launch { val isSwapEnabled = boltzService.isSwapEnabled() _savingsSwapState.update { it.copy(isSwapEnabled = isSwapEnabled) } @@ -134,7 +153,7 @@ class TransferViewModel @Inject constructor( // Reserve headroom for Lightning routing fees. Paying an invoice for 100% of // outbound capacity leaves nothing for fees and fails with RouteNotFound, so cap // the swap at outbound minus ~1% (with a small floor). - val spendable = walletRepo.balanceState.value.maxSendLightningSats.toLong() + val spendable = channelSendableSat.toLong() val routingReserve = (spendable / 100).coerceAtLeast(MIN_LN_ROUTING_FEE_RESERVE_SATS) val sendable = (spendable - routingReserve).coerceAtLeast(0).toULong() val maxSat = minOf(requestedSat, limits.maximalSat, sendable) @@ -200,6 +219,7 @@ class TransferViewModel @Inject constructor( fun startSavingsSwap() { if (savingsSwapJob?.isActive == true || _savingsSwapResult.value != null) return savingsSwapJob = viewModelScope.launch { + if (withdrawsSpark) withdrawSparkToSavings() val result = executeSavingsSwap() _savingsSwapResult.update { result } } @@ -279,8 +299,35 @@ class TransferViewModel @Inject constructor( return SavingsSwapResult.Failure(event.reason.toUserMessage(context)) } - fun setSelectedChannelIds(channelIds: Set) { - _selectedChannelIdsState.update { channelIds } + fun setSavingsSelection(selection: SavingsSelection) { + _savingsSelection.update { selection } + } + + /** Prices Spark's withdrawal to savings for the confirm screen; null until priced or when it can't be. */ + fun loadSparkWithdrawFee(balanceSats: ULong) { + val isPriced = sparkFeeJob?.isActive == true || _sparkWithdrawFeeSats.value != null + if (balanceSats == sparkFeeBalanceSats && isPriced) return + sparkFeeJob?.cancel() + sparkFeeBalanceSats = balanceSats + _sparkWithdrawFeeSats.update { null } + sparkFeeJob = viewModelScope.launch { + val address = sparkWithdrawAddress() ?: return@launch + val result = withTimeoutOrNull(SWAP_QUOTE_TIMEOUT) { sparkRepo.estimateWithdrawAllFeeSats(address) } + if (result == null) Logger.warn("Timed out estimating Spark withdrawal fee", context = TAG) + result + ?.onSuccess { fee -> _sparkWithdrawFeeSats.update { fee } } + ?.onFailure { Logger.warn("Failed to estimate Spark withdrawal fee", it, context = TAG) } + if (result?.isSuccess != true) sparkFeeBalanceSats = null + } + } + + /** One Savings address for Spark's withdrawal, priced on the confirm screen and then paid to. */ + private suspend fun sparkWithdrawAddress(): String? { + sparkAddress?.let { return it } + return lightningRepo.newAddress() + .onFailure { Logger.error("Failed to get address for Spark withdrawal", it, context = TAG) } + .getOrNull() + ?.also { sparkAddress = it } } /** @@ -290,22 +337,53 @@ class TransferViewModel @Inject constructor( */ fun onTransferToSavingsConfirm( channels: List, - mode: SavingsTransferMode = resolveSavingsTransferMode(), + withdrawSpark: Boolean, + mode: SavingsTransferMode = resolveSavingsTransferMode(channels), ) { _savingsTransferMode.update { mode } // Drop any outcome from an earlier attempt so the progress screen cannot act on it. _savingsSwapResult.update { null } - _selectedChannelIdsState.update { emptySet() } + _isSparkWithdrawFailed.update { false } + _savingsSelection.update { SavingsSelection() } channelsToClose = channels + withdrawsSpark = withdrawSpark } - private fun resolveSavingsTransferMode(): SavingsTransferMode = - if (_savingsSwapState.value.quote != null) SavingsTransferMode.SWAP else SavingsTransferMode.CLOSE + private fun resolveSavingsTransferMode(channels: List): SavingsTransferMode = + if (channels.isNotEmpty() && _savingsSwapState.value.quote != null) { + SavingsTransferMode.SWAP + } else { + SavingsTransferMode.CLOSE + } - /** Closes the channels selected earlier, pending closure */ - suspend fun closeSelectedChannels() = closeChannels(channelsToClose) + /** Whether Transfer to Savings closes channels, rather than only withdrawing Spark's balance. */ + fun hasChannelsToClose(): Boolean = channelsToClose.isNotEmpty() + + /** Withdraws Spark's balance when selected, then closes the channels selected earlier, pending closure */ + suspend fun closeSelectedChannels(): List { + if (withdrawsSpark) withdrawSparkToSavings() + return closeChannels(channelsToClose) + } + + private suspend fun withdrawSparkToSavings() { + sparkFeeJob?.join() + val balance = sparkRepo.state.value.balanceSats + if (balance == 0uL) return + val address = sparkWithdrawAddress() + if (address == null) { + _isSparkWithdrawFailed.update { true } + return + } + sparkRepo.withdrawAll(address) + .onSuccess { + sparkAddress = null + sparkFeeBalanceSats = null + } + .onFailure { _isSparkWithdrawFailed.update { true } } + } private suspend fun closeChannels(channels: List): List { + if (channels.isEmpty()) return emptyList() lightningRepo.awaitPeerConnected() val channelsFailedToClose = coroutineScope { channels.map { channel -> @@ -445,6 +523,23 @@ class TransferViewModel @Inject constructor( } } +/** + * What Transfer to Savings moves: the open channels picked in [channelIds], null for all of them, and whether + * Spark's balance goes too. The default moves everything. + */ +@Immutable +data class SavingsSelection( + val channelIds: ImmutableSet? = null, + val includesSpark: Boolean = true, +) { + val isAll: Boolean get() = channelIds == null && includesSpark + + fun channels(openChannels: List): List = + channelIds?.let { ids -> openChannels.filter { it.channelId in ids } } ?: openChannels + + fun withdrawsSpark(sparkSats: ULong): Boolean = includesSpark && sparkSats > 0uL +} + /** Whether a transfer to savings swaps funds out or closes a channel (default). */ enum class SavingsTransferMode { SWAP, CLOSE } diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index d482e991b4..7de4230089 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -50,6 +50,7 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.NodeStartYieldedToStopError import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.RecoveryModeError +import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo import to.bitkit.repositories.WipeInProgressError @@ -80,6 +81,7 @@ class WalletViewModel @Inject constructor( private val connectivityRepo: ConnectivityRepo, private val boltzService: BoltzService, private val connectionRecovery: WalletConnectionRecovery, + sparkRepo: SparkRepo, ) : ViewModel() { companion object { private const val TAG = "WalletViewModel" @@ -99,6 +101,7 @@ class WalletViewModel @Inject constructor( } val lightningState = lightningRepo.lightningState + val sparkState = sparkRepo.state val walletState = walletRepo.walletState val balanceState = walletRepo.balanceState diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c8973f2586..39227d7601 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -158,6 +158,7 @@ استخدم محفظة أخرى تحويل من محفظة الأجهزة رصيد الإنفاق + أسهل خيار هو استخدام مدخرات Bitkit الخاصة بك أو إرسال بيتكوين من محفظة مختلفة. موّل <accent>رصيد الإنفاق</accent> إعداد يدوي السعة الواردة @@ -168,6 +169,9 @@ ارتفاع أرشفة مراقب القناة حد HTLC الصادر التالي الحد الأدنى لـ HTLC الصادر التالي + قبل أن تتمكن من تحويل الأموال من رصيد مدخراتك، تحتاج إلى إرسال Bitcoin إلى محفظة Bitkit الخاصة بك. + تمويل المحفظة + لا توجد أموال متاحة معرّف عقدة LDK عقدة Lightning وقت مزامنة محفظة Lightning @@ -206,16 +210,56 @@ يرجى الانتظار، جارٍ تحويل أموالك. يجب أن يستغرق هذا <accent>±10 ثوانٍ.</accent> الأموال\n<accent>قيد التحويل</accent> وقت مزامنة درجات تحديد المسار + لم يرَ Spark تحويلك بعد. يُضاف بعد 3 تأكيدات؛ يمكنك مغادرة هذه الشاشة. + ادفع ₿ {amount} + أصبح الفوري يكلّف الآن ₿ {amount}. ادفعه، أو انتظر 3 تأكيدات، نحو 30 دقيقة، برسوم أقل. + جارٍ الإضافة إلى الإنفاق + رآه Spark + تم إرسال التحويل + الفوري غير متاح لهذا التحويل. يضيفه Spark إلى رصيد الإنفاق بعد 3 تأكيدات، نحو 30 دقيقة. + متابعة استخدام Bitkit + Spark + رسوم المطالبة + %1$d/3 تأكيدات + إيداع + يضيفه Spark إلى رصيد الإنفاق. + بانتظار أن يرى Spark تحويلك. + يضيفه Spark إلى رصيد الإنفاق بعد {standard} تأكيدات، أي بعد نحو {minutes} دقيقة. + انتظر + إيداعات تمت المطالبة بها + إيداعات قيد التنفيذ + المزوّد + Spark عبر Breez + بلا حد + يُحفظ هذا الرصيد على Spark الذي تديره Lightspark وBreez وFlashnet. يبقى آمنًا ما دام أحدهم على الأقل يتصرف بأمانة. يمكنهم إيقاف الوصول مؤقتًا، والخروج من دونهم يتطلب خروجًا على السلسلة. قابل للإنفاق على السلسلة الإنفاق + لا تكفي مدخراتك لتغطية هذا التحويل ورسومه. جرّب مبلغًا أصغر. + المدخرات غير كافية المبلغ الذي يمكنك تحويله إلى رصيد الإنفاق محدود حاليًا بـ ₿ {amount}. الحد الأقصى لرصيد الإنفاق + حوّل أكثر من ₿ {amount} لتغطية رسوم إضافته إلى رصيد الإنفاق. + المبلغ صغير جدًا 25% + تحويل\n<accent>إلى الإنفاق</accent> إلى الإنفاق + الرسوم أعلى بمقدار {amount} لأن معدلات الرسوم أو رصيد مدخراتك تغيّر أثناء وجودك في هذه الشاشة. اسحب مرة أخرى للتأكيد. + تغيّرت الرسوم + جاهز خلال دقائق + بعد 3 تأكيدات، نحو 30 دقيقة رسوم الخدمة رسوم الشبكة + تعذّر على Bitkit الحصول على الرسوم الحالية لهذا التحويل. تحقق من اتصالك وحاول مرة أخرى. + الرسوم غير متاحة + رسوم الإنفاق الإجمالي + حتى + ابدأ + حوّل الأموال إلى رصيد الإنفاق للاستمتاع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. + تحويل\n<accent>إلى الإنفاق</accent> رصيد الإنفاق + يدفع الفوري للمزوّد لإضافة تحويلك إلى رصيد الإنفاق قبل تأكيده، عادةً خلال دقائق.\n\nأما لاحقًا فينتظر 3 تأكيدات، نحو 30 دقيقة، برسوم أقل. + Transfer\n<accent>speed</accent> الحالة الدعم إجمالي احتياطي قنوات Anchor @@ -226,10 +270,16 @@ يرجى\n<accent>التأكيد</accent> تحويل الأموال اسحب للتحويل + فتح Trezor Connect جارٍ التحويل + ابدأ + موّل رصيد الإنفاق للاستمتاع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. + رصيد\n<accent>الإنفاق</accent> نجح التحويل تم تحويل أموالك. يمكنك استخدام هذه الأموال فورًا. + تم تحويل أموالك ورصيد الإنفاق جاهز للاستخدام. تم نقل الأموال\n<accent>إلى المدخرات</accent> + تم نقل الأموال\n<accent>إلى الإنفاق</accent> يرجى الانتظار حتى يتصل Bitkit بشبكة الدفع (±10 ثوانٍ). يرجى الانتظار حتى يتصل Bitkit بشبكة البيتكوين (±10 ثوانٍ). أرصدة المحفظة @@ -528,6 +578,7 @@ جهات الاتصال الملف الشخصي الإعدادات + بيانات الخروج من Spark العلامات سجل المعاملات التعزيزات والتحويلات @@ -1209,11 +1260,16 @@ رسوم الشبكة ستستلم رسوم الخدمة + رسوم Spark بدأ التحويل وهو <accent>قيد التسوية على السلسلة</accent>. سيتم تحديث رصيد مدخراتك تلقائيًا عند اكتماله. التحويل\n<accent>في الطريق</accent> + تعذّر نقل رصيد Spark إلى المدخرات ويبقى في رصيد الإنفاق. + تعذّر نقل رصيد Spark إلى المدخرات ويبقى في رصيد الإنفاق. اتصالاتك قيد النقل إلى المدخرات. <accent>جارٍ الاتصال</accent>\nبالشبكة يرجى إعادة توصيل جهازك، يبدو أنه غير متصل بهاتفك. إعادة توصيل الجهاز + وقّع باستخدام\n<accent>جهازك</accent> + تم توقيع\n<accent>المعاملة</accent> التحويل جاهز خلال %s التحويل غير متاح لم تعد التحويلات التلقائية إلى رصيد الإنفاق متاحة. استخدم عقدتك الخاصة، أو أنشئ اتصالًا مع مزوّد آخر. 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 f62df577aa..dac1da7456 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -165,6 +165,7 @@ Usar Otra Billetera Transferir desde billetera HW Saldo de gastos + La forma más fácil es usar tus ahorros de Bitkit o enviar bitcoin desde una billetera diferente. Fondee su <accent>saldo de gastos</accent> Configuración Manual Capacidad entrante @@ -175,6 +176,9 @@ Altura de archivo del monitor de canal Límite del próximo HTLC saliente Mínimo del próximo HTLC saliente + Para transferir fondos a su saldo de ahorros, primero tiene que enviar bitcoin a su billetera Bitkit. + Financiar billetera + Sin fondos disponibles ID del nodo LDK Nodo Lightning Hora de sincronización de billetera Lightning @@ -213,16 +217,56 @@ Espera un momento, tu transferencia está en proceso. Tomará aproximadamente <accent>10 segundos.</accent> Fondos\n<accent>en proceso</accent> Hora de sincronización de puntuaciones de ruta + Spark todavía no vio tu transferencia. Se agrega después de 3 confirmaciones; puedes salir de esta pantalla. + Pagar ₿ {amount} + Instantáneo ahora cuesta ₿ {amount}. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Agregando a gastos + Visto por Spark + Transferencia enviada + Instantáneo no está disponible para esta transferencia. Spark la agrega a tu saldo para gastos después de 3 confirmaciones, unos 30 minutos. + Continuar Usando Bitkit + Spark + Comisión de reclamo + %1$d/3 confirmaciones + Depósito + Spark lo está agregando a tu saldo de gastos. + Esperando a que Spark vea tu transferencia. + Spark lo agrega a tu saldo de gastos después de {standard} confirmaciones, en unos {minutes} minutos. + Esperar + Depósitos reclamados + Depósitos en curso + 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. Gastable onchain Gasto + Sus ahorros no alcanzan para cubrir esta transferencia y sus comisiones. Intente con un monto menor. + Ahorros insuficientes El monto que puedes transferir a tu saldo para gastar está limitado a ₿ {amount}. Saldo máximo de gastos + Transfiere más de ₿ {amount} para cubrir las comisiones de agregarlo a tu saldo para gastos. + Monto demasiado bajo 25% + Transferir\n<accent>a gastos</accent> Hacia Gastos + Las comisiones son {amount} más altas porque las tarifas o su saldo de ahorros cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. + Las comisiones cambiaron + Listo en unos minutos + Después de 3 confirmaciones, unos 30 minutos Comisión de servicio Comisiones de red + Bitkit no pudo obtener las comisiones actuales de esta transferencia. Revisa tu conexión e inténtalo de nuevo. + Comisiones no disponibles + Comisión de gastos Total + hasta + Empezar + Transfiera fondos a su saldo de gastos para disfrutar de transacciones baratas e instantáneas con amigos y comercios. + Transferir\n<accent>a gastos</accent> Saldo para gastos + Instantáneo le paga al proveedor para agregar tu transferencia a tu saldo para gastos antes de que se confirme, normalmente en unos minutos.\n\nDespués espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Transfer\n<accent>speed</accent> Estatus Soporte Reserva total de canales ancla @@ -233,10 +277,16 @@ Por favor,\n<accent>confirme</accent> Transferir fondos Desliza para enviar + Abrir Trezor Connect TRANSFERENCIA EN PROGRESO + Empezar + Fondee el saldo de gastos para disfrutar de transacciones baratas e instantáneas con amigos y comercios. + Saldo de\n<accent>Gasto</accent> Transferencia exitosa Sus fondos han sido transferidos. Podrá utilizar estos fondos inmediatamente. + Tus fondos han sido transferidos y tu saldo para gastar está listo para usarse. Fondos movidos\n<accent>a gastos</accent> + Fondos movidos\n<accent>a gastos</accent> Por favor, espere a que Bitkit se conecte a la red de pagos (±10 seg.). Por favor, espere a que Bitkit se conecte a la red bitcoin (±10 seg.). Saldos de billetera @@ -549,6 +599,7 @@ Contactos Perfil Ajustes + Datos de salida de Spark Etiquetas Registro de transacciones Impulsos y transferencias @@ -1239,11 +1290,16 @@ Comisión de red Recibirá Comisión de servicio + Comisión de Spark Su transferencia se inició y se está <accent>liquidando onchain</accent>. Su saldo de ahorros se actualizará automáticamente cuando termine. Transferencia\n<accent>en camino</accent> + Tu saldo de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. + Tu saldo de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. <accent>Conectando</accent>\na la red Vuelva a conectar su dispositivo de hardware; parece que está desconectado de su teléfono. Reconectar dispositivo de hardware + Firme con\n<accent>su dispositivo</accent> + Transacción\n<accent>firmada</accent> TRANSFERENCIA LISTA EN %s Transferencia no disponible Las transferencias automáticas a tu saldo de gasto ya no están disponibles. Usa tu propio nodo o configura una conexión con otro proveedor. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index f87eac631f..334505505c 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -162,6 +162,7 @@ Utilitza un altre moneder Transferir des del moneder HW Balanç de despesa + La forma més fàcil és utilitzar els teus estalvis de Bitkit o enviar bitcoin des d\'una altra cartera. Finança el teu <accent>saldo de despesa</accent> Configuració manual Capacitat d\'entrada @@ -172,6 +173,9 @@ Alçada d\'arxiu del monitor de canal Límit del pròxim HTLC de sortida Mínim del pròxim HTLC de sortida + Abans de poder transferir fons del teu saldo d\'estalvis, has d\'enviar bitcoin a la teva cartera Bitkit. + Finançar cartera + No hi ha fons disponibles ID de Node LDK Node de Lightning Temps de sincronització de la cartera Lightning @@ -210,16 +214,56 @@ Si us plau, espera, la transferència de fons està en curs. Hauria de trigar <accent>±10 segons.</accent> Fons\n<accent>en transferència</accent> Temps de sincronització de puntuacions de rutes + Spark encara no ha vist la teva transferència. S\'afegeix després de 3 confirmacions; pots sortir d\'aquesta pantalla. + Paga ₿ {amount} + Instant ara costa ₿ {amount}. Paga-ho o espera 3 confirmacions, uns 30 minuts, amb una comissió més baixa. + Afegint a despesa + Vist per Spark + Transferència enviada + Instant no està disponible per a aquesta transferència. Spark l\'afegeix al teu saldo de despesa després de 3 confirmacions, uns 30 minuts. + Continua utilitzant Bitkit + Spark + Comissió de reclamació + %1$d/3 confirmacions + Dipòsit + Spark ho està afegint al teu saldo de despeses. + Esperant que Spark vegi la teva transferència. + Spark ho afegeix al teu saldo de despeses després de {standard} confirmacions, d\'aquí a uns {minutes} minuts. + Espera + Dipòsits reclamats + Dipòsits en curs + 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. Gastable Onchain Despesa + Els teus estalvis no poden cobrir aquesta transferència i les seves tarifes. Prova un import més petit. + Estalvis insuficients L\'import que pots transferir al teu saldo de despesa està limitat a ₿ {amount}. Màxim del saldo de despesa + Transfereix més de ₿ {amount} perquè cobreixi les comissions d\'afegir-ho al teu saldo de despesa. + Import massa baix 25% + Transferir\n<accent>a despesa</accent> A despesa + Les tarifes són {amount} més altes perquè les taxes de tarifa o el teu saldo d\'estalvis han canviat mentre eres en aquesta pantalla. Torna a desplaçar per confirmar. + Les tarifes han canviat + A punt en pocs minuts + Després de 3 confirmacions, uns 30 minuts Tarifes de servei Tarifes de xarxa + Bitkit no ha pogut obtenir les comissions actuals d\'aquesta transferència. Comprova la connexió i torna-ho a provar. + Comissions no disponibles + Comissió de despesa Total + fins a + Començar + Transfereix fons al teu saldo de despesa per gaudir de transaccions instantànies i barates amb amics, família i comerciants. + Transferir\n<accent>a despesa</accent> Saldo de despesa + Instant paga el proveïdor per afegir la teva transferència al saldo de despesa abans que es confirmi, normalment en pocs minuts.\n\nDesprés espera 3 confirmacions, uns 30 minuts, amb una comissió més baixa. + Transfer\n<accent>speed</accent> Estat Suport Reserva total de canals Anchor @@ -230,10 +274,16 @@ Si us plau\n<accent>confirma</accent> Transferir fons Desplaçar per Transferir + Obrir Trezor Connect TRANSFERÈNCIA EN CURS + Començar + Finança el teu saldo de despesa per gaudir de transaccions instantànies i barates amb amics, família i comerciants. + Saldo de\n<accent>despesa</accent> Transferència realitzada Els teus fons han estat transferits. Pots utilitzar aquests fons immediatament. + Els teus fons han estat transferits i el teu saldo de despesa està llest per usar. Fons moguts\n<accent>a estalvis</accent> + Fons moguts\n<accent>a despesa</accent> Si us plau, espereu que Bitkit es connecti a la xarxa de pagament (±10 segons). Si us plau, espereu que Bitkit es connecti a la xarxa bitcoin (±10 segons). Saldos de la cartera @@ -543,6 +593,7 @@ Contactes Perfil Configuracions + Dades de sortida de Spark Etiquetes Registre de transaccions Impulsos i transferències @@ -1233,11 +1284,16 @@ Tarifa de xarxa Rebràs Tarifa de servei + Tarifa de Spark La teva transferència s\'ha iniciat i <accent>s\'està liquidant onchain</accent>. El teu saldo d\'estalvis s\'actualitzarà automàticament quan es completi. Transferència\n<accent>en camí</accent> + El saldo de Spark no s\'ha pogut moure a estalvis i es queda al saldo de despesa. + El saldo de Spark no s\'ha pogut moure a estalvis i es queda al saldo de despesa. Les teves connexions s\'estan movent a estalvis. <accent>Connectant</accent>\na la xarxa Torna a connectar el teu dispositiu de maquinari; sembla que s\'ha desconnectat del telèfon. Torna a connectar el dispositiu + Signa amb\n<accent>el teu dispositiu</accent> + Transacció\n<accent>signada</accent> TRANSFERÈNCIA LLESTA EN %s Transferència no disponible Les transferències automàtiques al teu saldo de despesa ja no estan disponibles. Fes servir el teu propi node o configura una connexió amb un altre proveïdor. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index a6b2454328..91f4805c90 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -165,6 +165,7 @@ Použijte jinou peněženku Převod z HW peněženky Dostupný zůstatek + Nejjednodušší možností je použít úspory z Bitkitu nebo poslat bitcoin z jiné peněženky. Navyšte svůj <accent>disponibilní zůstatek</accent> Manuální nastavení Příchozí kapacita @@ -175,6 +176,9 @@ Archivní výška monitoru kanálu Limit dalšího odchozího HTLC Min dalšího odchozího HTLC + Než budete moci převést prostředky ze svého zůstatku na spořicím účtu, musíte poslat bitcoiny do peněženky Bitkit. + Financovat peněženku + Žádné dostupné prostředky ID uzlu LDK Lightning uzel Čas synchronizace Lightning peněženky @@ -213,16 +217,56 @@ Počkejte prosím, probíhá převod finančních prostředků. To by mělo trvat <accent>±10 sekund.</accent> Finanční prostředky\n<accent>v převodu</accent> Čas synchronizace skóre hledání cest + Spark tvůj převod zatím neviděl. Připíše se po 3 potvrzeních; tuto obrazovku můžeš opustit. + Zaplatit ₿ {amount} + Okamžitě nyní stojí ₿ {amount}. Zaplať, nebo počkej na 3 potvrzení, asi 30 minut, s nižším poplatkem. + Přidávání do výdajů + Viděno Sparkem + Převod odeslán + Okamžitě není pro tento převod dostupné. Spark ho přidá do tvého zůstatku pro výdaje po 3 potvrzeních, asi za 30 minut. + Pokračujte v používání Bitkit + Spark + Poplatek za připsání + %1$d/3 potvrzení + Vklad + Spark ji připisuje na váš zůstatek k utrácení. + Čekáme, až Spark uvidí váš převod. + Spark ji připíše na váš zůstatek k utrácení po {standard} potvrzeních, asi za {minutes} minut. + Počkat + Připsané vklady + Probíhající vklady + 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. Utratitelné onchain Útraty + Vaše úspory nepokryjí tento převod a jeho poplatky. Zkuste menší částku. + Nedostatečné úspory Částka, kterou můžete převést na svůj disponibilní zůstatek, je v současné době omezena na ₿ {amount}. Maximální disponibilní zůstatek + Převeď více než ₿ {amount}, aby to pokrylo poplatky za přidání do zůstatku pro výdaje. + Příliš malá částka 25% + Převést\n<accent>do výdajů</accent> Do výdajů + Poplatky jsou o {amount} vyšší, protože se během zobrazení této obrazovky změnily sazby poplatků nebo zůstatek vašich úspor. Pro potvrzení přejeďte znovu. + Poplatky se změnily + Hotovo za pár minut + Po 3 potvrzeních, asi 30 minut Poplatky za služby Síťové poplatky + Bitkit nedokázal získat aktuální poplatky za tento převod. Zkontroluj připojení a zkus to znovu. + Poplatky nedostupné + Poplatek za výdaje Celkem + až + Začít + Převeďte peníze na svůj disponibilní zůstatek a využívejte okamžité a levné transakce s přáteli, rodinou a obchodníky. + Převést\n<accent>do výdajů</accent> Disponibilní zůstatek + Okamžitě platí poskytovateli za přidání převodu do zůstatku pro výdaje ještě před potvrzením, obvykle během pár minut.\n\nPozději čeká na 3 potvrzení, asi 30 minut, s nižším poplatkem. + Transfer\n<accent>speed</accent> Status Podpora Celková rezerva kotevních kanálů @@ -233,10 +277,16 @@ Prosím,\n<accent>potvrďte</accent> Převést prostředky Přejeďte prstem k provedení převodu + Otevřít Trezor Connect PŘEVOD PROBÍHÁ + Začít + Navyšte svůj disponibilní zůstatek a užívejte si okamžité a levné transakce s přáteli, rodinou a obchodníky. + Disponibilní\n<accent>Zůstatek</accent> Přenos úspěšný Vaše prostředky byly převedeny. Tyto prostředky můžete okamžitě použít. + Vaše prostředky byly převedeny a disponibilní zůstatek je připraven k použití. Prostředky převedeny\n<accent>do úspor</accent> + Prostředky převedeny\n<accent>do výdajů</accent> Prosím vyčkejte, až se Bitkit připojí k platební síti (±10 sekund). Prosím vyčkejte, až se Bitkit připojí k síti bitcoin (±10 sekund). Zůstatky peněženky @@ -548,6 +598,7 @@ Kontakty Profil Nastavení + Data pro výstup ze Spark Tagy Transakční protokol Posílení a převody @@ -1237,11 +1288,16 @@ Síťový poplatek Obdržíte Poplatek za službu + Poplatek Spark Váš převod byl zahájen a <accent>vypořádává se on-chain</accent>. Zůstatek vašich úspor se po dokončení automaticky aktualizuje. Převod\n<accent>je na cestě</accent> + Zůstatek Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. + Zůstatek Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. Vaše spojení se přesouvají do úspor. <accent>Připojování</accent>\nk síti Připojte prosím znovu své hardwarové zařízení, zdá se, že je od telefonu odpojené. Znovu připojte hardwarové zařízení + Podepište\n<accent>svým zařízením</accent> + Transakce\n<accent>podepsána</accent> PŘEVOD PŘIPRAVEN ZA %s Převod není dostupný Automatické převody na zůstatek útrat již nejsou k dispozici. Použijte vlastní uzel nebo si nastavte připojení u jiného poskytovatele. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d8a0d88b77..5cea87a889 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -101,20 +101,50 @@ Abhängig von der Gebühr Anderes Wallet verwenden Von HW-Wallet übertragen + Am einfachsten ist es, deine Bitkit-Ersparnisse zu verwenden oder Bitcoin von einer anderen Wallet zu senden. + Spark + Einlösegebühr + %1$d/3 Bestätigungen + Einzahlung + Spark schreibt es deinem Ausgabenguthaben gut. + Warte, bis Spark deine Überweisung sieht. + Spark schreibt es deinem Ausgabenguthaben nach {standard} Bestätigungen gut, in etwa {minutes} Minuten. + Warten + Eingelöste Einzahlungen + Laufende Einzahlungen + 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. Spending Balance Fund your <accent>spending balance</accent> Von Sparkonto übertragen Manuelle Einrichtung + <accent>zu den Ausgaben</accent> Übertrage Guthaben Bitte\n<accent>bestätige</accent> Swipe zum Übertragen + Trezor Connect öffnen 25% Maximaler Ausgabensaldo + Überweise mehr als ₿ {amount}, damit die Gebühren für dein Ausgabenguthaben gedeckt sind. + Betrag zu klein Der Betrag, den du auf dein Ausgabenkonto übertragen kannst, ist derzeit auf ₿ {amount} begrenzt. Netzgebühren + Bitkit konnte die aktuellen Gebühren für diese Überweisung nicht abrufen. Prüfe deine Verbindung und versuche es erneut. + Gebühren nicht verfügbar + Ausgabengebühr Servicegebühren Zu den Ausgaben + Die Gebühren sind um {amount} höher, weil sich die Gebührensätze oder dein Sparguthaben geändert haben, während du auf diesem Bildschirm warst. Wische erneut, um zu bestätigen. + Gebühren geändert + In wenigen Minuten bereit + Nach 3 Bestätigungen, etwa 30 Minuten Total + bis zu + Los geht\'s + Überweisen Sie Geld auf Ihr Guthaben, um sofortige und günstige Transaktionen mit Freunden, Familie und Händlern zu tätigen. + <accent>zu den Ausgaben</accent> Übertragung\n<accent>zu den Einsparungen</accent> Übertragen Sie Ihr Ausgabensaldo auf Ihr Sparguthaben, um Ihre Bitcoin langfristig zu speichern und Ihre Zukunft zu sichern. Los geht\'s @@ -132,7 +162,9 @@ Die Gelder wurden noch nicht übertragen. Bitkit wird versuchen, die Übertragung in den nächsten <accent>30 Minuten</accent> zu initiieren. Bitte halte deine App offen. Übertragung erfolgreich Bewegte Mittel\n<accent>zu den Einsparungen</accent> + Bewegte Mittel\n<accent>zu den Ausgaben</accent> Ihr Geld wurde überwiesen. Sie können diese Mittel sofort verwenden. + Deine Gelder wurden übertragen und dein Ausgabenguthaben ist einsatzbereit. Lightning-Verbindung <accent>Manuelle Einrichtung</accent> Sie können einen externen Knoten verwenden, um eine Lightning-Verbindung manuell zu öffnen. Geben Sie die Details des Knotens ein, um fortzufahren. @@ -148,8 +180,12 @@ Einrichtung der Instant-Zahlungen fehlgeschlagen Ein Fehler ist bei der Einrichtung deines Sofortguthabens aufgetreten. {raw} Ausgabenkonto + Dein Sparkonto reicht nicht aus, um diese Übertragung und ihre Gebühren zu decken. Versuche einen kleineren Betrag. + Unzureichendes Sparguthaben Sparkonto Ausgabenguthaben + Sofort bezahlt den Anbieter dafür, deine Überweisung schon vor der Bestätigung deinem Ausgabenguthaben hinzuzufügen, meist innerhalb weniger Minuten.\n\nSpäter wartet auf 3 Bestätigungen, etwa 30 Minuten, zu einer niedrigeren Gebühr. + Transfer\n<accent>speed</accent> Empfangskapazität Lightning Node LDK Node ID @@ -192,6 +228,9 @@ Channel Monitor Archivhöhe Nächstes ausgehendes HTLC-Limit Nächster ausgehender HTLC Min + Bevor du Geld von deinem Sparkonto übertragen kannst, musst du Bitcoin zu deiner Bitkit Wallet senden. + Wallet aufladen + Keine verfügbaren Mittel Lightning Wallet Sync-Zeit Onchain Wallet Sync-Zeit Anderes @@ -232,11 +271,22 @@ Verbindung inaktiv Rapid Gossip Sync Snapshot-Zeit Pathfinding-Scores Sync-Zeit + Spark hat deine Überweisung noch nicht gesehen. Sie wird nach 3 Bestätigungen gutgeschrieben; du kannst diesen Bildschirm verlassen. + ₿ {amount} zahlen + Sofort kostet jetzt ₿ {amount}. Zahle es oder warte auf 3 Bestätigungen, etwa 30 Minuten, zu einer niedrigeren Gebühr. + Wird hinzugefügt + Von Spark gesehen + Überweisung gesendet + Sofort ist für diese Überweisung nicht verfügbar. Spark fügt sie nach 3 Bestätigungen, etwa 30 Minuten, deinem Ausgabenguthaben hinzu. + Bitkit weiter verwenden Onchain verfügbar Gesamte Anchor-Channels-Reserve Gesamt Lightning Gesamt Onchain ÜBERTRAGUNG LÄUFT + Los geht\'s + Fülle dein Guthaben auf, um sofortige und günstige Transaktionen mit Freunden, Familie und Händlern zu genießen. + Spending\n<accent>Balance</accent> Bitte warte bis sich Bitkit mit dem Zahlungsnetzwerk verbunden hat (±10 Sekunden). Bitte warte bis sich Bitkit mit dem Bitcoin-Netzwerk verbunden hat (±10 Sekunden). Wallet-Guthaben @@ -600,6 +650,7 @@ Transaktionshistorie Boosts & Übertragungen Einstellungen + Spark-Ausstiegsdaten Widgets Tags Profil @@ -1234,11 +1285,16 @@ Netzwerkgebühr Du erhältst Servicegebühr + Spark-Gebühr Deine Übertragung wurde gestartet und wird <accent>onchain abgewickelt</accent>. Dein Sparguthaben wird automatisch aktualisiert, sobald sie abgeschlossen ist. Übertragung\n<accent>unterwegs</accent> + Dein Spark-Guthaben konnte nicht in die Ersparnisse verschoben werden und bleibt im Ausgabenguthaben. + Dein Spark-Guthaben konnte nicht in die Ersparnisse verschoben werden und bleibt im Ausgabenguthaben. Deine Verbindungen werden in die Ersparnisse verschoben. <accent>Verbinde</accent>\nmit Netzwerk Bitte verbinde dein Hardware-Gerät erneut, es scheint von deinem Telefon getrennt zu sein. Hardware-Gerät neu verbinden + Mit deinem\n<accent>Gerät signieren</accent> + Transaktion\n<accent>signiert</accent> ÜBERTRAGUNG BEREIT IN %s Übertragung nicht verfügbar Automatische Übertragungen auf dein Ausgabenkonto sind nicht mehr verfügbar. Nutze deinen eigenen Node oder richte eine Verbindung mit einem anderen Anbieter ein. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5b589e5087..13bc6c27e3 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -158,6 +158,7 @@ Χρήση άλλου πορτοφολιού Μεταφορά από πορτοφόλι HW Υπόλοιπο δαπανών + Ο ευκολότερος τρόπος είναι να χρησιμοποιήσεις τις αποταμιεύσεις Bitkit ή να στείλεις bitcoin από διαφορετικό πορτοφόλι. Χρηματοδότησε το <accent>υπόλοιπο δαπανών</accent> Χειροκίνητη ρύθμιση Χωρητικότητα εισερχομένων @@ -168,6 +169,9 @@ Ύψος αρχειοθέτησης παρακολούθησης καναλιού Όριο επόμενου εξερχόμενου HTLC Ελάχιστο επόμενο εξερχόμενο HTLC + Πριν μπορέσεις να μεταφέρεις κεφάλαια από το υπόλοιπο αποταμιεύσεων, πρέπει να στείλεις bitcoin στο πορτοφόλι Bitkit. + Χρηματοδότηση πορτοφολιού + Δεν υπάρχουν διαθέσιμα κεφάλαια LDK Node ID Κόμβος Lightning Χρόνος συγχρονισμού πορτοφολιού Lightning @@ -206,16 +210,56 @@ Περίμενε, η μεταφορά κεφαλαίων σου είναι σε εξέλιξη. Αυτό θα διαρκέσει <accent>±10 δευτερόλεπτα.</accent> Κεφάλαια\n<accent>σε μεταφορά</accent> Χρόνος συγχρονισμού βαθμολογιών εύρεσης διαδρομής + Το Spark δεν έχει δει ακόμα τη μεταφορά σου. Προστίθεται μετά από 3 επιβεβαιώσεις· μπορείς να φύγεις από αυτή την οθόνη. + Πλήρωσε ₿ {amount} + Το Άμεσα κοστίζει τώρα ₿ {amount}. Πλήρωσέ το ή περίμενε 3 επιβεβαιώσεις, περίπου 30 λεπτά, με χαμηλότερη χρέωση. + Προσθήκη στις δαπάνες + Το είδε το Spark + Η μεταφορά στάλθηκε + Το Άμεσα δεν είναι διαθέσιμο για αυτή τη μεταφορά. Το Spark την προσθέτει στο υπόλοιπο δαπανών σου μετά από 3 επιβεβαιώσεις, περίπου 30 λεπτά. + Συνέχισε να χρησιμοποιείς το Bitkit + Spark + Χρέωση εξαργύρωσης + %1$d/3 επιβεβαιώσεις + Κατάθεση + Το Spark το προσθέτει στο υπόλοιπο δαπανών σας. + Αναμονή για να δει το Spark τη μεταφορά σας. + Το Spark το προσθέτει στο υπόλοιπο δαπανών σας μετά από {standard} επιβεβαιώσεις, σε περίπου {minutes} λεπτά. + Αναμονή + Εξαργυρωμένες καταθέσεις + Καταθέσεις σε εξέλιξη + Πάροχος + Spark μέσω Breez + Χωρίς όριο + Αυτό το υπόλοιπο φυλάσσεται στο Spark, που λειτουργούν οι Lightspark, Breez και Flashnet. Είναι ασφαλές όσο τουλάχιστον ένας από αυτούς ενεργεί έντιμα. Μπορούν να αναστείλουν την πρόσβαση, και η έξοδος χωρίς αυτούς απαιτεί έξοδο on-chain. Διαθέσιμα onchain Δαπάνες + Οι αποταμιεύσεις σου δεν επαρκούν για αυτή τη μεταφορά και τα τέλη της. Δοκίμασε μικρότερο ποσό. + Ανεπαρκείς αποταμιεύσεις Το ποσό που μπορείς να μεταφέρεις στο υπόλοιπο δαπανών περιορίζεται προς το παρόν σε ₿ {amount}. Μέγιστο υπόλοιπο δαπανών + Μετέφερε περισσότερα από ₿ {amount}, ώστε να καλύπτονται οι χρεώσεις για την προσθήκη στο υπόλοιπο δαπανών σου. + Πολύ μικρό ποσό 25% + Μεταφορά\n<accent>σε δαπάνες</accent> Σε δαπάνες + Τα τέλη είναι {amount} υψηλότερα, επειδή τα ποσοστά τελών ή το υπόλοιπο αποταμιεύσεων άλλαξαν ενώ ήσουν σε αυτή την οθόνη. Σύρε ξανά για επιβεβαίωση. + Τα τέλη άλλαξαν + Έτοιμο σε λίγα λεπτά + Μετά από 3 επιβεβαιώσεις, περίπου 30 λεπτά Τέλη υπηρεσίας Τέλη δικτύου + Το Bitkit δεν μπόρεσε να λάβει τις τρέχουσες χρεώσεις για αυτή τη μεταφορά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. + Μη διαθέσιμες χρεώσεις + Χρέωση δαπανών Σύνολο + έως + Ξεκίνα + Μετέφερε κεφάλαια στο υπόλοιπο δαπανών για να απολαύσεις άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. + Μεταφορά\n<accent>σε δαπάνες</accent> Υπόλοιπο δαπανών + Το Άμεσα πληρώνει τον πάροχο για να προσθέσει τη μεταφορά σου στο υπόλοιπο δαπανών πριν επιβεβαιωθεί, συνήθως μέσα σε λίγα λεπτά.\n\nΤο Αργότερα περιμένει 3 επιβεβαιώσεις, περίπου 30 λεπτά, με χαμηλότερη χρέωση. + Transfer\n<accent>speed</accent> Κατάσταση Υποστήριξη Συνολικό αποθεματικό anchor καναλιών @@ -226,10 +270,16 @@ Παρακαλώ\n<accent>επιβεβαίωσε</accent> Μεταφορά κεφαλαίων Σύρε για μεταφορά + Άνοιγμα Trezor Connect ΜΕΤΑΦΟΡΑ ΣΕ ΕΞΕΛΙΞΗ + Ξεκίνα + Χρηματοδότησε το υπόλοιπο δαπανών για να απολαύσεις άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. + Υπόλοιπο\n<accent>δαπανών</accent> Επιτυχής μεταφορά Τα κεφάλαιά σου μεταφέρθηκαν. Μπορείς να χρησιμοποιήσεις αυτά τα κεφάλαια αμέσως. + Τα κεφάλαιά σου μεταφέρθηκαν και το υπόλοιπο δαπανών είναι έτοιμο για χρήση. Κεφάλαια μεταφέρθηκαν\n<accent>σε αποταμιεύσεις</accent> + Κεφάλαια μεταφέρθηκαν\n<accent>σε δαπάνες</accent> Περίμενε το Bitkit να συνδεθεί στο δίκτυο πληρωμών (±10 δευτερόλεπτα). Περίμενε το Bitkit να συνδεθεί στο δίκτυο bitcoin (±10 δευτερόλεπτα). Υπόλοιπα πορτοφολιού @@ -528,6 +578,7 @@ Επαφές Προφίλ Ρυθμίσεις + Δεδομένα εξόδου Spark Ετικέτες Αρχείο συναλλαγών Ενισχύσεις & Μεταφορές @@ -1215,11 +1266,16 @@ Τέλος δικτύου Θα λάβεις Τέλος υπηρεσίας + Τέλος Spark Η μεταφορά σου ξεκίνησε και <accent>εκκαθαρίζεται onchain</accent>. Το υπόλοιπο αποταμιεύσεων θα ενημερωθεί αυτόματα μόλις ολοκληρωθεί. Η μεταφορά\n<accent>είναι καθ\' οδόν</accent> + Το υπόλοιπο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. + Το υπόλοιπο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. Οι συνδέσεις σας μεταφέρονται στις αποταμιεύσεις. <accent>Σύνδεση</accent>\nστο δίκτυο Σύνδεσε ξανά τη συσκευή υλικού σου, φαίνεται ότι αποσυνδέθηκε από το τηλέφωνό σου. Επανασύνδεση συσκευής υλικού + Υπόγραψε με\n<accent>τη συσκευή σου</accent> + Η συναλλαγή\n<accent>υπογράφηκε</accent> Η ΜΕΤΑΦΟΡΑ ΕΙΝΑΙ ΕΤΟΙΜΗ ΣΕ %s Μεταφορά μη διαθέσιμη Οι αυτόματες μεταφορές στο υπόλοιπο δαπανών δεν είναι πλέον διαθέσιμες. Χρησιμοποιήστε τον δικό σας κόμβο ή ρυθμίστε σύνδεση με άλλον πάροχο. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 34faa374a7..e50e8de4c2 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -164,6 +164,7 @@ Usar Otro Monedero Transferir desde billetera HW Saldo de gastos + La forma más fácil es usar sus ahorros en Bitkit o enviar bitcoin desde un monedero diferente. Rellene su <accent>saldo de gastos</accent> Configuración manual Capacidad entrante @@ -174,6 +175,9 @@ Altura de archivo del monitor de canales Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente + Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. + Financiar monedero + No hay fondos disponibles ID del nodo LDK Nodo Lightning Hora de sincronización del monedero Lightning @@ -212,16 +216,56 @@ Por favor espera, tu transferencia de fondos está en curso. Debería tardar <accent>±10 segundos.</accent> Fondos\n<accent>en transferencia</accent> Hora de sincronización de puntuaciones de rutas + Spark aún no ha visto su transferencia. Se añade tras 3 confirmaciones; puede salir de esta pantalla. + Pagar ₿ {amount} + Instantáneo ahora cuesta ₿ {amount}. Páguelo o espere 3 confirmaciones, unos 30 minutos, con una comisión menor. + Añadiendo a gastos + Visto por Spark + Transferencia enviada + Instantáneo no está disponible para esta transferencia. Spark la añade a su saldo para gastos tras 3 confirmaciones, unos 30 minutos. + Continuar Usando Bitkit + Spark + Comisión de reclamación + %1$d/3 confirmaciones + Depósito + Spark lo está añadiendo a tu saldo de gastos. + Esperando a que Spark vea tu transferencia. + Spark lo añade a tu saldo de gastos tras {standard} confirmaciones, en unos {minutes} minutos. + Esperar + Depósitos reclamados + Depósitos en curso + 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. Gastable en cadena Gasto + Tus ahorros no cubren esta transferencia y sus comisiones. Prueba con una cantidad menor. + Ahorros Insuficientes La cantidad que puedes transferir a tu saldo de gasto está actualmente limitada a ₿ {amount}. Máximo del saldo de gasto + Transfiera más de ₿ {amount} para cubrir las comisiones de añadirlo a su saldo para gastos. + Importe demasiado bajo 25% + Transferir\n<accent>a gasto</accent> A gasto + Las comisiones son {amount} más altas porque las tasas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + Las comisiones han cambiado + Listo en unos minutos + Tras 3 confirmaciones, unos 30 minutos Comisión de servicio Comisión de red + Bitkit no pudo obtener las comisiones actuales de esta transferencia. Compruebe su conexión e inténtelo de nuevo. + Comisiones no disponibles + Comisión de gastos Total + hasta + Empezar + Transfiera fondos a su saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. + Transferir\n<accent>a gasto</accent> Saldo para gastos + Instantáneo paga al proveedor para añadir su transferencia a su saldo para gastos antes de que se confirme, normalmente en unos minutos.\n\nMás tarde espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Transfer\n<accent>speed</accent> Estatus Soporte Reserva total de canales ancla @@ -232,10 +276,16 @@ Por favor,\n<accent>confirme</accent> Transferir fondos Deslizar para transferir + Abrir Trezor Connect TRANSFERENCIA EN CURSO + Empezar + Rellene el saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. + Saldo de\n<accent>Gasto</accent> Transferencia exitosa Tus fondos han sido transferidos. Puedes usar estos fondos inmediatamente. + Tus fondos han sido transferidos y tu saldo de gasto está listo para usar. Fondos movidos\n<accent>a ahorros</accent> + Fondos movidos\n<accent>a gasto</accent> Por favor, espere a que Bitkit se conecte a la red de pagos (±10 segundos). Por favor, espere a que Bitkit se conecte a la red bitcoin (±10 segundos). Saldos del monedero @@ -546,6 +596,7 @@ Contactos Perfil Ajustes + Datos de salida de Spark Etiquetas Registro de Transacciones Impulsos y transferencias @@ -1231,11 +1282,16 @@ Comisión de red Recibirás Comisión de servicio + Comisión de Spark Tu transferencia se ha iniciado y se está <accent>liquidando en cadena</accent>. Tu saldo de ahorro se actualizará automáticamente cuando se complete. Transferencia\n<accent>en camino</accent> + Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. + Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. <accent>Conectando</accent>\na la red Vuelve a conectar tu dispositivo de hardware; parece que se ha desconectado de tu teléfono. Reconecta el dispositivo de hardware + Firma con\n<accent>tu dispositivo</accent> + Transacción\n<accent>firmada</accent> TRANSFERENCIA LISTA EN %s Transferencia no disponible Las transferencias automáticas a tu saldo de gasto ya no están disponibles. Usa tu propio nodo o configura una conexión con otro proveedor. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b9c24c4522..fa41c6b382 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -133,6 +133,7 @@ No se pueden transferir los fondos de vuelta a ahorros. Por favor, inténtalo de nuevo. Usar Otro Monedero Transferir desde billetera HW + La forma más fácil es usar tus ahorros de Bitkit o enviar bitcoin desde un monedero diferente. Configuración Manual Capacidad de entrada HTLC de entrada máximo @@ -141,6 +142,9 @@ Altura de archivo del monitor de canal Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente + Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. + Financiar monedero + No hay fondos disponibles Hora de sincronización del monedero Lightning Hora de sincronización del monedero onchain Vencimiento del pedido @@ -154,24 +158,64 @@ Por favor espera, la transferencia de tus fondos está en progreso. Esto debería llevar <accent>±10 segundos.</accent> Fondos\n<accent>en transferencia</accent> Hora de sincronización de puntuaciones de rutas + Spark aún no ha visto tu transferencia. Se añade tras 3 confirmaciones; puedes salir de esta pantalla. + Pagar ₿ {amount} + Instantáneo ahora cuesta ₿ {amount}. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Añadiendo a gastos + Visto por Spark + Transferencia enviada + Instantáneo no está disponible para esta transferencia. Spark la añade a tu saldo para gastos tras 3 confirmaciones, unos 30 minutos. + Continuar Usando Bitkit + Spark + Comisión de reclamo + %1$d/3 confirmaciones + Depósito + Spark lo está añadiendo a tu saldo de gastos. + Esperando a que Spark vea tu transferencia. + Spark lo añade a tu saldo de gastos tras {standard} confirmaciones, en unos {minutes} minutos. + Esperar + Depósitos reclamados + Depósitos en curso + 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. Gastable onchain La cantidad que puedes transferir a tu saldo de gastos está actualmente limitada a ₿ {amount}. Máximo del Saldo de Gastos + Transfiere más de ₿ {amount} para cubrir las comisiones de añadirlo a tu saldo para gastos. + Importe demasiado bajo + Transferir\n<accent>a gastos</accent> A gastos + Las comisiones son {amount} más altas porque las tasas de comisión o su saldo de ahorro cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. + Las comisiones han cambiado + Listo en unos minutos + Tras 3 confirmaciones, unos 30 minutos Reserva total de canales ancla Total Lightning Total onchain TRANSFERENCIA EN PROGRESO + Empezar + Rellene el saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. + Saldo de\n<accent>Gasto</accent> Saldo de gastos Rellene su <accent>saldo de gastos</accent> Transferir desde Ahorros Transferir fondos Por favor,\n<accent>confirme</accent> Deslizar para transferir + Abrir Trezor Connect 25% Comisión de red + Bitkit no pudo obtener las comisiones actuales de esta transferencia. Comprueba tu conexión e inténtalo de nuevo. + Comisiones no disponibles + Comisión de gastos Comisión de servicio Total + hasta + Empezar + Transfiera fondos a su saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. + Transferir\n<accent>a gastos</accent> Transferir\n<accent>a ahorros</accent> Empezar Transferir todo @@ -182,7 +226,9 @@ Los fondos todavía no se transfirieron. Bitkit intentará iniciar la transferencia durante los próximos <accent>30 minutos</accent>. Por favor, mantenga la aplicación abierta. Transferencia exitosa Tus fondos han sido transferidos. Puedes usar estos fondos inmediatamente. + Tus fondos han sido transferidos y tu saldo de gastos está listo para usar. Fondos movidos\n<accent>a ahorros</accent> + Fondos movidos\n<accent>a gastos</accent> Saldos del Monedero Conexión Lightning Servidor @@ -190,8 +236,12 @@ Escanear QR Error en la Configuración de Pago Instántaneo Gasto + Sus ahorros no cubren esta transferencia y sus comisiones. Pruebe con una cantidad menor. + Ahorros Insuficientes Ahorro Saldo para gastos + Instantáneo paga al proveedor para añadir tu transferencia a tu saldo para gastos antes de que se confirme, normalmente en unos minutos.\n\nMás tarde espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Transfer\n<accent>speed</accent> Capacidad de recepción Nodo Lightning ID del nodo LDK @@ -573,6 +623,7 @@ Registro de Conexiones Registro de Transacciones Ajustes + Datos de salida de Spark Widgets Etiquetas Perfil @@ -1230,11 +1281,16 @@ Comisión de red Recibirá Comisión de servicio + Comisión de Spark Su transferencia se ha iniciado y se está <accent>liquidando onchain</accent>. Su saldo de ahorro se actualizará automáticamente cuando se complete. Transferencia\n<accent>en camino</accent> + Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. + Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. <accent>Conectando</accent>\na la red Vuelva a conectar su dispositivo de hardware; parece que se ha desconectado de su teléfono. Reconecte el dispositivo de hardware + Firme con\n<accent>su dispositivo</accent> + Transacción\n<accent>firmada</accent> TRANSFERENCIA LISTA EN %s Transferencia no disponible Las transferencias automáticas a tu saldo de gasto ya no están disponibles. Usa tu propio nodo o configura una conexión con otro proveedor. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 504d48a804..205a538624 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -100,20 +100,50 @@ Dépend des frais Utiliser un autre portefeuille Transfert depuis le portefeuille HW + Le plus simple est d\'utiliser vos économies Bitkit ou d\'envoyer des bitcoins depuis un autre portefeuille. + Spark + Frais de réclamation + %1$d/3 confirmations + Dépôt + Spark l\'ajoute à votre solde de dépenses. + En attente que Spark voie votre transfert. + Spark l\'ajoute à votre solde de dépenses après {standard} confirmations, dans environ {minutes} minutes. + Attendre + Dépôts réclamés + Dépôts en cours + 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. Solde Dépenses Financez votre <accent>solde Dépenses</accent> Transfert depuis l\'épargne Configuration manuelle + Transfert \n<accent>Dépenses</accent> Transfert de fonds Veuillez\n<accent>confirmer</accent> Glissez pour transférer + Ouvrir Trezor Connect 25% Seuil Maximum Épargne + Transférez plus de ₿ {amount} pour couvrir les frais d\'ajout à votre solde de dépenses. + Montant trop faible Le montant que vous pouvez transférer vers votre solde de dépenses est actuellement limité à ₿ {amount}. Frais de réseau + Bitkit n\'a pas pu obtenir les frais actuels de ce transfert. Vérifiez votre connexion et réessayez. + Frais indisponibles + Frais de dépense Frais de service Vers Dépenses + Les frais sont plus élevés de {amount}, car les taux de frais ou votre solde d\'épargne ont changé pendant que vous étiez sur cet écran. Glissez à nouveau pour confirmer. + Frais modifiés + Prêt en quelques minutes + Après 3 confirmations, environ 30 minutes Total + jusqu\'à + Commencer + Transférez des fonds vers votre solde Dépenses pour profiter de transactions instantanées et moins chers avec vos amis, votre famille et les commerçants. + Transfert\n<accent>aux dépenses</accent> Transfert \n<accent>vers l\'Épargne</accent> Transférez le solde de votre compte Dépenses vers votre Épargne pour conserver vos bitcoins à long terme. Commencer @@ -131,7 +161,9 @@ Les fonds n\'ont pas encore été transférés. Bitkit va essayer d\'initier le transfert au cours des <accent>30</accent> prochaines <accent>minutes</accent>. Veuillez garder votre application ouverte. Transfert réussi Fonds transférés \n<accent>à l\'épargne</accent> + Fonds transférés \n<accent>vers Dépenses</accent> Vos fonds ont été transférés. Vous pouvez utiliser ces fonds immédiatement. + Vos fonds ont été transférés et votre solde Dépenses est prêt à être utilisé. Connexion Lightning <accent>Configuration manuelle</accent> Vous pouvez utiliser un nœud externe pour ouvrir manuellement une connexion Lightning. Saisissez les détails du nœud pour continuer. @@ -147,16 +179,31 @@ Échec de la configuration des paiements instantanés Une erreur s\'est produite lors de l\'établissement de votre solde du compte courant. {raw} Dépenser + Votre épargne ne couvre pas ce transfert et ses frais. Essayez un montant plus petit. + Épargne insuffisante Épargner Solde Dépenses + Instantané paie le fournisseur pour ajouter votre transfert à votre solde de dépenses avant sa confirmation, généralement en quelques minutes.\n\nPlus tard attend 3 confirmations, environ 30 minutes, pour des frais moins élevés. + Transfer\n<accent>speed</accent> Capacité de réception Heure de l\'instantané Rapid Gossip Sync Heure de synchronisation des scores de routage + Spark n\'a pas encore vu votre transfert. Il est ajouté après 3 confirmations ; vous pouvez quitter cet écran. + Payer ₿ {amount} + Instantané coûte maintenant ₿ {amount}. Payez-le, ou attendez 3 confirmations, environ 30 minutes, pour des frais moins élevés. + Ajout aux dépenses + Vu par Spark + Transfert envoyé + Instantané n\'est pas disponible pour ce transfert. Spark l\'ajoute à votre solde de dépenses après 3 confirmations, environ 30 minutes. + Continuer à utiliser Bitkit Dépensable Onchain Réserve totale des canaux Anchor Total Lightning Total Onchain TRANSFERT EN COURS + Commencer + Alimentez votre solde de dépenses pour profiter de transactions instantanées et bon marché avec vos amis, votre famille et les commerçants. + Dépenses \n<accent>Solde</accent> Soldes du portefeuille Nœud Lightning ID du nœud LDK @@ -209,6 +256,9 @@ Hauteur d\'archivage du moniteur de canal Limite HTLC sortant suivant HTLC sortant min suivant + Avant de pouvoir transférer des fonds depuis votre solde d\'épargne, vous devez envoyer des bitcoins à votre portefeuille Bitkit. + Approvisionner le portefeuille + Pas de fonds disponibles Support Fermer la connexion Échec de transfer  @@ -587,6 +637,7 @@ Journal des transactions Boosts et transferts Réglages + Données de sortie Spark Widgets Tags Profil @@ -1233,11 +1284,16 @@ Frais de réseau Vous recevrez Frais de service + Frais Spark Votre transfert a été initié et est <accent>en cours de règlement on-chain</accent>. Votre solde d\'épargne se mettra à jour automatiquement une fois terminé. Transfert\n<accent>en cours</accent> + Votre solde Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. + Votre solde Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. Vos connexions sont en cours de transfert vers l\'épargne. <accent>Connexion</accent>\nau réseau Veuillez reconnecter votre appareil matériel, il semble être déconnecté de votre téléphone. Reconnecter l\'appareil matériel + Signez avec\n<accent>votre appareil</accent> + Transaction\n<accent>signée</accent> TRANSFERT PRÊT DANS %s Transfert indisponible Les transferts automatiques vers votre solde de dépenses ne sont plus disponibles. Utilisez votre propre nœud ou configurez une connexion avec un autre fournisseur. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index bbe3915683..f46eaf89c8 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -163,6 +163,7 @@ Usa un altro portafoglio Trasferimento da wallet HW Conto di Spesa + Il modo più semplice è usare i tuoi risparmi Bitkit o inviare bitcoin da un portafoglio diverso. Manda fondi al tuo <accent>conto di spesa</accent> Configurazione Manuale Capacita\' in Entrata @@ -173,6 +174,9 @@ Altezza Archivio Monitor Canali Limite HTLC in Uscita Successivo HTLC Min in Uscita Successivo + Prima di poter trasferire fondi dal tuo conto di risparmio, devi inviare bitcoin al tuo portafoglio Bitkit. + Finanzia portafoglio + Nessun fondo disponibile ID Nodo LDK Nodo Lightning Tempo Sincronizzazione Wallet Lightning @@ -211,16 +215,56 @@ Attendi, il trasferimento dei fondi e\' in corso. Dovrebbe richiedere <accent>circa 10 secondi.</accent> Fondi\n<accent>in trasferimento</accent> Tempo Sincronizzazione Punteggi Pathfinding + Spark non ha ancora visto il tuo trasferimento. Viene aggiunto dopo 3 conferme; puoi lasciare questa schermata. + Paga ₿ {amount} + Istantanea ora costa ₿ {amount}. Pagala, oppure attendi 3 conferme, circa 30 minuti, con una commissione più bassa. + Aggiunta alle spese + Visto da Spark + Trasferimento inviato + Istantanea non è disponibile per questo trasferimento. Spark lo aggiunge al tuo conto di spesa dopo 3 conferme, circa 30 minuti. + Continua ad utilizzare Bitkit + Spark + Commissione di riscatto + %1$d/3 conferme + Deposito + Spark lo sta aggiungendo al tuo saldo di spesa. + In attesa che Spark veda il tuo trasferimento. + Spark lo aggiunge al tuo saldo di spesa dopo {standard} conferme, tra circa {minutes} minuti. + Attendi + Depositi riscattati + Depositi in corso + 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. Spendibile Onchain Spesa + I tuoi risparmi non coprono questo trasferimento e le relative commissioni. Prova un importo minore. + Risparmi insufficienti L\'importo che puoi trasferire al tuo conto di spesa e\' attualmente limitato a ₿ {amount}. Massimo Conto di Spesa + Trasferisci più di ₿ {amount}, così copre le commissioni per aggiungerlo al tuo conto di spesa. + Importo troppo basso 25% + Trasferisci\n<accent>alle spese</accent> Alle spese + Le commissioni sono aumentate di {amount} perché i tassi di commissione o il saldo dei tuoi risparmi sono cambiati mentre eri su questa schermata. Scorri di nuovo per confermare. + Commissioni cambiate + Pronto in pochi minuti + Dopo 3 conferme, circa 30 minuti Commissioni servizio Commissioni rete + Bitkit non è riuscito a ottenere le commissioni attuali per questo trasferimento. Controlla la connessione e riprova. + Commissioni non disponibili + Commissione di spesa Totale + fino a + Inizia + Trasferisci fondi al tuo conto di spesa per usufruire di transazioni istantanee ed economiche con amici, familiari e commercianti. + Trasferisci\n<accent>alle spese</accent> Conto di spesa + Istantanea paga il fornitore per aggiungere il tuo trasferimento al conto di spesa prima della conferma, di solito in pochi minuti.\n\nPiù tardi attende 3 conferme, circa 30 minuti, con una commissione più bassa. + Transfer\n<accent>speed</accent> Stato Supporto Riserva Totale Canali Anchor @@ -231,10 +275,16 @@ Per favore\n<accent>conferma</accent> Trasferimento Fondi Swipe Per Trasferire + Apri Trezor Connect TRASFERIMENTO IN CORSO + Inizia + Manda fondi al tuo conto di spesa per usufruire di transazioni istantanee ed economiche con amici, familiari e commercianti. + Conto\n<accent>di Spesa</accent> Trasferimento Riuscito I tuoi fondi sono stati trasferiti. Puoi utilizzare questi fondi immediatamente. + I tuoi fondi sono stati trasferiti e il tuo conto di spesa è pronto per essere utilizzato. Fondi spostati\n<accent>ai risparmi</accent> + Fondi spostati\n<accent>alle spese</accent> Attendi che Bitkit si connetta alla rete di pagamento (±10 secondi). Attendi che Bitkit si connetta alla rete bitcoin (±10 secondi). Saldi Wallet @@ -545,6 +595,7 @@ Contatti Profilo Impostazioni + Dati di uscita Spark Tag Log delle transazioni Boost e Trasferimenti @@ -1236,11 +1287,16 @@ Commissione di rete Riceverai Commissione di servizio + Commissione Spark Il tuo trasferimento è stato avviato ed è <accent>in regolamento on-chain</accent>. Il saldo dei tuoi risparmi si aggiornerà automaticamente al termine. Trasferimento\n<accent>in corso</accent> + Il saldo Spark non è stato spostato nei risparmi e resta nel saldo di spesa. + Il saldo Spark non è stato spostato nei risparmi e resta nel saldo di spesa. Le tue connessioni stanno passando ai risparmi. <accent>Connessione</accent>\nalla rete Ricollega il tuo dispositivo hardware, sembra essere disconnesso dal telefono. Ricollega il Dispositivo Hardware + Firma con\n<accent>il tuo dispositivo</accent> + Transazione\n<accent>firmata</accent> TRASFERIMENTO PRONTO TRA %s Trasferimento non disponibile I trasferimenti automatici al saldo di spesa non sono più disponibili. Usa il tuo nodo o configura una connessione con un altro fornitore. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9e476721ba..fc7c27129e 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -162,6 +162,7 @@ Andere wallet gebruiken Overboeken van HW-wallet Bestedingssaldo + De makkelijkste optie is om je Bitkit-spaargeld te gebruiken of bitcoin te versturen vanuit een andere wallet. Vul je <accent>bestedingssaldo</accent> Handmatige configuratie Inkomende capaciteit @@ -172,6 +173,9 @@ Kanaalmonitor archiveringshoogte Volgende uitgaande HTLC-limiet Volgende uitgaande HTLC min + Voordat je geld van je spaargeld kunt overboeken, moet je bitcoin naar je Bitkit-wallet sturen. + Wallet financieren + Geen beschikbaar geld LDK Node ID Lightning Node Lightning-wallet synchronisatietijd @@ -210,16 +214,56 @@ Even geduld, je geld wordt overgeboekt. Dit duurt <accent>±10 seconden.</accent> Geld\n<accent>in overboeking</accent> Pathfinding scores synchronisatietijd + Spark heeft je overboeking nog niet gezien. Hij wordt toegevoegd na 3 bevestigingen; je kunt dit scherm verlaten. + Betaal ₿ {amount} + Direct kost nu ₿ {amount}. Betaal het, of wacht op 3 bevestigingen, ongeveer 30 minuten, tegen lagere kosten. + Toevoegen aan besteding + Gezien door Spark + Overboeking verzonden + Direct is niet beschikbaar voor deze overboeking. Spark voegt hem na 3 bevestigingen, ongeveer 30 minuten, toe aan je bestedingssaldo. + Doorgaan met Bitkit + Spark + Claimkosten + %1$d/3 bevestigingen + Storting + Spark voegt het toe aan je bestedingssaldo. + Wachten tot Spark je overboeking ziet. + Spark voegt het na {standard} bevestigingen toe aan je bestedingssaldo, over ongeveer {minutes} minuten. + Wachten + Geclaimde stortingen + Lopende stortingen + 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. Besteedbaar onchain Bestedingssaldo + Uw spaargeld is niet voldoende voor deze overboeking en de vergoedingen. Probeer een kleiner bedrag. + Onvoldoende spaargeld Het bedrag dat je kunt overboeken naar je bestedingssaldo is momenteel beperkt tot ₿ {amount}. Maximum bestedingssaldo + Boek meer dan ₿ {amount} over, zodat de kosten om het aan je bestedingssaldo toe te voegen gedekt zijn. + Bedrag te klein 25% + Overboeken\n<accent>naar bestedingssaldo</accent> Naar bestedingssaldo + De vergoedingen zijn {amount} hoger, omdat de vergoedingstarieven of uw spaargeld zijn gewijzigd terwijl u op dit scherm was. Veeg opnieuw om te bevestigen. + Vergoedingen gewijzigd + Klaar binnen enkele minuten + Na 3 bevestigingen, ongeveer 30 minuten Servicevergoedingen Netwerkvergoedingen + Bitkit kon de huidige kosten voor deze overboeking niet ophalen. Controleer je verbinding en probeer het opnieuw. + Kosten niet beschikbaar + Bestedingskosten Totaal + tot + Aan de slag + Boek geld over naar je bestedingssaldo voor directe en goedkope transacties met vrienden, familie en winkeliers. + Overboeken\n<accent>naar bestedingssaldo</accent> Bestedingssaldo + Direct betaalt de aanbieder om je overboeking al vóór de bevestiging aan je bestedingssaldo toe te voegen, meestal binnen enkele minuten.\n\nLater wacht op 3 bevestigingen, ongeveer 30 minuten, tegen lagere kosten. + Transfer\n<accent>speed</accent> Status Ondersteuning Totale ankerkanalen reserve @@ -230,10 +274,16 @@ Graag\n<accent>bevestigen</accent> Geld overboeken Veeg om over te boeken + Trezor Connect openen OVERBOEKING BEZIG + Aan de slag + Vul je bestedingssaldo voor directe en goedkope transacties met vrienden, familie en winkeliers. + Bestedings\n<accent>saldo</accent> Overboeking succesvol Je geld is overgeboekt. Je kunt dit geld direct gebruiken. + Je geld is overgeboekt en je bestedingssaldo is klaar voor gebruik. Geld verplaatst\n<accent>naar spaargeld</accent> + Geld verplaatst\n<accent>naar bestedingssaldo</accent> Wacht tot Bitkit verbinding maakt met het betaalnetwerk (±10 seconden). Wacht tot Bitkit verbinding maakt met het bitcoinnetwerk (±10 seconden). Wallet-saldi @@ -543,6 +593,7 @@ Contacten Profiel Instellingen + Spark-exitgegevens Tags Transactielog Boosts & overboekingen @@ -1232,11 +1283,16 @@ Netwerkvergoeding U ontvangt Servicevergoeding + Spark-vergoeding Uw overboeking is gestart en wordt <accent>on-chain afgehandeld</accent>. Uw spaargeld wordt automatisch bijgewerkt zodra deze is voltooid. Overboeking\n<accent>onderweg</accent> + Je Spark-saldo kon niet naar sparen en blijft in je bestedingssaldo. + Je Spark-saldo kon niet naar sparen en blijft in je bestedingssaldo. Je verbindingen gaan naar sparen. <accent>Verbinden</accent>\nmet netwerk Verbind uw hardwareapparaat opnieuw, de verbinding met uw telefoon lijkt verbroken. Hardwareapparaat opnieuw verbinden + Onderteken met\n<accent>uw apparaat</accent> + Transactie\n<accent>ondertekend</accent> OVERBOEKING KLAAR OVER %s Overboeking niet beschikbaar Automatische overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Gebruik je eigen node of stel een verbinding in met een andere aanbieder. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index db3199891a..61316f843c 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -102,20 +102,50 @@ Zależy od opłaty Użyj innego portfela Prześlij z portfela HW + Najłatwiejszą opcją jest użycie oszczędności Bitkit lub wysłanie bitcoinów z innego portfela. + Spark + Opłata za odbiór + %1$d/3 potwierdzeń + Wpłata + Spark dodaje je do Twojego salda wydatków. + Czekamy, aż Spark zobaczy Twój przelew. + Spark doda je do Twojego salda wydatków po {standard} potwierdzeniach, za około {minutes} minut. + Czekaj + Odebrane wpłaty + Wpłaty w toku + 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. Saldo wydatków Zasil swoje <accent>saldo wydatków</accent> Prześlij z Oszczędności Konfiguracja ręczna + Prześlij \n<accent>na saldo wydatków</accent> Prześlij środki Proszę \n<accent>potwierdzić</accent> Przesuń, aby przesłać + Otwórz Trezor Connect 25% Maksymalne saldo wydatków + Prześlij więcej niż ₿ {amount}, aby pokryć opłaty za dodanie do salda wydatków. + Kwota zbyt mała Kwota, którą można przelać na saldo wydatków, jest obecnie ograniczona do ₿ {amount}. Opłaty sieciowe + Bitkit nie mógł pobrać aktualnych opłat za ten przelew. Sprawdź połączenie i spróbuj ponownie. + Opłaty niedostępne + Opłata za wydatki Opłaty serwisowe Do salda wydatków + Opłaty są wyższe o {amount}, ponieważ stawki opłat lub saldo oszczędności zmieniły się podczas wyświetlania tego ekranu. Przesuń ponownie, aby potwierdzić. + Opłaty się zmieniły + Gotowe w kilka minut + Po 3 potwierdzeniach, około 30 minut Razem + do + Rozpocznij + Przelewaj środki na swoje saldo wydatków, aby cieszyć się natychmiastowymi i tanimi transakcjami z przyjaciółmi, rodziną i sprzedawcami. + Prześlij \n<accent>na saldo wydatków</accent> Prześlij \n<accent>na saldo oszczędności</accent> Przenieś saldo wydatków do oszczędności, aby przechowywać Bitcoiny długoterminowo i zabezpieczyć swoją przyszłość. Rozpocznij @@ -133,7 +163,9 @@ Środki nie zostały jeszcze przelane. Bitkit spróbuje zainicjować transfer w ciągu najbliższych <accent>30 minut</accent>. Proszę pozostawić aplikację otwartą. Transfer środków powiódł się Środki przeniesione\n<accent>na saldo oszczędności</accent> + Środki przeniesione\n<accent>na saldo wydatków</accent> Środki zostały przelane i są gotowe do natychmiastowego użycia. + Środki zostały przeniesione i saldo wydatków jest gotowe do użycia. Połączenie z Lightning <accent>Konfiguracja ręczna</accent> Do ręcznego otwarcia połączenia Lightning można użyć węzła zewnętrznego. Proszę wprowadzić szczegóły węzła, aby kontynuować. @@ -149,8 +181,12 @@ Konfiguracja płatności natychmiastowych nie powiodła się Wystąpił błąd podczas konfigurowania salda natychmiastowego. {raw} Wydatki + Twoje oszczędności nie pokryją tego transferu i jego opłat. Spróbuj mniejszej kwoty. + Niewystarczające oszczędności Oszczędności Saldo wydatków + Natychmiast płaci dostawcy za dodanie przelewu do salda wydatków jeszcze przed potwierdzeniem, zwykle w kilka minut.\n\nPóźniej czeka na 3 potwierdzenia, około 30 minut, z niższą opłatą. + Transfer\n<accent>speed</accent> Zdolność odbioru Węzeł Lightning Identyfikator węzła LDK @@ -194,6 +230,9 @@ Wysokość archiwalnego monitora kanału Limit następnej wychodzącej HTLC Min. następnej wychodzącej HTLC + Zanim będzie można przelać środki z salda oszczędności, należy wysłać bitcoiny do portfela Bitkit. + Doładuj portfel + Brak dostępnych środków Inne Jest użyteczny Otwarto @@ -233,11 +272,22 @@ Połączenie nieaktywne Czas snapshotu Rapid Gossip Sync Czas synchronizacji wyników ścieżek + Spark jeszcze nie widzi Twojego przelewu. Zostanie dodany po 3 potwierdzeniach; możesz opuścić ten ekran. + Zapłać ₿ {amount} + Natychmiast kosztuje teraz ₿ {amount}. Zapłać albo poczekaj na 3 potwierdzenia, około 30 minut, z niższą opłatą. + Dodawanie do wydatków + Widziany przez Spark + Przelew wysłany + Natychmiast nie jest dostępne dla tego przelewu. Spark doda go do Twojego salda wydatków po 3 potwierdzeniach, około 30 minut. + Kontunuuj korzystanie z Bitkit\'a Dostępne Onchain Całkowita rezerwa kanałów anchor Całkowite Lightning Całkowite Onchain TRANSFER W TOKU + Rozpocznij + Zasil swoje saldo wydatków, aby cieszyć się natychmiastowymi i tanimi transakcjami z przyjaciółmi, rodziną i sprzedawcami. + Saldo \n<accent>Wydatków</accent> Saldo portfela Proszę poczekać, aż Bitkit połączy się z siecią płatności (±10 sekund). Proszę poczekać, aż Bitkit połączy się z siecią bitcoin (±10 sekund). @@ -586,6 +636,7 @@ Log transakcji Przyśpieszenia i transfery Ustawienia + Dane wyjścia ze Spark Widgety Tagi Profil @@ -1236,11 +1287,16 @@ Opłata sieciowa Otrzymasz Opłata serwisowa + Opłata Spark Twój transfer został zainicjowany i jest <accent>rozliczany on-chain</accent>. Saldo oszczędności zaktualizuje się automatycznie po jego zakończeniu. Transfer\n<accent>w drodze</accent> + Nie udało się przenieść salda Spark do oszczędności; pozostaje w saldzie wydatków. + Nie udało się przenieść salda Spark do oszczędności; pozostaje w saldzie wydatków. Twoje połączenia są przenoszone do oszczędności. <accent>Łączenie</accent>\nz siecią Połącz ponownie urządzenie sprzętowe, wygląda na to, że zostało odłączone od telefonu. Połącz ponownie urządzenie + Podpisz\n<accent>urządzeniem</accent> + Transakcja\n<accent>podpisana</accent> TRANSFER GOTOWY ZA %s Przesłanie niedostępne Automatyczne przesyłanie środków na saldo wydatków nie jest już dostępne. Użyj własnego węzła lub skonfiguruj połączenie z innym dostawcą. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 47626cd119..3e7b7deb6b 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -166,6 +166,7 @@ Transferir de Outra Carteira Transferir da carteira HW Saldo de Gastos + A forma mais fácil é usar suas economias do Bitkit ou enviar bitcoin de uma carteira diferente. Transfira para seu <accent>saldo de gastos</accent> Setup Manual Capacidade de Entrada @@ -176,6 +177,9 @@ Altura de Arquivamento do Monitor de Canal Limite do Próximo HTLC de Saída HTLC de Saída Mín Próximo + Antes de transferir fundos de seu saldo de poupança, receba bitcoin na sua carteira Bitkit. + Financiar Carteira + Não há Fundos Disponíveis ID do LDK Node Nó Lightning Sincronização da Carteira Lightning @@ -214,16 +218,56 @@ Aguarde, sua transferência de fundos está em andamento. Isso deve levar <accent>±10 segundos.</accent> <accent>Transferindo</accent>\nfundos Sincronização de Scores de Roteamento + A Spark ainda não viu sua transferência. Ela é adicionada após 3 confirmações; você pode sair desta tela. + Pagar ₿ {amount} + Instantâneo agora custa ₿ {amount}. Pague ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa menor. + Adicionando aos gastos + Vista pela Spark + Transferência enviada + Instantâneo não está disponível para esta transferência. A Spark a adiciona ao seu saldo de gastos após 3 confirmações, cerca de 30 minutos. + Continuar Usando o Bitkit + Spark + Taxa de resgate + %1$d/3 confirmações + Depósito + A Spark está adicionando ao seu saldo de gastos. + Aguardando a Spark ver sua transferência. + A Spark adiciona ao seu saldo de gastos após {standard} confirmações, em cerca de {minutes} minutos. + Esperar + Depósitos resgatados + Depósitos em andamento + 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. Disponível Onchain Gastos + Sua poupança não cobre esta transferência e suas taxas. Tente um valor menor. + Saldo de Poupança Insuficiente O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}. Saldo de gastos Máximo + Transfira mais de ₿ {amount} para cobrir as taxas de adicioná-la ao seu saldo de gastos. + Valor muito baixo 25% + Transferir\n<accent>para gastos</accent> Para gastos + As taxas estão {amount} mais altas porque as taxas de rede ou seu saldo de poupança mudaram enquanto você estava nesta tela. Deslize novamente para confirmar. + Taxas alteradas + Pronto em poucos minutos + Após 3 confirmações, cerca de 30 minutos Taxa de serviço Taxa da rede + O Bitkit não conseguiu obter as taxas atuais desta transferência. Verifique sua conexão e tente novamente. + Taxas indisponíveis + Taxa de gastos Total + até + Começar + Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. + Transferir\n<accent>para gastos</accent> Saldo de gastos + Instantâneo paga ao provedor para adicionar sua transferência ao saldo de gastos antes de ela ser confirmada, normalmente em poucos minutos.\n\nDepois aguarda 3 confirmações, cerca de 30 minutos, com uma taxa menor. + Transfer\n<accent>speed</accent> Status Suporte Reserva Total de Canais Anchor @@ -234,10 +278,16 @@ Por favor\n<accent>confirme</accent> Transf. fundos Deslizar Para Transferir + Abrir Trezor Connect TRANSFERÊNCIA EM ANDAMENTO + Começar + Use seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. + Saldo de\n<accent>Gastos</accent> Transferência bem-sucedida Seus fundos foram transferidos. Você já pode usar esses fundos imediatamente. + Seus fundos foram transferidos e seu saldo de gastos está pronto para ser usado. Fundos transferidos\n<accent>para poupança</accent> + Fundos transferidos\n<accent>para gastos</accent> Por favor, espere que a Bitkit se conecte à rede de pagamento (±10 segundos). Por favor, espere que a Bitkit se conecte à rede bitcoin (±10 segundos). Saldos da Carteira @@ -550,6 +600,7 @@ Contatos Perfil Ajustes + Dados de saída do Spark Tags Histórico de transações Boosts e transferências @@ -1238,11 +1289,16 @@ Taxa de rede Você receberá Taxa de serviço + Taxa do Spark Sua transferência foi iniciada e está sendo <accent>liquidada onchain</accent>. Seu saldo de poupança será atualizado automaticamente quando ela for concluída. Transferência\n<accent>a caminho</accent> + Não foi possível mover seu saldo do Spark para a poupança; ele continua no saldo de gastos. + Não foi possível mover seu saldo do Spark para a poupança; ele continua no saldo de gastos. Suas conexões estão sendo movidas para a poupança. <accent>Conectando</accent>\nà rede Reconecte seu dispositivo de hardware, ele parece estar desconectado do seu telefone. Reconectar Dispositivo de Hardware + Assine com\n<accent>seu dispositivo</accent> + Transação\n<accent>assinada</accent> TRANSFERÊNCIA PRONTA EM %s Transferência indisponível As transferências automáticas para seu saldo de gastos não estão mais disponíveis. Use seu próprio nó ou configure uma conexão com outro provedor. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1fece40c5e..81321c2947 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -97,20 +97,50 @@ Depende da taxa Transferir de Outra Carteira Transferir da carteira HW + A forma mais fácil é usar as suas poupanças Bitkit ou enviar bitcoin de uma carteira diferente. + Spark + Taxa de resgate + %1$d/3 confirmações + Depósito + A Spark está a adicioná-lo ao seu saldo de gastos. + A aguardar que a Spark veja a sua transferência. + A Spark adiciona-o ao seu saldo de gastos após {standard} confirmações, dentro de cerca de {minutes} minutos. + Esperar + Depósitos resgatados + Depósitos em curso + 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. Saldo de Gastos Transfira para seu <accent>saldo de gastos</accent> Transferir do Saldo de Poupança Setup Manual + Transferir\n<accent>para gastos</accent> Transf. fundos Por favor\n<accent>confirme</accent> Deslizar Para Transferir + Abrir Trezor Connect 25% Saldo de gastos Máximo + Transfira mais de ₿ {amount} para cobrir as taxas de a adicionar ao seu saldo de gastos. + Montante demasiado baixo O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}. Taxa da rede + A Bitkit não conseguiu obter as taxas atuais desta transferência. Verifique a sua ligação e tente novamente. + Taxas indisponíveis + Taxa de gastos Taxa de serviço Para gastos + As taxas estão {amount} mais altas porque as taxas de rede ou o seu saldo de poupança mudaram enquanto estava neste ecrã. Deslize novamente para confirmar. + As taxas mudaram + Pronto em poucos minutos + Após 3 confirmações, cerca de 30 minutos Total + até + Começar + Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. + Transferir\n<accent>para gastos</accent> Transferir\n<accent>para poupança</accent> Transfira seu saldo de gastos para sua poupança para armazenar seu Bitcoin a longo prazo e garantir seu futuro. Começar @@ -128,7 +158,9 @@ Os fundos ainda não foram transferidos. A Bitkit tentará iniciar a transferência durante os próximos <accent>30 minutos</accent>. Por favor, mantenha o aplicativo aberto. Transferência bem-sucedida Fundos transferidos\n<accent>para poupança</accent> + Fundos transferidos\n<accent>para gastos</accent> Seus fundos foram transferidos. Você já pode usar esses fundos imediatamente. + Seus fundos foram transferidos e seu saldo de gastos está pronto para ser usado. Conexões Lightning <accent>Setup manual</accent> Você pode usar um nó externo para abrir manualmente uma conexão Lightning. Digite os detalhes do nó para continuar. @@ -144,8 +176,12 @@ Setup dos Pagamentos Instantâneos falhou Ocorreu um erro ao configurar seu saldo de gastos. {raw} Gastos + A sua poupança não cobre esta transferência e as respetivas taxas. Tente um montante menor. + Saldo de Poupança Insuficiente Poupança Saldo de gastos + Instantâneo paga ao fornecedor para adicionar a sua transferência ao saldo de gastos antes de ser confirmada, normalmente em poucos minutos.\n\nDepois aguarda 3 confirmações, cerca de 30 minutos, com uma taxa mais baixa. + Transfer\n<accent>speed</accent> Capacidade de recebimento Nó Lightning ID do LDK Node @@ -226,14 +262,28 @@ Tempo de Sinc. da Carteira Lightning Tempo do Snapshot Rapid Gossip Sync Tempo de Sinc. das Pontuações de Pathfinding + A Spark ainda não viu a sua transferência. É adicionada após 3 confirmações; pode sair deste ecrã. + Pagar ₿ {amount} + Instantâneo custa agora ₿ {amount}. Pague-o ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa mais baixa. + A adicionar aos gastos + Vista pela Spark + Transferência enviada + Instantâneo não está disponível para esta transferência. A Spark adiciona-a ao seu saldo de gastos após 3 confirmações, cerca de 30 minutos. + Continuar Usando o Bitkit Tempo de Atualização do Cache de Taxa Capacidade de Entrada Limite do Próximo HTLC de Saída Mínimo do Próximo HTLC de Saída + Antes de transferir fundos de seu saldo de poupança, receba bitcoin na sua carteira Bitkit. + Financiar Carteira + Não há Fundos Disponíveis Máximo do HTLC de Entrada Mínimo do HTLC de Entrada Altura do Arquivo do Monitor de Canal TRANSFERÊNCIA EM ANDAMENTO + Começar + Use seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. + Saldo de\n<accent>Gastos</accent> Começar Configure o seu saldo de despesas para desfrutar de transações instantâneas e económicas com amigos, familiares e comerciantes. Ativar\nLightning\n<accent>pagamentos</accent> @@ -563,6 +613,7 @@ Histórico de transações Boosts e transferências Ajustes + Dados de saída do Spark Widgets Tags Perfil @@ -1207,11 +1258,16 @@ Taxa de rede Vai receber Taxa de serviço + Taxa do Spark A sua transferência foi iniciada e está a ser <accent>liquidada on-chain</accent>. O saldo de poupança será atualizado automaticamente quando terminar. Transferência\n<accent>a caminho</accent> + Não foi possível mover o saldo do Spark para a poupança; continua no saldo de gastos. + Não foi possível mover o saldo do Spark para a poupança; continua no saldo de gastos. As suas ligações estão a ser movidas para a poupança. <accent>A ligar</accent>\nà rede Volte a ligar o seu dispositivo de hardware; parece estar desligado do telemóvel. Voltar a ligar o dispositivo + Assine com\n<accent>o seu dispositivo</accent> + Transação\n<accent>assinada</accent> TRANSFERÊNCIA PRONTA EM %s Transferência indisponível As transferências automáticas para o seu saldo de gastos já não estão disponíveis. Use o seu próprio nó ou configure uma ligação com outro fornecedor. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c59eb8f103..3f8d38a426 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -174,6 +174,7 @@ Использовать Другой Кошелёк Перевести с аппаратного кошелька Баланс Расходов + Самый простой вариант — использовать ваши сбережения Bitkit или отправить биткоин с другого кошелька. Пополните свой <accent>Баланс Расходов</accent> Ручная Настройка Входящая ёмкость @@ -184,6 +185,9 @@ Архивная высота мониторинга канала Лимит след. исходящего HTLC Мин. след. исходящего HTLC + Прежде чем вы сможете перевести средства со своего баланса сбережений, вам нужно отправить биткойны в ваш кошелёк Bitkit. + Пополнить кошелёк + Недостаточно Средств ID Узла LDK Lightning Узел Время синхронизации Lightning кошелька @@ -222,16 +226,56 @@ Пожалуйста, подождите, ваш перевод средств выполняется. Это займёт <accent>±10 секунд.</accent> Средства\n<accent>в Процессе Перевода</accent> Время синхронизации оценок маршрутизации + Spark ещё не увидел ваш перевод. Он будет зачислен после 3 подтверждений; можно покинуть этот экран. + Оплатить ₿ {amount} + Мгновенно теперь стоит ₿ {amount}. Оплатите или дождитесь 3 подтверждений, около 30 минут, с меньшей комиссией. + Зачисление на расходы + Виден Spark + Перевод отправлен + Мгновенно недоступно для этого перевода. Spark зачислит его на баланс расходов после 3 подтверждений, примерно через 30 минут. + Продолжить Использование Bitkit + Spark + Комиссия за зачисление + %1$d/3 подтверждений + Депозит + Spark зачисляет их на ваш расходный баланс. + Ждём, пока Spark увидит ваш перевод. + Spark зачислит их на ваш расходный баланс после {standard} подтверждений, примерно через {minutes} минут. + Ждать + Зачисленные депозиты + Депозиты в обработке + Провайдер + Spark через Breez + Без ограничений + Этот баланс хранится в Spark, которым управляют Lightspark, Breez и Flashnet. Он в безопасности, пока хотя бы один из них действует честно. Они могут приостановить доступ, а выход без них требует ончейн-вывода. Доступно Onchain Расходы + Ваших сбережений не хватает на этот перевод и его комиссии. Попробуйте меньшую сумму. + Недостаточно Сбережений Сумма, которую вы можете перевести на баланс расходов, в настоящее время ограничена ₿ {amount}. Максимум Баланса Расходов + Переведите больше ₿ {amount}, чтобы покрыть комиссии за зачисление на баланс расходов. + Слишком маленькая сумма 25% + Перевод\n<accent>на Расходы</accent> На Баланс Расходов + Комиссии выросли на {amount}, потому что ставки комиссий или баланс сбережений изменились, пока вы были на этом экране. Проведите ещё раз для подтверждения. + Комиссии изменились + Готово через несколько минут + После 3 подтверждений, около 30 минут Сервисные Комиссии Сетевые Комиссии + Bitkit не смог получить текущие комиссии за этот перевод. Проверьте соединение и попробуйте снова. + Комиссии недоступны + Комиссия расходов Итого + до + Начать + Переведите средства на свой баланс расходов, чтобы наслаждаться мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. + Перевод\n<accent>на Расходы</accent> Баланс Расходов + Мгновенно платит провайдеру, чтобы зачислить перевод на баланс расходов до подтверждения, обычно за несколько минут.\n\nПозже ждёт 3 подтверждений, около 30 минут, с меньшей комиссией. + Transfer\n<accent>speed</accent> Статус Поддержка Общий резерв Anchor каналов @@ -242,10 +286,16 @@ Пожалуйста,\n<accent>Подтвердите</accent> Перевод Средств Проведите для Перевода + Открыть Trezor Connect ПЕРЕВОД В ПРОЦЕССЕ + Начать + Пополните свой баланс расходов, чтобы наслаждаться мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. + Расходы\n<accent>Баланс</accent> Перевод Выполнен Успешно Ваши средства переведены. Вы можете использовать эти средства немедленно. + Ваши средства переведены, и ваш баланс расходов готов к использованию. Средства Переведены\n<accent>в Сбережения</accent> + Средства Переведены\n<accent>на Расходы</accent> Пожалуйста, подождите, пока Bitkit подключается к платёжной сети (±10 секунд). Пожалуйста, подождите, пока Bitkit подключается к сети биткоин (±10 секунд). Балансы кошелька @@ -561,6 +611,7 @@ Контакты Профиль Настройки + Данные выхода из Spark Теги Журнал Транзакций Ускорения и Переводы @@ -1254,11 +1305,16 @@ Сетевая комиссия Вы получите Сервисная комиссия + Комиссия Spark Ваш перевод инициирован и <accent>проводится в блокчейне</accent>. Баланс сбережений обновится автоматически после завершения. Перевод\n<accent>в пути</accent> + Не удалось перевести баланс Spark в сбережения, он остаётся в балансе расходов. + Не удалось перевести баланс Spark в сбережения, он остаётся в балансе расходов. Ваши соединения переводятся в сбережения. <accent>Подключение</accent>\nк сети Переподключите аппаратное устройство: похоже, оно отключилось от телефона. Переподключите Аппаратное Устройство + Подпишите на\n<accent>устройстве</accent> + Транзакция\n<accent>подписана</accent> ПЕРЕВОД БУДЕТ ГОТОВ ЧЕРЕЗ %s Перевод недоступен Автоматические переводы на баланс расходов больше недоступны. Используйте собственный узел или настройте подключение к другому провайдеру. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0581f041af..2fb23120cf 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -311,6 +311,7 @@ Use Other Wallet Transfer from HW wallet Spending Balance + The easiest option is to use your Bitkit savings or send bitcoin from a different wallet. Fund your <accent>spending balance</accent> Manual Setup Inbound Capacity @@ -321,6 +322,9 @@ Channel Monitor Archival Height Next Outbound HTLC Limit Next Outbound HTLC Min + Before you can transfer funds from your savings balance, you need to send bitcoin to your Bitkit wallet. + Fund Wallet + No Available Funds LDK Node ID Lightning Node Lightning Wallet Sync Time @@ -355,6 +359,7 @@ Network fee You\'ll receive Service fee + Spark fee Transfer all Transfer\n<accent>interrupted</accent> Funds were not transferred yet. Bitkit will try to initiate the transfer during the next <accent>30 minutes</accent>. Please keep your app open. @@ -366,17 +371,60 @@ Funds\n<accent>in transfer</accent> Your transfer has been initiated and is <accent>settling on-chain</accent>. Your savings balance will update automatically once it completes. Transfer\n<accent>on the way</accent> + Your Spark balance couldn\'t move to savings and stays in your spending balance. + Your Spark balance couldn\'t move to savings and stays in your spending balance. Your connections are moving to savings. Pathfinding Scores Sync Time + Spark hasn\'t seen your transfer yet. It\'s added after 3 confirmations; you can leave this screen. + Pay ₿ {amount} + Instant now costs ₿ {amount}. Pay it, or wait for 3 confirmations, about 30 minutes, at a lower fee. + Adding To Spending + Seen By Spark + Transfer Sent + Instant isn\'t available for this transfer. Spark adds it to your spending balance after 3 confirmations, about 30 minutes. + Continue Using Bitkit + Spark + Claim fee + %1$d/3 confirmations + Deposit + Spark is adding it to your spending balance. + Waiting for Spark to see your transfer. + Spark adds it to your spending balance after {standard} confirmations, about {minutes} minutes. + Wait + Claimed deposits + Deposits in progress + 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. Spendable Onchain Spending + Your savings cannot cover this transfer and its fees. Try a smaller amount. + Insufficient Savings The amount you can transfer to your spending balance is currently limited to ₿ {amount}. Spending Balance Maximum + Transfer more than ₿ {amount}, so it covers the fees to add it to your spending balance. + Amount Too Small 25% + Transfer\n<accent>to spending</accent> + ≈ To spending + Fees are {amount} higher because fee rates or your savings balance changed while you were on this screen. Swipe again to confirm. + Fees changed + Ready in a few minutes + After 3 confirmations, about 30 minutes Service fees Network fees + Bitkit couldn\'t get the current fees for this transfer. Check your connection and try again. + Fees Unavailable + Spending fee Total + up to + Get Started + Transfer funds to your spending balance to enjoy instant and cheap transactions with friends, family, and merchants. + Transfer\n<accent>to spending</accent> Spending balance + Instant pays the provider to add your transfer to your spending balance before it confirms, usually within a few minutes.\n\nLater waits for 3 confirmations, about 30 minutes, at a lower fee. + Transfer\n<accent>speed</accent> Status Support <accent>Connecting</accent>\nto network @@ -388,13 +436,21 @@ Please\n<accent>confirm</accent> Transfer Funds Swipe To Transfer + Open Trezor Connect Please reconnect your hardware device, it appears to be disconnected from your phone. Reconnect Hardware Device + Sign with\n<accent>your device</accent> + Transaction\n<accent>signed</accent> TRANSFER IN PROGRESS + Get Started + Fund your spending balance to enjoy instant and cheap transactions with friends, family, and merchants. + Spending\n<accent>Balance</accent> TRANSFER READY IN %s Transfer Successful Your funds have been transferred. You are able to use these funds immediately. + Your funds have been transferred and your spending balance is ready to use. Funds moved\n<accent>to savings</accent> + Funds moved\n<accent>to spending</accent> Transfer Unavailable Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider. <accent>Manual setup</accent>\nrequired @@ -854,6 +910,7 @@ Contacts Profile Settings + Spark exit data Tags Transaction Log Boosts & Transfers diff --git a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt index a76ca21675..110f3521fd 100644 --- a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt +++ b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt @@ -28,6 +28,7 @@ import to.bitkit.models.WalletScope import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo import to.bitkit.repositories.CurrencyRepo +import to.bitkit.repositories.SparkRepo import to.bitkit.services.MigrationService import to.bitkit.test.BaseUnitTest import java.math.BigDecimal @@ -58,6 +59,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { private val settingsStore: SettingsStore = mock() private val clock: Clock = mock() private val backupRepo: BackupRepo = mock() + private val sparkRepo: SparkRepo = mock() private val migrationService: MigrationService = mock() private val isRestoring = MutableStateFlow(false) private val isShowingMigrationLoading = MutableStateFlow(false) @@ -74,6 +76,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { whenever(migrationService.isShowingMigrationLoading).thenReturn(isShowingMigrationLoading) whenever { migrationService.needsPostMigrationSync() }.thenReturn(false) whenever(clock.now()).thenReturn(NOW) + whenever { sparkRepo.markWithdrawalAsTransfer(any()) }.thenReturn(false) whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())).thenReturn( Result.success( ConvertedAmount( @@ -99,6 +102,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { currencyRepo = currencyRepo, settingsStore = settingsStore, ), + sparkRepo = sparkRepo, ) } @@ -187,6 +191,21 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { verify(activityRepo).markOnchainActivityAsSeen("txid456", WalletScope.default) } + @Test + fun `onchain receive from a spark withdrawal is a transfer with no received sheet`() = test { + val details = mock { + on { amountSats } doReturn 5000L + } + whenever(activityRepo.shouldShowReceivedSheet(any(), any())).thenReturn(true) + whenever(sparkRepo.markWithdrawalAsTransfer("txid456")).thenReturn(true) + + val result = sut(NotifyPaymentReceived.Command.Onchain(txid = "txid456", details = details)) + + assertTrue(result.getOrThrow() is NotifyPaymentReceived.Result.Skip) + verify(activityRepo).handleOnchainTransactionReceived("txid456", details) + verify(activityRepo, never()).shouldShowReceivedSheet(any(), any()) + } + @Test fun `onchain payment returns Skip when shouldShowReceivedSheet is false`() = test { val details = mock { diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 85a4e812de..66db95505f 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -38,6 +38,7 @@ import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -81,6 +82,7 @@ import to.bitkit.models.PaykitUsdtStateBackup import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 import to.bitkit.models.SettingsBackupV1 +import to.bitkit.models.SparkExitBackupV1 import to.bitkit.models.TransportType import to.bitkit.models.WalletBackupV1 import to.bitkit.models.WalletScope @@ -138,6 +140,7 @@ class BackupRepoTest : BaseUnitTest() { private val paykitAllowanceStore = mock() private val keychain = mock() private val onchainSendAttemptStore = mock() + private val sparkRepo = mock() private val vssStoreIdProvider = mock() private val preActivityMetadataRepo = mock() private val lightningService = mock() @@ -218,6 +221,11 @@ class BackupRepoTest : BaseUnitTest() { }.thenReturn(Result.success(Unit)) whenever { vssBackupClient.listKeys() }.thenReturn(Result.success(emptyList())) + whenever { sparkRepo.exitBackup() }.thenReturn(Result.success(null)) + whenever { sparkRepo.restoreExitBackup(any(), any()) }.thenReturn(Result.success(Unit)) + whenever(sparkRepo.exitStateChanged).thenReturn(MutableSharedFlow()) + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) + sut = createSut() } @@ -251,6 +259,54 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `spark exit backup uploads the exported state and restores it before the wallet`() = test { + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "{\"pedigrees\":[]}") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val data = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), data.capture()) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = data.firstValue, version = 1)) + ) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).restoreExitBackup(backup, 0) + verify(vssBackupClient).getObject(BackupCategory.WALLET.name) + } + } + + @Test + fun `spark exit backup uploads when Spark was ready before observing started`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState(isSupported = true, isReady = true))) + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(6_000) + runCurrent() + + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `spark exit backup uploads nothing while Spark is not connected`() = test { + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + @Test fun `wallet backup waits for submission and includes the latest pending state`() = test { val statuses = MutableStateFlow( @@ -3037,6 +3093,7 @@ class BackupRepoTest : BaseUnitTest() { keychain = keychain, onchainSendAttemptStore = onchainSendAttemptStore, lightningRepo = Provider { lightningRepo }, + sparkRepo = sparkRepo, vssStoreIdProvider = vssStoreIdProvider, preActivityMetadataRepo = preActivityMetadataRepo, lightningService = lightningService, diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 18c097ea37..8e3c2ec285 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -89,6 +89,7 @@ import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.test.idleSparkRepo import to.bitkit.utils.AppError import to.bitkit.utils.LdkError import to.bitkit.utils.UrlValidator @@ -102,6 +103,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant @OptIn(kotlin.time.ExperimentalTime::class, ExperimentalCoroutinesApi::class) class LightningRepoTest : BaseUnitTest() { @@ -123,6 +125,7 @@ class LightningRepoTest : BaseUnitTest() { private lateinit var sut: LightningRepo private val lightningService = mock() + private val sparkRepo = idleSparkRepo() private val settingsStore = mock() private val coreService = mock() private val keychain = mock() @@ -164,6 +167,7 @@ class LightningRepoTest : BaseUnitTest() { vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, ) } @@ -229,6 +233,7 @@ class LightningRepoTest : BaseUnitTest() { activityRepo = mock(), hwWalletRepo = hardware, connectionRecovery = connectionRecoveryFixture(settingsStore), + sparkRepo = sparkRepo, ) } @@ -1098,6 +1103,50 @@ class LightningRepoTest : BaseUnitTest() { verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + @Test + fun `pending wallet recovery prevents spark payment dispatch`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(keychain.exists(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name)).thenReturn(true) + var beforeSend = false + + val result = sut.payInvoice("invoice", 1_000uL, onBeforeSend = { + beforeSend = true + true + }) + + assertIs(result.exceptionOrNull()) + assertFalse(beforeSend) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `spark payment keeps the deadline and the fee limit`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(Result.success("hash")) + val deadline = Instant.fromEpochSeconds(1_800_000_000) + + val result = sut.payInvoice("invoice", 1_000uL, deadline, maxTotalRoutingFeeMsat = 10_000uL) { true } + + assertEquals("hash", result.getOrThrow()) + verify(sparkRepo).payInvoice("invoice", 1_000uL, deadline, 10_000uL) + } + + @Test + fun `restore beginning during spark payment authorization prevents dispatch`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val result = sut.payInvoice("invoice", 1_000uL, onBeforeSend = { + whenever(keychain.exists(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name)).thenReturn(true) + true + }) + + assertIs(result.exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun `restore beginning during payment authorization prevents dispatch`() = test { startNodeForTesting() @@ -2085,6 +2134,7 @@ class LightningRepoTest : BaseUnitTest() { vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) whenever(coreService.activity).thenReturn(mock()) @@ -2510,6 +2560,7 @@ class LightningRepoTest : BaseUnitTest() { onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -2580,6 +2631,7 @@ class LightningRepoTest : BaseUnitTest() { onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -2661,6 +2713,7 @@ class LightningRepoTest : BaseUnitTest() { onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -3140,6 +3193,7 @@ class LightningRepoTest : BaseUnitTest() { vssBackupClientLdk = vssBackupClientLdk, urlValidator = failingValidator, electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, ) sutWithFailingValidator.setInitNodeLifecycleState() whenever(lightningService.node).thenReturn(mock()) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt index 8e8cc711b9..cb79fdac3d 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt @@ -3,13 +3,17 @@ package to.bitkit.repositories import com.synonym.paykit.PaymentOutcome import org.junit.Before import org.junit.Test +import org.lightningdevkit.ldknode.PaymentStatus import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.models.WalletScope import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus class PaykitAllowancePayerTest : BaseUnitTest() { private val paymentProofRepo = mock() @@ -18,10 +22,43 @@ class PaykitAllowancePayerTest : BaseUnitTest() { private val requestId = PaykitPaymentRequestId(paymentRequestId = "req-1", counterparty = "payee") private val txid = "ab".repeat(32) + private val paymentHash = "cd".repeat(32) @Before fun setUp() = test { whenever(paymentProofRepo.hasVerifiedOnchainProof(any(), any())).thenReturn(false) + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(emptyList()) + whenever(lightningRepo.canListSparkPayments()).thenReturn(true) + whenever(lightningRepo.sparkLightningSend(any())).thenReturn(SparkLightningSend.NotFound) + } + + @Test + fun `a lightning send the node does not know is read from spark`() = test { + val statuses = mapOf( + SparkPaymentStatus.COMPLETED to PaymentStatus.SUCCEEDED, + SparkPaymentStatus.PENDING to PaymentStatus.PENDING, + SparkPaymentStatus.FAILED to PaymentStatus.FAILED, + ) + for ((spark, node) in statuses) { + whenever(lightningRepo.sparkLightningSend(paymentHash)).thenReturn(SparkLightningSend.Found(spark, null)) + + assertEquals(node, sut.lightningPaymentStatus(paymentHash)) + } + } + + @Test + fun `a lightning send neither rail knows is one the wallet never made`() = test { + assertTrue(sut.canListLightningPayments()) + assertNull(sut.lightningPaymentStatus(paymentHash)) + } + + @Test + fun `a spark send is never read as unsent while spark cannot list its payments`() = test { + whenever(lightningRepo.canListSparkPayments()).thenReturn(false) + whenever(lightningRepo.sparkLightningSend(paymentHash)).thenReturn(SparkLightningSend.Unavailable) + + assertFalse(sut.canListLightningPayments()) + assertEquals(PaymentStatus.PENDING, sut.lightningPaymentStatus(paymentHash)) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt index 55fc7fc43e..b6869c1e77 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt @@ -63,6 +63,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { private val executorEvents = MutableSharedFlow(extraBufferCapacity = 8) private val nodeEvents = MutableSharedFlow(extraBufferCapacity = 8) private val lightningState = MutableStateFlow(LightningState()) + private val isSparkSynced = MutableStateFlow(false) private val terms = fixtures.terms() private val clock = object : Clock { override fun now(): Instant = PaykitAllowanceFixtures.now @@ -97,6 +98,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { whenever(executor.classifyAboveLimit(any(), any(), any())).thenReturn(false) whenever(lightningRepo.nodeEvents).thenReturn(nodeEvents) whenever(lightningRepo.lightningState).thenReturn(lightningState) + whenever(lightningRepo.isSparkSynced).thenReturn(isSparkSynced) whenever(activityRepo.setContact(any(), any(), any(), any())).thenReturn(Result.success(Unit)) whenever(sdk.listAllowances(any())).thenAnswer { records } whenever(sdk.linkedPeers()).thenReturn(emptyList()) @@ -894,6 +896,18 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { verify(executor).settleOpenLightningAttempts() } + @Test + fun `spark syncing settles attempts left open while it could not list payments`() = test { + sut.activate(identity) + whenever(executor.activeIdentity).thenReturn(identity) + clearInvocations(executor) + + isSparkSynced.value = true + + verify(executor).recover(identity) + verify(executor).settleOpenLightningAttempts() + } + // endregion // region Helpers diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index c6f146bb78..9001d10569 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1,6 +1,7 @@ package to.bitkit.repositories import android.content.Context +import breez_sdk_spark.SdkException import com.synonym.bitkitcore.BroadcastException import com.synonym.paykit.BillingPeriod import com.synonym.paykit.ConversionRate @@ -75,6 +76,7 @@ import to.bitkit.models.WalletScope import to.bitkit.services.CoreService import to.bitkit.services.PaykitSdkOperationLock import to.bitkit.services.PaykitSdkService +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.ui.screens.wallets.send.HwSendRequest import to.bitkit.ui.screens.wallets.send.HwSendViewModel @@ -93,6 +95,7 @@ import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus private val lenientJson = Json { ignoreUnknownKeys = true } @@ -812,6 +815,55 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(storedProofs.isEmpty()) } + @Test + fun `lightning proof settles from spark when its event was missed`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.Bolt11.rawValue) + whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever( + paykitSdkService.submitPaymentProof(any(), any(), any(), any(), any(), isNull(), isNull(), isNull(), any()) + ).thenReturn(record) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + + for (pending in listOf(SparkLightningSend.Unavailable, SparkLightningSend.NotFound)) { + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)).thenReturn(pending) + paymentProofRepo().reconcile() + assertEquals(PAYMENT_HASH, storedProofs.single().paymentIdentifier) + } + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)) + .thenReturn(SparkLightningSend.Found(SparkPaymentStatus.COMPLETED, PREIMAGE)) + paymentProofRepo().reconcile() + + val proofCaptor = argumentCaptor() + verify(paykitSdkService).submitPaymentProof( + any(), any(), any(), any(), proofCaptor.capture(), isNull(), isNull(), isNull(), any(), + ) + assertEquals( + """{"data":"$PREIMAGE","type":"${PaykitPaymentProofKind.Lightning.type}"}""", + proofCaptor.firstValue, + ) + assertTrue(storedProofs.isEmpty()) + } + + @Test + fun `lightning proof is removed when spark failed the send`() = test { + whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(paymentRequestRecord())) + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)) + .thenReturn(SparkLightningSend.Found(SparkPaymentStatus.FAILED, null)) + val request = paymentRequest(MethodId.Bolt11.rawValue) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + + paymentProofRepo().reconcile() + + assertTrue(storedProofs.isEmpty()) + } + @Test fun `allowance proof is submitted with its allowance id`() = test { val record = paymentRequestRecord() @@ -1013,6 +1065,7 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { LdkError(NodeException.PersistenceFailed("io")), NodeException.DuplicatePayment("pending"), AppError("payment outcome unknown"), + SdkException.Generic("spark send timed out"), ) val record = paymentRequestRecord() whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) @@ -1064,6 +1117,8 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { NodeException.InvalidInvoice("invalid"), NodeException.InvalidAmount("invalid"), LdkError(NodeException.PaymentSendingFailed("no route")), + SparkError.SendRefused("Spark fee over the limit"), + to.bitkit.utils.AppError(SparkError.SendRefused("Spark could not prepare the payment")), ) for (error in errors) { val request = paymentRequest(MethodId.Bolt11.rawValue) diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt index 9c9b18c55d..39fc8adc82 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt @@ -54,6 +54,7 @@ class PrivatePaykitAllowancePaymentTest : BaseUnitTest(StandardTestDispatcher()) private val cacheStore = mock() private val settingsStore = mock() private val lightningRepo = mock() + private val sparkRepo = mock() private val publicPaykitRepo = mock() private val coreService = mock() private val clock = mock() @@ -75,6 +76,8 @@ class PrivatePaykitAllowancePaymentTest : BaseUnitTest(StandardTestDispatcher()) } } PublicPaykitRepo.lightningRouteHintsValidator = { true } + whenever { sparkRepo.receivedLightningPaymentHashes() }.thenReturn(emptySet()) + whenever { sparkRepo.attemptedLightningPaymentHashes() }.thenReturn(emptySet()) sut = PrivatePaykitRepo( ioDispatcher = testDispatcher, @@ -84,6 +87,7 @@ class PrivatePaykitAllowancePaymentTest : BaseUnitTest(StandardTestDispatcher()) settingsStore = settingsStore, addressReservationRepo = mock(), lightningRepo = lightningRepo, + sparkRepo = sparkRepo, walletRepo = mock(), publicPaykitRepo = publicPaykitRepo, paymentRequestRepo = mock(), diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index a5327b4308..68dd141f07 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -112,6 +112,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { private val settingsStore = mock() private val addressReservationRepo = mock() private val lightningRepo = mock() + private val sparkRepo = mock() private val walletRepo = mock() private val publicPaykitRepo = mock() private val paymentRequestRepo = mock() @@ -196,6 +197,8 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { whenever { paymentRequestRepo.refreshEligibleTarget(any()) } .thenReturn(Result.success(PaykitPaymentRequestTargetCheck(null, isComplete = true))) whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) + whenever { sparkRepo.receivedLightningPaymentHashes() }.thenReturn(emptySet()) + whenever { sparkRepo.attemptedLightningPaymentHashes() }.thenReturn(emptySet()) whenever(coreService.getAddressUsage(any())).doSuspendableAnswer { it.getArgument>(0).associateWith { address -> Result.success(coreService.isAddressUsed(address)) @@ -3191,6 +3194,29 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.closeAndClear() } + @Test + fun `private Lightning invoice paid through Spark is replaced`() = test { + preparePrivateLightningContact() + val refreshedInvoice = "lnbcrt1refreshed" + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + .thenReturn(Result.success(refreshedInvoice)) + whenever(coreService.decode(refreshedInvoice)) + .thenReturn(Scanner.Lightning(lightningInvoice(refreshedInvoice, byteArrayOf(8, 8, 8)))) + whenever(sparkRepo.receivedLightningPaymentHashes()).thenReturn(setOf("090909")) + clearInvocations(paykitSdkService) + + sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() + runCurrent() + + val publication = argumentCaptor>() + verify(paykitSdkService).syncPrivatePaymentListsWithReservations(publication.capture(), eq(false)) + assertEquals( + PublicPaykitRepo.serializePayload(refreshedInvoice), + publication.firstValue.single().reservations.single().payload, + ) + sut.closeAndClear() + } + @Test fun `forced private Lightning refresh includes contacts loaded later`() = test { preparePrivateLightningContact() @@ -4446,6 +4472,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { settingsStore = settingsStore, addressReservationRepo = addressReservationRepo, lightningRepo = lightningRepo, + sparkRepo = sparkRepo, walletRepo = walletRepo, publicPaykitRepo = publicPaykitRepo, paymentRequestRepo = paymentRequestRepo, diff --git a/app/src/test/java/to/bitkit/repositories/SparkClaimOfferTest.kt b/app/src/test/java/to/bitkit/repositories/SparkClaimOfferTest.kt new file mode 100644 index 0000000000..8c9150b8bb --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkClaimOfferTest.kt @@ -0,0 +1,95 @@ +package to.bitkit.repositories + +import breez_sdk_spark.ClaimDeferredReason +import breez_sdk_spark.ClaimDepositOutcome +import breez_sdk_spark.ClaimDepositQuote +import breez_sdk_spark.FetchClaimDepositQuoteResponse +import org.junit.Test +import kotlin.test.assertEquals + +class SparkClaimOfferTest { + + @Test + fun `offers only the standard claim when no early claim is quoted`() { + val offer = SparkClaimOffer.from(TXID, 1u, quote(instant = null)) + + assertEquals(SparkClaimOffer.Standard(TXID, 1u, feeSats = 907uL, confirmations = 3u), offer) + } + + @Test + fun `leaves an early claim within the cap to the sdk`() { + val offer = SparkClaimOffer.from(TXID, 1u, quote(instant = early(feeSats = 900uL, maxFeeSats = 1_000uL))) + + assertEquals(SparkClaimOffer.Automatic(TXID, 1u, feeSats = 900uL, confirmations = 0u), offer) + } + + @Test + fun `offers a choice when the early claim costs more than the cap`() { + val offer = SparkClaimOffer.from( + TXID, + 1u, + quote(instant = early(feeSats = 1_350uL, maxFeeSats = 1_000uL, confirmations = 1u)), + ) + + assertEquals( + SparkClaimOffer.Choice( + txid = TXID, + vout = 1u, + earlyFeeSats = 1_350uL, + earlyConfirmations = 1u, + standardFeeSats = 907uL, + standardConfirmations = 3u, + ), + offer, + ) + } + + @Test + fun `offers a choice when automatic claiming is off`() { + val offer = SparkClaimOffer.from(TXID, 1u, quote(instant = early(feeSats = 900uL, maxFeeSats = null))) + + assertEquals(SparkClaimOffer.Choice(TXID, 1u, 900uL, 0u, 907uL, 3u), offer) + } + + @Test + fun `maps each claim outcome`() { + assertEquals(SparkEarlyClaim.Claimed, SparkEarlyClaim.from(ClaimDepositOutcome.Submitted)) + assertEquals( + SparkEarlyClaim.Waiting, + SparkEarlyClaim.from(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)), + ) + assertEquals( + SparkEarlyClaim.Repriced(1_500uL), + SparkEarlyClaim.from(ClaimDepositOutcome.Deferred(ClaimDeferredReason.MaxFeeExceeded(1_500uL, 1_350uL))), + ) + assertEquals( + SparkEarlyClaim.Declined, + SparkEarlyClaim.from(ClaimDepositOutcome.Deferred(ClaimDeferredReason.ProviderDeclined("busy"))), + ) + } + + private fun quote(instant: ClaimDepositQuote?) = FetchClaimDepositQuoteResponse( + amountSats = 15_000uL, + confirmations = 0u, + instant = instant, + mature = ClaimDepositQuote( + confirmationsRequired = 3u, + creditAmountSats = 14_093uL, + feeSats = 907uL, + maxFeeSats = 1_000uL, + isEstimate = false, + ), + ) + + private fun early(feeSats: ULong, maxFeeSats: ULong?, confirmations: UInt = 0u) = ClaimDepositQuote( + confirmationsRequired = confirmations, + creditAmountSats = 15_000uL - feeSats, + feeSats = feeSats, + maxFeeSats = maxFeeSats, + isEstimate = false, + ) + + private companion object { + const val TXID = "txid" + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt new file mode 100644 index 0000000000..dc56da0703 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -0,0 +1,572 @@ +package to.bitkit.repositories + +import breez_sdk_spark.BitcoinAddressDetails +import breez_sdk_spark.Bolt11InvoiceDetails +import breez_sdk_spark.ClaimDeferredReason +import breez_sdk_spark.ClaimDepositOutcome +import breez_sdk_spark.ClaimDepositQuote +import breez_sdk_spark.DepositInfo +import breez_sdk_spark.FeePolicy +import breez_sdk_spark.FetchClaimDepositQuoteResponse +import breez_sdk_spark.GetInfoResponse +import breez_sdk_spark.ImportUnilateralExitStateResponse +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentDetails +import breez_sdk_spark.PaymentMethod +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.PaymentType +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.SdkEvent +import breez_sdk_spark.SdkException +import breez_sdk_spark.SendOnchainFeeQuote +import breez_sdk_spark.SendOnchainSpeedFeeQuote +import breez_sdk_spark.SendPaymentMethod +import breez_sdk_spark.SparkHtlcDetails +import breez_sdk_spark.SparkHtlcStatus +import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.OnchainActivity +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.advanceUntilIdle +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore +import to.bitkit.env.Env +import to.bitkit.ext.create +import to.bitkit.ext.scopedActivityId +import to.bitkit.models.SparkExitBackupV1 +import to.bitkit.models.WalletScope +import to.bitkit.services.SparkError +import to.bitkit.services.SparkService +import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.ServiceError +import java.io.File +import java.math.BigInteger +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Instant +import com.synonym.bitkitcore.PaymentType as ActivityPaymentType + +@OptIn(ExperimentalCoroutinesApi::class) +class SparkRepoTest : BaseUnitTest() { + private companion object { + const val ADDRESS = "bcrt1qsavings" + } + + private val sparkService = mock() + private val activityRepo = mock() + private val sparkEvents = MutableSharedFlow() + private val cacheData = MutableStateFlow(AppCacheData()) + private val cacheStore = mock { on { data } doReturn cacheData } + private val contactResolver = mock() + private val now = Instant.fromEpochSeconds(1_800_000_000) + private val clock = object : Clock { + override fun now() = this@SparkRepoTest.now + } + + private fun createSut() = SparkRepo( + bgDispatcher = testDispatcher, + sparkService = sparkService, + activityRepo = { activityRepo }, + cacheStore = cacheStore, + contactResolver = { contactResolver }, + clock = clock, + ) + + @get:Rule + val tempFolder = TemporaryFolder() + + @Before + fun setUp() { + Env.initAppStoragePath(tempFolder.root.absolutePath) + whenever { sparkService.getInfo() }.thenReturn(GetInfoResponse("pubkey", 0uL, emptyMap(), 0uL)) + whenever { sparkService.listUnclaimedDeposits() }.thenReturn(emptyList()) + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + whenever(sparkService.events).thenReturn(sparkEvents) + whenever { activityRepo.getActivity(any(), any()) }.thenReturn(Result.success(null)) + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.networkName).thenReturn("regtest") + } + + @Test + fun `imports a restored exit backup once Spark connects`() = test { + whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) + val sut = createSut() + + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "state"), 0) + .getOrThrow() + verify(sparkService, never()).importExitState(any()) + + whenever(sparkService.isConnected).thenReturn(true) + sut.start(0).getOrThrow() + + verify(sparkService).importExitState("state") + assertFalse(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `records a send's fee once a sync reports it`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + + sparkEvents.emit(SdkEvent.PaymentSucceeded(sentPayment(fees = 0))) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + sparkEvents.emit(SdkEvent.Synced) + + val activities = argumentCaptor() + verify(activityRepo, times(2)).upsertActivity(activities.capture()) + assertEquals(listOf(0uL, 2uL), activities.allValues.map { (it as Activity.Lightning).v1.fee }) + } + + @Test + fun `marks a withdrawal's arrival as a transfer by the txid its send returned`() = test { + val arrival = OnchainActivity.create( + id = "arrival", + txType = ActivityPaymentType.RECEIVED, + txId = "withdrawal", + value = 4_917uL, + fee = 0uL, + address = "bc1q", + timestamp = 1uL, + ) + whenever { activityRepo.getOnchainActivityByTxId(eq("withdrawal"), any()) }.thenReturn(arrival) + whenever { activityRepo.updateActivity(any(), any(), any()) }.thenReturn(Result.success(Unit)) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + val sent = sentPayment(fees = 1_470).copy( + method = PaymentMethod.WITHDRAW, + details = PaymentDetails.Withdraw("withdrawal"), + ) + whenever { sparkService.send(any()) }.thenReturn(sent) + val sut = createSut() + + assertFalse(sut.markWithdrawalAsTransfer("withdrawal")) + sut.withdrawAll(ADDRESS).getOrThrow() + + assertTrue(sut.markWithdrawalAsTransfer("withdrawal")) + assertFalse(sut.markWithdrawalAsTransfer("other")) + val updated = argumentCaptor() + verify(activityRepo).updateActivity(eq("arrival"), updated.capture(), any()) + assertTrue((updated.firstValue as Activity.Onchain).v1.isTransfer) + } + + @Test + fun `lists a withdrawal with its fee and marks its arrival in Savings as a transfer`() = test { + val arrival = OnchainActivity.create( + id = "arrival", + txType = ActivityPaymentType.RECEIVED, + txId = "withdrawal", + value = 4_917uL, + fee = 0uL, + address = "bc1q", + timestamp = 1uL, + ) + whenever { activityRepo.getOnchainActivityByTxId(eq("withdrawal"), any()) }.thenReturn(arrival) + whenever { activityRepo.updateActivity(any(), any(), any()) }.thenReturn(Result.success(Unit)) + val withdrawal = sentPayment(fees = 1_470).copy( + method = PaymentMethod.WITHDRAW, + details = PaymentDetails.Withdraw("withdrawal"), + ) + whenever { sparkService.listPayments() }.thenReturn(listOf(withdrawal)) + whenever(sparkService.isConnected).thenReturn(true) + + val sut = createSut() + sut.start(0).getOrThrow() + + val updated = argumentCaptor() + verify(activityRepo).updateActivity(eq("arrival"), updated.capture(), any()) + assertTrue((updated.firstValue as Activity.Onchain).v1.isTransfer) + assertEquals(listOf(SparkWithdrawal("withdrawal", 128uL, 1_470uL)), sut.state.value.withdrawals) + } + + @Test + fun `skips an exit backup from another network`() = test { + val sut = createSut() + + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "mainnet", exitState = "state"), 0) + .getOrThrow() + + assertFalse(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `lists a broadcast deposit as pending until Spark lists it`() = test { + val sut = createSut() + + sut.onDepositBroadcast("txid", 2_500uL) + + val deposit = sut.state.value.deposits.single() + assertEquals("txid", deposit.txid) + assertEquals(false, deposit.isClaimed) + assertEquals(2_500uL, sut.state.value.pendingDepositSats) + } + + @Test + fun `instant claims early at once when the offer is within the ceiling`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn(ClaimDepositOutcome.Submitted) + whenever { sparkService.listPayments() }.thenReturn(emptyList(), listOf(depositPayment())) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + verify(sparkService).claimDeposit("txid", 0u, 300uL) + assertEquals(SparkDepositClaim.Claimed, sut.depositClaims.value["txid"]) + } + + @Test + fun `instant asks the user when the early fee is over the ceiling`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 900uL)) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + val claim = assertIs(sut.depositClaims.value["txid"]) + assertEquals(900uL, claim.offer.earlyFeeSats) + verify(sparkService, never()).claimDeposit(any(), any(), any()) + } + + @Test + fun `paying a repriced claim claims at the new fee`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 900uL)) + whenever { sparkService.claimDeposit("txid", 0u, 900uL) }.thenReturn(ClaimDepositOutcome.Submitted) + val sut = createSut() + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + sut.payRepricedClaim("txid") + advanceUntilIdle() + + verify(sparkService).claimDeposit("txid", 0u, 900uL) + assertEquals(SparkDepositClaim.Adding, sut.depositClaims.value["txid"]) + } + + @Test + fun `instant shows the new price when the claim comes back repriced`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + ClaimDepositOutcome.Deferred( + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ) + ) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + val claim = assertIs(sut.depositClaims.value["txid"]) + assertEquals(450uL, claim.offer.earlyFeeSats) + } + + @Test + fun `instant is unavailable when Spark offers only the standard claim`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = null)) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + assertEquals(SparkDepositClaim.Unavailable, sut.depositClaims.value["txid"]) + verify(sparkService, never()).claimDeposit(any(), any(), any()) + } + + @Test + fun `instant is unavailable when the provider declines the early claim`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + ClaimDepositOutcome.Deferred(ClaimDeferredReason.ProviderDeclined("no")) + ) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + assertEquals(SparkDepositClaim.Unavailable, sut.depositClaims.value["txid"]) + } + + @Test + fun `later leaves the deposit to the claim at maturity`() = test { + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Later, ceilingSats = 500uL) + advanceUntilIdle() + + assertEquals(SparkDepositClaim.Later, sut.depositClaims.value["txid"]) + verify(sparkService, never()).listUnclaimedDeposits() + verify(sparkService, never()).claimDeposit(any(), any(), any()) + } + + @Test + fun `instant says Spark has not seen the deposit when it is never listed`() = test { + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + assertEquals(SparkDepositClaim.NotSeen, sut.depositClaims.value["txid"]) + } + + @Test + fun `claim step follows the offer and the ceiling`() { + val choice = SparkClaimOffer.Choice("txid", 0u, earlyFeeSats = 300uL, 0u, 198uL, 3u) + + assertEquals(SparkClaimStep.KeepLooking, SparkClaimStep.of(null, 500uL)) + assertEquals(SparkClaimStep.ClaimEarly(choice), SparkClaimStep.of(choice, 300uL)) + assertEquals(SparkClaimStep.Ask(choice), SparkClaimStep.of(choice, 299uL)) + assertEquals( + SparkClaimStep.Unavailable, + SparkClaimStep.of(SparkClaimOffer.Standard("txid", 0u, 198uL, 3u), 500uL) + ) + assertEquals(SparkClaimStep.Adding, SparkClaimStep.of(SparkClaimOffer.Automatic("txid", 0u, 250uL, 0u), 500uL)) + } + + @Test + fun `a receive recorded without its event gets its paykit contact`() = test { + whenever { contactResolver.contactPublicKeyForPrivateInvoicePaymentHash("hash") }.thenReturn("pubky-contact") + whenever { sparkService.listPayments() }.thenReturn(listOf(receivedPayment())) + whenever(sparkService.isConnected).thenReturn(true) + + createSut().start(0).getOrThrow() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubky-contact", (activity.firstValue as Activity.Lightning).v1.contact) + } + + @Test + fun `a receive whose contact the user detached stays without one`() = test { + cacheData.value = AppCacheData(detachedActivityContacts = setOf(scopedActivityId(WalletScope.default, "hash"))) + whenever { contactResolver.contactPublicKeyForPrivateInvoicePaymentHash("hash") }.thenReturn("pubky-contact") + whenever { sparkService.listPayments() }.thenReturn(listOf(receivedPayment())) + whenever(sparkService.isConnected).thenReturn(true) + + createSut().start(0).getOrThrow() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertNull((activity.firstValue as Activity.Lightning).v1.contact) + verify(contactResolver, never()).contactPublicKeyForPrivateInvoicePaymentHash(any()) + } + + @Test + fun `lightning send lookup reads spark's payments and waits until spark has synced them`() = test { + val sut = createSut() + assertEquals(SparkLightningSend.Unavailable, sut.lightningSend("hash")) + + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED) + sut.start(0).getOrThrow() + whenever { sparkService.listPayments() }.thenReturn(listOf(failed, sentPayment(fees = 1))) + // A restored wallet lists its payments only after its first sync. + assertEquals(SparkLightningSend.Unavailable, sut.lightningSend("hash")) + + sparkEvents.emit(SdkEvent.Synced) + assertEquals(SparkLightningSend.Found(PaymentStatus.COMPLETED, "preimage"), sut.lightningSend("HASH")) + assertEquals(SparkLightningSend.NotFound, sut.lightningSend("other")) + + whenever { sparkService.listPayments() }.thenAnswer { throw SdkException.Generic("offline") } + assertEquals(SparkLightningSend.Unavailable, sut.lightningSend("hash")) + } + + @Test + fun `a send spark refuses before it leaves is a typed refusal`() = test { + val sut = createSut() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + whenever(sparkService.isConnected).thenReturn(true) + val noRoute = SdkException.Generic("no route") + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { throw noRoute } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any()) + } + + @Test + fun `a spark send over the fee limit is refused before it leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 2uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sut = createSut() + + assertIs(sut.payInvoice("lnbc1", 100uL, maxTotalFeeMsat = 1_999uL).exceptionOrNull()) + verify(sparkService, never()).send(any()) + + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 2)) + assertEquals("hash", sut.payInvoice("lnbc1", 100uL, maxTotalFeeMsat = 2_000uL).getOrThrow()) + } + + @Test + fun `a spark withdrawal pays the quote its fee estimate priced while it holds`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val held = withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(held) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut() + + assertEquals(500uL, sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow()) + sut.withdrawAll(ADDRESS).getOrThrow() + + verify(sparkService, times(1)).prepareSend(any(), anyOrNull(), anyOrNull()) + verify(sparkService).send(held) + } + + @Test + fun `a spark withdrawal asks again once its quote expired or the address changed`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val expiring = withdrawal(expiresAt = now.epochSeconds.toULong() + 10uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(expiring) + val sut = createSut() + + sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow() + sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow() + verify(sparkService, times(2)).prepareSend(any(), anyOrNull(), anyOrNull()) + + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow() + sut.estimateWithdrawAllFeeSats("bcrt1qother").getOrThrow() + verify(sparkService, times(4)).prepareSend(any(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a spark send past its deadline never leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sut = createSut() + + val result = sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = now - 1.minutes) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `a failure inside the spark send stays uncertain`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + + val error = createSut().payInvoice("lnbc1", 100uL).exceptionOrNull() + + assertIs(error) + } + + @Test + fun `can send leaves room for spark's service fee`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(GetInfoResponse("pubkey", 100_000uL, emptyMap(), 0uL)) + val sut = createSut() + sut.start(0).getOrThrow() + + assertEquals(99_750uL, sut.state.value.sendableSats) + assertTrue(sut.canSend(99_750uL)) + assertFalse(sut.canSend(100_000uL)) + } + + @Test + fun `sendable amount fits the fee beside it`() { + for (balance in listOf(0uL, 1uL, 400uL, 401uL, 9_572uL, 100_000uL, 21_000_000uL)) { + val sendable = SparkFees.sendableSats(balance) + assertTrue(sendable + SparkFees.serviceFeeSats(sendable) <= balance, "$balance") + assertTrue(sendable + 1uL + SparkFees.serviceFeeSats(sendable + 1uL) > balance, "$balance leaves room") + } + } + + private fun prepared(feeSats: ULong): PrepareSendPaymentResponse { + val details = mock { on { paymentHash } doReturn "hash" } + return PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, feeSats), + amount = BigInteger.valueOf(100), + tokenIdentifier = null, + conversionEstimate = null, + feePolicy = FeePolicy.FEES_EXCLUDED, + ) + } + + private fun withdrawal(expiresAt: ULong): PrepareSendPaymentResponse { + val speed = SendOnchainSpeedFeeQuote(userFeeSat = 300uL, l1BroadcastFeeSat = 200uL) + val quote = SendOnchainFeeQuote("quote", expiresAt, speed, speed, speed, isEstimate = false) + return PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.BitcoinAddress(mock(), quote), + amount = BigInteger.valueOf(100), + tokenIdentifier = null, + conversionEstimate = null, + feePolicy = FeePolicy.FEES_INCLUDED, + ) + } + + private fun receivedPayment() = sentPayment(fees = 0).copy(id = "receive", paymentType = PaymentType.RECEIVE) + + private fun listDeposit() { + whenever { sparkService.listUnclaimedDeposits() }.thenReturn( + listOf(DepositInfo("txid", 0u, 50_000uL, false, null, null, null, null, null, null)) + ) + } + + private fun quote(earlyFee: ULong?) = FetchClaimDepositQuoteResponse( + amountSats = 50_000uL, + confirmations = 0u, + instant = earlyFee?.let { ClaimDepositQuote(0u, 50_000uL - it, it, 200uL, false) }, + mature = ClaimDepositQuote(3u, 49_802uL, 198uL, null, true), + ) + + private fun depositPayment() = sentPayment(fees = 300).copy( + id = "deposit", + paymentType = PaymentType.RECEIVE, + method = PaymentMethod.DEPOSIT, + details = PaymentDetails.Deposit(txId = "txid", vout = 0u), + ) + + private fun sentPayment(fees: Int) = Payment( + id = "send", + paymentType = PaymentType.SEND, + status = PaymentStatus.COMPLETED, + amount = BigInteger.valueOf(128), + fees = BigInteger.valueOf(fees.toLong()), + timestamp = 1uL, + method = PaymentMethod.LIGHTNING, + details = PaymentDetails.Lightning( + description = null, + invoice = "lnbc1280n1send", + destinationPubkey = "pubkey", + htlcDetails = SparkHtlcDetails("hash", "preimage", 1uL, SparkHtlcStatus.PREIMAGE_SHARED), + lnurlPayInfo = null, + lnurlWithdrawInfo = null, + lnurlReceiveMetadata = null, + conversionInfo = null, + ), + conversionDetails = null, + ) +} diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index c57889118f..68c7bed28c 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -57,6 +57,7 @@ import to.bitkit.services.CoreService import to.bitkit.services.OnchainService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.test.idleSparkRepo import to.bitkit.ui.screens.wallets.receive.ReceiveTab import to.bitkit.ui.screens.wallets.receive.getInvoiceForTab import to.bitkit.usecases.DeriveBalanceStateUseCase @@ -77,6 +78,7 @@ class WalletRepoTest : BaseUnitTest() { private lateinit var sut: WalletRepo private val keychain = mock() + private val sparkRepo = idleSparkRepo() private val coreService = mock() private val settingsStore = mock() private val lightningRepo = mock() @@ -188,6 +190,7 @@ class WalletRepoTest : BaseUnitTest() { activityRepo = activityRepo, hwWalletRepo = hwWalletRepo, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) private fun lightningInvoice(bolt11: String, isExpired: Boolean = false) = LightningInvoice( diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt new file mode 100644 index 0000000000..cb005cedc8 --- /dev/null +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -0,0 +1,73 @@ +package to.bitkit.services + +import breez_sdk_spark.Config +import breez_sdk_spark.LeafOptimizationConfig +import breez_sdk_spark.Network +import breez_sdk_spark.SendPaymentOptions +import breez_sdk_spark.TokenOptimizationConfig +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull + +class SparkServiceTest { + @Test + fun `lightning sends return before completion so callers see the completion event`() { + val options = assertIs(SparkService.bolt11SendOptions(prefersSpark = true)) + + assertNull(options.completionTimeoutSecs) + assertEquals(true, options.preferSpark) + } + + @Test + fun `claim fee estimate covers the claims seen on mainnet`() { + // Mainnet claims so far took 198 and 297 sats; the cap at 1 sat/vB stays above both. + assertEquals(302uL, SparkService.maxDepositClaimFeeSats(fastestFeeRate = 1uL, amountSats = 2_500uL)) + assertEquals(327uL, SparkService.maxDepositClaimFeeSats(fastestFeeRate = 1uL, amountSats = 15_000uL)) + } + + @Test + fun `later claim fee prices the mature claim at the half-hour rate`() { + // Run 2 quoted the mature claim at 198 sats at 2 sat/vB. + assertEquals(198uL, SparkService.matureDepositClaimFeeSats(halfHourFeeRate = 2uL)) + } + + /** A config as `defaultConfig` returns it, with Breez's data sync and Lightning address servers set. */ + private fun defaults(network: Network) = Config( + apiKey = null, + network = network, + syncIntervalSecs = 60u, + maxDepositClaimFee = null, + lnurlDomain = "breez.tips", + preferSparkOverLightning = false, + exitChainAutoFetchEnabled = true, + watchtowerFeeLadderEnabled = null, + externalInputParsers = null, + useDefaultExternalInputParsers = true, + realTimeSyncServerUrl = "https://datasync.breez.technology", + privateEnabledDefault = true, + leafOptimizationConfig = LeafOptimizationConfig(autoEnabled = true, multiplicity = 1u), + tokenOptimizationConfig = TokenOptimizationConfig( + autoEnabled = true, + targetOutputCount = 1u, + minOutputsThreshold = 1u, + ), + stableBalanceConfig = null, + maxConcurrentClaims = 4u, + sparkConfig = null, + backgroundTasksEnabled = true, + proxy = null, + crossChainConfig = null, + ) + + @Test + fun `config turns off breez data sync and the lightning address server on every network`() { + Network.entries.forEach { network -> + val config = SparkService.configure(defaults(network), apiKey = "key") + + assertNull(config.realTimeSyncServerUrl, "$network") + assertNull(config.lnurlDomain, "$network") + assertEquals("key", config.apiKey) + } + } +} diff --git a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt new file mode 100644 index 0000000000..e77e84ceb7 --- /dev/null +++ b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt @@ -0,0 +1,14 @@ +package to.bitkit.test + +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState + +/** A Spark wallet that is not connected, so every flow takes its Blocktank and channel path. */ +fun idleSparkRepo(): SparkRepo = mock { + on { state } doReturn MutableStateFlow(SparkState()) + on { nodeEvents } doReturn MutableSharedFlow() +} diff --git a/app/src/test/java/to/bitkit/ui/ContentViewTest.kt b/app/src/test/java/to/bitkit/ui/ContentViewTest.kt index abab203eb9..5adcaec1dd 100644 --- a/app/src/test/java/to/bitkit/ui/ContentViewTest.kt +++ b/app/src/test/java/to/bitkit/ui/ContentViewTest.kt @@ -270,6 +270,33 @@ class ContentViewTest { assertTrue(navController.currentDestination?.hasRoute() == true) } + @Test + fun `spending start route uses intro until seen`() { + assertEquals(Routes.SpendingIntro, transferSpendingStartRoute(hasSeenSpendingIntro = false)) + assertEquals(Routes.SparkFundingNav, transferSpendingStartRoute(hasSeenSpendingIntro = true)) + } + + @Test + fun `hardware spending start route keeps the wallet id after intro`() { + val walletId = "trezor-1" + + assertEquals(Routes.SpendingIntroHw(walletId), transferSpendingStartRoute(false, walletId)) + assertEquals(Routes.SpendingAmountHw(walletId), transferSpendingStartRoute(true, walletId)) + } + + @Test + fun `setting up removes spending confirmation from the back stack`() { + val navController = transferNavController() + navController.navigateTo(Routes.SparkFundingNav) + navController.navigateTo(Routes.SpendingConfirm) + + navController.navigateToSettingUp() + assertTrue(navController.currentDestination?.hasRoute() == true) + + navController.popBackStack() + assertTrue(navController.currentDestination?.hasRoute() == true) + } + private fun transferNavController(): NavHostController = NavHostController(ApplicationProvider.getApplicationContext()).apply { navigatorProvider.addNavigator(ComposeNavigator()) @@ -282,6 +309,11 @@ class ContentViewTest { composable {} composable {} } + navigation(startDestination = Routes.SpendingAmount) { + composable {} + composable {} + composable {} + } } } } diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index f3b3a7403d..158bb3669c 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -57,6 +57,7 @@ import to.bitkit.services.MigrationService import to.bitkit.services.PendingChannelMigration import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.test.idleSparkRepo import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.viewmodels.RestoreState @@ -86,6 +87,7 @@ class WalletViewModelTest : BaseUnitTest() { private val migrationService = mock() private val connectivityRepo = mock() private val boltzService = mock() + private val sparkRepo = idleSparkRepo() private val lightningState = MutableStateFlow(LightningState()) private val walletState = MutableStateFlow(WalletState()) @@ -126,6 +128,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) } @@ -1176,6 +1179,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) assertEquals(RestoreState.Initial, testSut.restoreState.value) @@ -1243,6 +1247,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) testSut.start() @@ -1299,6 +1304,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) // Trigger restore to put state in non-idle @@ -1339,6 +1345,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) testSut.restoreWallet("mnemonic", null) @@ -1430,6 +1437,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + sparkRepo = sparkRepo, ) advanceUntilIdle() 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 new file mode 100644 index 0000000000..bf92b5c5d0 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt @@ -0,0 +1,240 @@ +package to.bitkit.ui.screens.transfer + +import android.content.Context +import com.synonym.bitkitcore.FeeRates +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import org.junit.Before +import org.junit.Test +import org.lightningdevkit.ldknode.BalanceDetails +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.R +import to.bitkit.models.BalanceState +import to.bitkit.models.Toast +import to.bitkit.models.TransactionSpeed +import to.bitkit.repositories.CurrencyRepo +import to.bitkit.repositories.CurrencyState +import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.LightningState +import to.bitkit.repositories.OnchainSendOutcome +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.repositories.SparkDepositClaim +import to.bitkit.repositories.SparkRepo +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 kotlin.test.assertEquals +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class SparkFundingViewModelTest : BaseUnitTest() { + private val context = mock() + private val walletRepo = mock() + private val lightningRepo = mock() + private val sparkRepo = mock() + private val currencyRepo = mock() + private val hwWalletRepo = mock() + private val feeRates = FeeRates(fast = 5u, mid = 3u, slow = 1u) + + private fun createSut() = + SparkFundingViewModel(context, walletRepo, lightningRepo, sparkRepo, currencyRepo, hwWalletRepo) + + @Before + fun setUp() { + whenever(context.getString(any())).thenReturn("text {amount}") + whenever(context.getString(R.string.lightning__spending_amount__error_min__title)).thenReturn("Too small") + whenever(context.getString(R.string.lightning__spending_confirm__fees_changed_title)).thenReturn("Changed") + whenever(context.getString(R.string.lightning__spending_amount__error_balance__title)).thenReturn("Short") + whenever(walletRepo.balanceState).thenReturn(MutableStateFlow(BalanceState(maxSendOnchainSats = 100_000u))) + whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) + whenever(currencyRepo.currencyState).thenReturn(MutableStateFlow(CurrencyState())) + whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(emptyMap())) + whenever { sparkRepo.depositAddress() }.thenReturn(Result.success("bcrt1qspark")) + whenever { sparkRepo.estimateDepositClaimFeeSats(any()) }.thenReturn(Result.success(1_350uL)) + whenever { sparkRepo.estimateMatureClaimFeeSats() }.thenReturn(Result.success(198uL)) + whenever { lightningRepo.getFeeRates() }.thenReturn(Result.success(feeRates)) + whenever { lightningRepo.getBalancesAsync() }.thenReturn(Result.success(balances(100_000uL))) + whenever { lightningRepo.estimateSendAllFee(any(), any(), any()) }.thenReturn(Result.success(500uL)) + whenever { lightningRepo.calculateTotalFee(any(), any(), any(), anyOrNull(), any()) } + .thenReturn(Result.success(500uL)) + } + + @Test + fun `max is the savings balance less the network fee and 25 percent is a quarter of it`() = test { + val sut = createSut() + advanceUntilIdle() + + assertEquals(99_500L, sut.uiState.value.maxSats) + assertEquals(24_875L, sut.quarterSats()) + } + + @Test + fun `max is zero without savings`() = test { + whenever { lightningRepo.getBalancesAsync() }.thenReturn(Result.success(balances(0uL))) + val sut = createSut() + advanceUntilIdle() + + assertEquals(0L, sut.uiState.value.maxSats) + } + + @Test + fun `continue refuses an amount that does not cover the instant fee`() = test { + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(1_000) + + val toasts = collectToasts { sut.onAmountContinue() } + + assertEquals("Too small", toasts.single().title) + assertEquals(null, sut.uiState.value.quote) + } + + @Test + fun `continue prices the transfer and opens confirm`() = test { + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + val effects = mutableListOf() + val job = launch { sut.effects.collect { effects.add(it) } } + + sut.onAmountContinue() + advanceUntilIdle() + job.cancel() + + assertEquals(listOf(SideEffect.AmountReady), effects) + val quote = requireNotNull(sut.uiState.value.quote) + assertEquals(50_500L, quote.totalSats) + assertEquals(48_650L, quote.toSpendingSats(SparkClaimSpeed.Instant)) + assertEquals(49_802L, quote.toSpendingSats(SparkClaimSpeed.Later)) + } + + @Test + fun `swipe asks again when the network fee rose since shown`() = test { + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + whenever { lightningRepo.calculateTotalFee(any(), any(), any(), anyOrNull(), any()) } + .thenReturn(Result.success(800uL)) + + val toasts = collectToasts { sut.onConfirm() } + + assertEquals("Changed", toasts.single().title) + assertEquals(50_800L, sut.uiState.value.quote?.totalSats) + assertEquals(false, sut.uiState.value.isSending) + verify(lightningRepo, never()).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + } + + @Test + fun `swipe refuses with real copy when savings no longer cover the transfer`() = test { + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + whenever { lightningRepo.getBalancesAsync() }.thenReturn(Result.success(balances(40_000uL))) + + val toasts = collectToasts { sut.onConfirm() } + + assertEquals("Short", toasts.single().title) + assertEquals(false, sut.uiState.value.isSending) + } + + @Test + fun `swipe sends at the quoted fee rates and follows the claim at the chosen speed`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Accepted("txid", 50_000uL))) + whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(mapOf("txid" to SparkDepositClaim.Later))) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + sut.onSpeedChange(SparkClaimSpeed.Later) + advanceUntilIdle() + + sut.onConfirm() + advanceUntilIdle() + + verify(lightningRepo).sendOnChain( + eq("bcrt1qspark"), eq(50_000uL), eq(TransactionSpeed.Fast), anyOrNull(), eq(feeRates), eq(true), + anyOrNull(), eq(false), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + verify(sparkRepo).onDepositBroadcast("txid", 50_000uL) + verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Later, 1_350uL) + assertEquals("txid", sut.uiState.value.txid) + assertTrue(sut.uiState.value.claim == SparkDepositClaim.Later) + } + + @Test + fun `hardware transfer prices from the device and hands signing a transfer request`() = test { + whenever { hwWalletRepo.maxSpendableFunding("trezor", "bcrt1qspark", 5uL) }.thenReturn(Result.success(80_000uL)) + whenever { hwWalletRepo.estimateFundingMiningFee("trezor", "bcrt1qspark", 50_000uL, 5uL) } + .thenReturn(Result.success(700uL)) + val sut = createSut() + sut.useHardwareWallet("trezor") + advanceUntilIdle() + assertEquals(80_000L, sut.uiState.value.maxSats) + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + val effects = mutableListOf() + val job = launch { sut.effects.collect { effects.add(it) } } + + sut.onConfirm() + advanceUntilIdle() + job.cancel() + + val request = (effects.single() as SideEffect.SignHw).request + assertEquals("trezor", request.walletId) + assertEquals("bcrt1qspark", request.address) + assertEquals(50_000uL, request.amountSats) + assertEquals(5uL, request.satsPerVByte) + assertTrue(request.isTransfer) + assertEquals(700L, sut.uiState.value.quote?.networkFeeSats) + } + + private suspend fun TestScope.collectToasts(action: () -> Unit): List { + val toasts = mutableListOf() + val job = launch { ToastEventBus.events.collect { toasts.add(it) } } + advanceUntilIdle() + action() + advanceUntilIdle() + job.cancel() + return toasts + } + + private fun balances(spendable: ULong) = BalanceDetails( + totalOnchainBalanceSats = spendable, + spendableOnchainBalanceSats = spendable, + totalAnchorChannelsReserveSats = 0u, + totalLightningBalanceSats = 0u, + lightningBalances = emptyList(), + pendingBalancesFromChannelClosures = emptyList(), + ) +} diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt index 0fc77baca2..b6a92f02b0 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/EditInvoiceVMTest.kt @@ -43,6 +43,25 @@ class EditInvoiceVMTest : BaseUnitTest() { verify(walletRepo, times(1)).inboundLiquiditySats() } + @Test + fun `onClickContinue should emit none for spending above inbound when Spark can receive`() = test { + whenever(walletRepo.canReceiveWithSpark()).thenReturn(true) + + sut.editInvoiceEffect.test { + sut.onClickContinue( + source = ReceiveLiquiditySource.SPENDING, + amountSats = 10_000u, + ) + + assertEquals( + EditInvoiceScreenEffects.ApplyReceiveLiquidityAction(ReceiveAdditionalLiquidityAction.None), + awaitItem(), + ) + cancelAndIgnoreRemainingEvents() + } + verify(walletRepo, times(0)).inboundLiquiditySats() + } + @Test fun `onClickContinue should emit transfer unavailable for spending above inbound`() = test { sut.editInvoiceEffect.test { 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 c354e5cf0a..d5e0e15fd1 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 @@ -19,6 +19,8 @@ import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.LogsRepo +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -32,6 +34,7 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { private val blocktankRepo = mock() private val logsRepo = mock() private val activityRepo = mock() + private val sparkRepo = mock() private val lightningState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)) private val lastKnownChannels = MutableStateFlow( @@ -44,6 +47,7 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { whenever(lightningRepo.lightningState).thenReturn(lightningState) whenever(lightningRepo.lastKnownChannels).thenReturn(lastKnownChannels) whenever(lightningRepo.nodeEvents).thenReturn(emptyFlow()) + whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) whenever { activityRepo.getClosedChannels(SortDirection.DESC) }.thenReturn(Result.success(emptyList())) @@ -74,5 +78,6 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { blocktankRepo = blocktankRepo, logsRepo = logsRepo, activityRepo = activityRepo, + sparkRepo = sparkRepo, ) } diff --git a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt index 342da8dd1d..800be7030a 100644 --- a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt @@ -23,8 +23,11 @@ import to.bitkit.models.TransferType import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState import to.bitkit.repositories.TransferRepo import to.bitkit.test.BaseUnitTest +import to.bitkit.test.idleSparkRepo import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -34,6 +37,7 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { private val transferRepo: TransferRepo = mock() private val settingsStore: SettingsStore = mock() private val hwWalletRepo: HwWalletRepo = mock() + private val sparkRepo: SparkRepo = idleSparkRepo() private lateinit var sut: DeriveBalanceStateUseCase @@ -60,9 +64,26 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { transferRepo = transferRepo, settingsStore = settingsStore, hwWalletRepo = hwWalletRepo, + sparkRepo = sparkRepo, ) } + @Test + fun `should add Spark balance to spending and pending deposits to transfer`() = test { + newBalanceDetails() + whenever(lightningRepo.getChannels()).thenReturn(emptyList()) + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isReady = true, balanceSats = 30_000uL, pendingDepositSats = 20_000uL)), + ) + + val balanceState = sut().getOrThrow() + + assertEquals(80_000uL, balanceState.totalLightningSats) + // Spark keeps 0.25% of a send as its fee, so the most it can send leaves room for it. + assertEquals(29_925uL, balanceState.maxSendLightningSats) + assertEquals(20_000uL, balanceState.balanceInTransferToSpending) + } + @Test fun `should subtract estimated fee from channelFundableBalance`() = test { val fundableBalance = 75_000uL diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 89de855cf8..ac1d2b580f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -325,6 +325,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ContactPaymentSettingsRepo(settingsStore, publicPaykitRepo, privatePaykitRepo, pubkyRepo, testDispatcher) } private val isRecoveryMode = MutableStateFlow(false) + private val isSparkReady = MutableStateFlow(false) private val isPaykitEnabled = MutableStateFlow(false) private val walletState = MutableStateFlow(WalletState()) private val nodeEventUpdates = MutableSharedFlow() @@ -709,6 +710,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(healthRepo.healthState).thenReturn(MutableStateFlow(mock())) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(lightningRepo.isRecoveryMode).thenReturn(isRecoveryMode) + whenever(lightningRepo.isSparkReady).thenReturn(isSparkReady) whenever(lightningRepo.nodeEventUpdates).thenReturn(nodeEventUpdates) whenever(lightningRepo.nodeEvents).thenReturn(nodeEventUpdates.map { it.event }) whenever(hwWalletRepo.receivedTxs).thenReturn(hwReceivedTxs) @@ -2627,6 +2629,36 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals("The payment request is no longer available.", terminalToast.description) } + @Test + fun `manual request whose resolution fails stops loading at once`() = test { + sut.setIsAuthenticated(true) + val request = paymentRequest() + whenever(context.getString(R.string.wallet__payment_request)).thenReturn("Payment Request") + whenever(context.getString(R.string.slashtags__error_pay_waiting_msg)).thenReturn("Try again") + whenever(privatePaykitRepo.beginPaymentRequest(request)).thenReturn( + Result.failure(AppError("Pubky shared state remains locked; retry later")) + ) + pendingPaykitPaymentRequests.value = listOf(request) + enablePaykitUi() + pubkyPublicKey.value = testPublicKey + runCurrent() + clearInvocations(toastManager) + + sut.showPaymentRequests() + sut.openIncomingPaymentRequest(request.id) + advanceTimeBy(TRANSITION_SCREEN_MS) + runCurrent() + advanceTimeBy(30.seconds.inWholeMilliseconds) + runCurrent() + + assertEquals(Sheet.PaymentRequests, sut.currentSheet.value) + verify(privatePaykitRepo, times(1)).beginPaymentRequest(request) + assertNull(sut.requestedPaymentRequestId.value) + val toast = argumentCaptor() + verify(toastManager).enqueue(toast.capture()) + assertEquals("Try again", toast.firstValue.description) + } + @Test fun `opened request with an invalid target returns to the request sheet`() = test { sut.setIsAuthenticated(true) @@ -3239,7 +3271,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `failed request opened from the full screen does not replace it with the request sheet`() = test { + fun `failed request opened from the full screen stops loading in place`() = test { sut.setIsAuthenticated(true) val request = paymentRequest() whenever(context.getString(R.string.wallet__payment_request)).thenReturn("Payment Request") @@ -3262,16 +3294,14 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.currentSheet.value) verify(paykitPaymentRequestRepo).markPresented(request) - verify(privatePaykitRepo, times(15)).beginPaymentRequest(request) - verify(paykitPaymentRequestDiagnostics, times(15)).logPresentationRejection( + verify(privatePaykitRepo, times(1)).beginPaymentRequest(request) + verify(paykitPaymentRequestDiagnostics).logPresentationRejection( request.counterparty, IncomingPaykitPaymentRequestFailureReason.NoSupportedEndpoint, ) val toastCaptor = argumentCaptor() - verify(toastManager, times(2)).enqueue(toastCaptor.capture()) - val (waitingToast, terminalToast) = toastCaptor.allValues - assertNull(waitingToast.testTag) - assertEquals("PaymentRequestUnavailableToast", terminalToast.testTag) + verify(toastManager).enqueue(toastCaptor.capture()) + assertEquals("PaymentRequestWaitingForDetailsToast", toastCaptor.firstValue.testTag) } @Test @@ -14949,6 +14979,36 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo).consumePrivatePaymentList(contactKey, privateContext) } + @Test + fun `spark send that settled before the watch started completes without pending`() = test { + val bolt11 = "lnbcrt1sparktospark" + val paymentHash = "spark_hash" + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) + whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + Event.PaymentSuccessful( + paymentId = paymentHash, + paymentHash = paymentHash, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + setSendState( + SendUiState( + address = bolt11, + amount = 1000u, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, amountSats = 1000u), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceTimeBy(LightningRepo.SEND_LN_TIMEOUT.inWholeMilliseconds + 1_000) + runCurrent() + + verify(pendingPaymentRepo, never()).track(paymentHash) + } + @Test fun `private lightning pending payment consumes private list`() = test { val bolt11 = "lnbcrt1pending" @@ -15215,6 +15275,24 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `spark becoming ready republishes the paykit lightning endpoints`() = test { + enablePublicPaykitSharing() + advanceUntilIdle() + clearInvocations(publicPaykitRepo, privatePaykitRepo) + + isSparkReady.value = true + advanceUntilIdle() + + verify(publicPaykitRepo).requestLightningRefresh(anyOrNull(), anyOrNull()) + verify(privatePaykitRepo).refreshKnownSavedContactEndpoints( + eq("spark ready"), + eq(true), + any(), + anyOrNull(), + ) + } + @Test fun `forced public refresh survives deferred initial restoration without another channel event`() = test { enablePublicPaykitSharing() diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 9c7e581058..d970738dfa 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -5,7 +5,9 @@ import app.cash.turbine.test import com.synonym.bitkitcore.BoltzPairInfo import com.synonym.bitkitcore.BoltzSwapEvent import com.synonym.bitkitcore.ReverseSwapResponse +import kotlinx.collections.immutable.persistentSetOf import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.advanceTimeBy @@ -18,16 +20,20 @@ import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.PaymentFailureReason import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.ext.createChannelDetails import to.bitkit.models.BalanceState import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState import to.bitkit.repositories.TransferRepo -import to.bitkit.repositories.WalletRepo import to.bitkit.services.BoltzService import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError @@ -36,6 +42,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime @@ -46,10 +53,11 @@ class TransferViewModelTest : BaseUnitTest() { private val context = mock() private val lightningRepo = mock() - private val walletRepo = mock() private val transferRepo = mock() private val clock = mock() private val boltzService = mock() + private val sparkState = MutableStateFlow(SparkState()) + private val sparkRepo = mock() private val balanceState = MutableStateFlow(BalanceState()) private val boltzEvents = MutableSharedFlow(extraBufferCapacity = 8) @@ -61,28 +69,167 @@ class TransferViewModelTest : BaseUnitTest() { val nodeStatus = mock() whenever(nodeStatus.isRunning).thenReturn(true) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState(nodeStatus = nodeStatus))) - whenever(walletRepo.balanceState).thenReturn(balanceState) whenever(boltzService.events).thenReturn(boltzEvents) whenever(lightningRepo.nodeEvents).thenReturn(nodeEvents) whenever(boltzService.isSwapSupported).thenReturn(true) whenever { boltzService.isSwapEnabled() }.thenReturn(true) + whenever(sparkRepo.state).thenReturn(sparkState) + whenever { sparkRepo.withdrawAll(any()) }.thenReturn(Result.success(Unit)) + whenever { lightningRepo.newAddress() }.thenReturn(Result.success(CLAIM_ADDRESS)) + whenever { lightningRepo.closeChannel(any(), any(), anyOrNull()) }.thenReturn(Result.success(Unit)) sut = TransferViewModel( context = context, lightningRepo = lightningRepo, - walletRepo = walletRepo, transferRepo = transferRepo, boltzService = boltzService, clock = clock, + sparkRepo = sparkRepo, ) } + @Test + fun `savings selection moves everything by default`() { + val selection = SavingsSelection() + + assertTrue(selection.isAll) + assertEquals(listOf(CHANNEL_A, CHANNEL_B), selection.channels(listOf(CHANNEL_A, CHANNEL_B))) + assertTrue(selection.withdrawsSpark(SPARK_SATS)) + assertFalse(selection.withdrawsSpark(0uL)) + } + + @Test + fun `savings selection moves only the picked channels and spark`() { + val channelsOnly = SavingsSelection(channelIds = persistentSetOf(CHANNEL_B.channelId), includesSpark = false) + val sparkOnly = SavingsSelection(channelIds = persistentSetOf(), includesSpark = true) + + assertFalse(channelsOnly.isAll) + assertEquals(listOf(CHANNEL_B), channelsOnly.channels(listOf(CHANNEL_A, CHANNEL_B))) + assertFalse(channelsOnly.withdrawsSpark(SPARK_SATS)) + assertFalse(sparkOnly.isAll) + assertTrue(sparkOnly.channels(listOf(CHANNEL_A, CHANNEL_B)).isEmpty()) + assertTrue(sparkOnly.withdrawsSpark(SPARK_SATS)) + } + + @Test + fun `transfer to savings with only spark withdraws spark and closes no channel`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + + assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) + assertFalse(sut.hasChannelsToClose()) + assertTrue(sut.closeSelectedChannels().isEmpty()) + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS) + verify(lightningRepo, never()).awaitPeerConnected(any()) + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + } + + @Test + fun `transfer to savings with only channels leaves spark untouched`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_B), withdrawSpark = false) + + assertTrue(sut.closeSelectedChannels().isEmpty()) + verify(sparkRepo, never()).withdrawAll(any()) + verify(lightningRepo).closeChannel(CHANNEL_B, false, null) + verify(lightningRepo, never()).closeChannel(CHANNEL_A, false, null) + } + + @Test + fun `a failed spark withdrawal is reported while the selected channels still close`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + whenever { sparkRepo.withdrawAll(any()) }.thenReturn(Result.failure(AppError(PAY_ERROR))) + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = true) + + assertTrue(sut.closeSelectedChannels().isEmpty()) + + assertTrue(sut.isSparkWithdrawFailed.value) + verify(lightningRepo).closeChannel(CHANNEL_A, false, null) + + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + assertFalse(sut.isSparkWithdrawFailed.value) + } + + @Test + fun `transfer to savings with channels and spark moves both`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A, CHANNEL_B), withdrawSpark = true) + + assertTrue(sut.closeSelectedChannels().isEmpty()) + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS) + verify(lightningRepo).closeChannel(CHANNEL_A, false, null) + verify(lightningRepo).closeChannel(CHANNEL_B, false, null) + } + + @Test + fun `transfer to savings with only spark ignores a quote left from a channel selection`() = test { + balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) + whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) + advanceUntilIdle() + assertNotNull(sut.savingsSwapState.value.quote) + + sut.loadSavingsSwapQuote(0uL, 0uL) + advanceUntilIdle() + assertNull(sut.savingsSwapState.value.quote) + + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) + } + + @Test + fun `swap to savings withdraws spark only when it is selected`() = test { + stubSavingsSwapHappyPath() + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) + advanceUntilIdle() + + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = false) + assertEquals(SavingsTransferMode.SWAP, sut.savingsTransferMode.value) + sut.startSavingsSwap() + advanceUntilIdle() + + verify(sparkRepo, never()).withdrawAll(any()) + verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) + } + + @Test + fun `loadSparkWithdrawFee prices spark's withdrawal once per balance`() = test { + whenever(sparkRepo.estimateWithdrawAllFeeSats(CLAIM_ADDRESS)).thenReturn(Result.success(SPARK_FEE)) + + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + + assertEquals(SPARK_FEE, sut.sparkWithdrawFeeSats.value) + verify(sparkRepo, times(1)).estimateWithdrawAllFeeSats(CLAIM_ADDRESS) + } + + @Test + fun `loadSparkWithdrawFee gives up on an estimate that never returns`() = test { + var calls = 0 + whenever(sparkRepo.estimateWithdrawAllFeeSats(CLAIM_ADDRESS)).doSuspendableAnswer { + if (calls++ == 0) awaitCancellation() + Result.success(SPARK_FEE) + } + + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceTimeBy(16.seconds) + runCurrent() + + assertNull(sut.sparkWithdrawFeeSats.value) + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + assertEquals(SPARK_FEE, sut.sparkWithdrawFeeSats.value) + } + @Test fun `loadSavingsSwapQuote defaults to max transferable within limits and spendable balance`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() val state = sut.savingsSwapState.value @@ -97,20 +244,31 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(expectedMax - expectedSwapFee - SWAP_MINER_FEE, quote.receiveSat) } + @Test + fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { + balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) + whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) + + sut.loadSavingsSwapQuote(REQUESTED_SAT, channelSendableSat = CHANNEL_SENDABLE) + advanceUntilIdle() + + assertEquals(CHANNEL_SENDABLE - CHANNEL_SENDABLE / 100uL, sut.savingsSwapState.value.maxSat) + } + @Test fun `loadSavingsSwapQuote falls back to close when below the swap minimum`() = test { whenever(context.getString(R.string.lightning__savings_confirm__amount_too_low)).thenReturn(TOO_LOW) balanceState.value = BalanceState(maxSendLightningSats = SWAP_MIN - 1uL) whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() val state = sut.savingsSwapState.value assertNull(state.quote) assertEquals(0uL, state.maxSat) - sut.onTransferToSavingsConfirm(emptyList()) + sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) sut.startSavingsSwap() @@ -124,13 +282,13 @@ class TransferViewModelTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) whenever(boltzService.reverseLimits(anyOrNull())).thenAnswer { throw AppError(BOLTZ_ERROR) } - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() assertNull(sut.savingsSwapState.value.quote) assertFalse(sut.savingsSwapState.value.isLoading) - sut.onTransferToSavingsConfirm(emptyList()) + sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) } @@ -139,13 +297,13 @@ class TransferViewModelTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) whenever(boltzService.isSwapSupported).thenReturn(false) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() assertEquals(SavingsSwapUiState(), sut.savingsSwapState.value) verify(boltzService, never()).reverseLimits(anyOrNull()) - sut.onTransferToSavingsConfirm(emptyList()) + sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) } @@ -154,13 +312,13 @@ class TransferViewModelTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) whenever(boltzService.isSwapEnabled()).thenReturn(false) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() assertEquals(SavingsSwapUiState(), sut.savingsSwapState.value) verify(boltzService, never()).reverseLimits(anyOrNull()) - sut.onTransferToSavingsConfirm(emptyList()) + sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) } @@ -168,13 +326,13 @@ class TransferViewModelTest : BaseUnitTest() { fun `onTransferToSavingsConfirm swaps when a quote is ready and closes when the user opts out`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() - sut.onTransferToSavingsConfirm(emptyList()) + sut.onTransferToSavingsConfirm(listOf(CHANNEL_A), withdrawSpark = false) assertEquals(SavingsTransferMode.SWAP, sut.savingsTransferMode.value) - sut.onTransferToSavingsConfirm(emptyList(), SavingsTransferMode.CLOSE) + sut.onTransferToSavingsConfirm(listOf(CHANNEL_A), withdrawSpark = false, SavingsTransferMode.CLOSE) assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) } @@ -182,13 +340,13 @@ class TransferViewModelTest : BaseUnitTest() { fun `onTransferToSavingsConfirm clears the outcome of an earlier swap`() = test { stubSavingsSwapHappyPath() whenever(lightningRepo.payInvoice(any(), anyOrNull())).thenReturn(Result.failure(AppError(PAY_ERROR))) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() advanceUntilIdle() assertEquals(SavingsSwapResult.Failure(PAY_ERROR), sut.savingsSwapResult.value) - sut.onTransferToSavingsConfirm(emptyList()) + sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) assertNull(sut.savingsSwapResult.value) } @@ -197,7 +355,7 @@ class TransferViewModelTest : BaseUnitTest() { fun `onSwapAmountChange clamps to the allowed range and reprices`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.onSwapAmountChange(SWAP_MIN - 10_000uL) @@ -208,7 +366,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `startSavingsSwap succeeds when the claim event arrives`() = test { stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -222,7 +380,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `startSavingsSwap fails when the swap reports an error event`() = test { stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -236,7 +394,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `startSavingsSwap returns pending when the claim does not arrive in time`() = test { stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -251,7 +409,7 @@ class TransferViewModelTest : BaseUnitTest() { fun `startSavingsSwap fails when the invoice payment fails`() = test { stubSavingsSwapHappyPath() whenever(lightningRepo.payInvoice(any(), anyOrNull())).thenReturn(Result.failure(AppError(PAY_ERROR))) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -263,7 +421,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `startSavingsSwap ignores a second start while a swap is in flight`() = test { stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -283,7 +441,7 @@ class TransferViewModelTest : BaseUnitTest() { stubSavingsSwapHappyPath() whenever(context.getString(R.string.wallet__payment_route_not_found)) .thenReturn(ROUTE_NOT_FOUND_MSG) - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -304,7 +462,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `startSavingsSwap ignores a restart once an outcome is already delivered`() = test { stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT) + sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -349,6 +507,11 @@ class TransferViewModelTest : BaseUnitTest() { ) private companion object { + val CHANNEL_A = createChannelDetails().copy(channelId = "channel_a") + val CHANNEL_B = createChannelDetails().copy(channelId = "channel_b") + const val SPARK_SATS = 40_000uL + const val SPARK_FEE = 1_470uL + const val CHANNEL_SENDABLE = 60_000uL const val TXID = "tx-abc" const val SPENDABLE_LN = 150_000uL const val REQUESTED_SAT = 200_000uL diff --git a/changelog.d/next/1697.added.md b/changelog.d/next/1697.added.md new file mode 100644 index 0000000000..e1e6a1d79d --- /dev/null +++ b/changelog.d/next/1697.added.md @@ -0,0 +1 @@ +Spending keeps Lightning without channels: transfers from Savings now fund a Spark wallet that sends and receives Lightning payments. diff --git a/docs/screens-map.md b/docs/screens-map.md index 7dfb7bf5df..b46984af02 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -135,6 +135,12 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | SavingsConfirmScreen.kt | Transfer to Savings (Channel Closure) › Transfer all funds to savings review | | SavingsIntroScreen.kt | Transfer to Savings (Channel Closure) › Transfer to savings | | SavingsProgressScreen.kt | Transfer to Savings (Channel Closure) › Transfer to savings progress 2 | +| SettingUpScreen.kt | Funds In Transfer › Transfer to Spending Progress 1 | +| SpendingAmountScreen.kt | Transfer to Spending Balance From Savings (Channel Opening) › Transfer to Spending Input | +| SpendingConfirmScreen.kt | Transfer to Spending Balance From Savings (Channel Opening) › Transfer to Spending Confirm | +| SpendingIntroScreen.kt | Transfer to Spending Balance From Savings (Channel Opening) › Transfer to Spending Intro | +| TransferIntroScreen.kt | Lightning Onboarding From Suggestion Card › Lightning onboarding Intro | +| TransferLearnMoreScreen.kt | Transfer to Spending Balance From Savings (Channel Opening) › Transfer to Spending Receiving Capacity | ## ui/screens/transfer/external @@ -150,6 +156,8 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | Android | Figma | | - | - | +| SpendingHwSignScreen.kt | Transfer to Spending Balance From HW Device › Transfer to Spending Confirm HW | +| SpendingHwSignedScreen.kt | Transfer to Spending Balance From HW Device › Transfer to Spending Confirmed HW | ## ui/screens/trezor @@ -308,6 +316,7 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | ChannelDetailScreen.kt | Settings > Advanced › Connection details | | CloseConnectionScreen.kt | Settings > Advanced › Close connection | | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | +| SparkDetailScreen.kt | `todo` | ## ui/settings/pin diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9767d1a465..a899b0db87 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,6 +22,7 @@ appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-alpha05" } bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc11" } +breez-sdk-spark = { module = "breez_sdk_spark:bindings-android", version = "0.27.2" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } diff --git a/journeys/README.md b/journeys/README.md index 5770c36ac8..93e69007f4 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -184,6 +184,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `deeplinks/screen-deeplink.xml`, `deeplinks/sheet-deeplink.xml` | not ported — iOS registers the `bitkit` scheme but has no screen or sheet router | | `backup-restore/restore-keeps-tags-and-closed-channels.xml` | not ported yet — iOS already gates uploads across the whole restore (`AppScene.restoreFromMostRecentBackup` sets `BackupService.setRestoring(true)` before the timestamp probe), but still applies the three activity slices in one block (`BackupService.performFullRestoreFromLatestBackup`), which is the half this journey pins; port it with the iOS slice fix | | `shop/gift-card-category-titles.xml` | not ported — iOS still hardcodes the category names, and its route in has no screen deeplink | +| `amount-limits/transfer-spending-preset-delete.xml` | not ported yet — the same fix shipped in synonymdev/bitkit-ios#289, so this one should port | | `app-update/critical-update-onboarding.xml` | not ported yet — iOS already blocks at the top level in `AppScene`, so the journey applies there once written | | `home/pull-to-refresh-rates.xml` | not ported — iOS does not refresh exchange rates on pull to refresh | | `home/timed-reminders-do-not-interrupt.xml` | paired draft in synonymdev/bitkit-ios#1013; the journey name and actions match, but iOS device verification is incomplete. Android resumes Home after permission prompts and background/foreground; iOS uses primary-screen lifecycle callbacks and explicit rechecks. | @@ -196,6 +197,8 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `lnurl/lnurl-pay-comment-note.xml` | not ported — bitkit-ios has not been checked for keeping the LNURL-pay comment on the activity | | `backup/confirm-mnemonic-clear-wrong-word.xml` | not ported — `BackupConfirmMnemonic.swift` clears only the last word by its chip, with no red-word tap | | `coin-selection/manual-coin-selection-load.xml` | not ported — iOS has `SendUtxoSelectionView` but no load error, retry or identifiers to assert on | +| `transfer/spending-confirm-amount-change.xml` | same file — both platforms show the same "Fees changed" info toast; closing the received sheet re-sizes iOS's Spending Confirm, so the lower amounts can show before the swipe | +| `transfer/savings-select-funds.xml` | same file and steps — iOS runs it as J8 on synonymdev/bitkit-ios#1128 | | — | `hardware-wallet/transfer-to-spending-over-max.xml` exists only on iOS | ### Running one on iOS diff --git a/journeys/amount-limits/README.md b/journeys/amount-limits/README.md index cf68388bcf..c124b846f7 100644 --- a/journeys/amount-limits/README.md +++ b/journeys/amount-limits/README.md @@ -2,7 +2,8 @@ These journeys exercise the "block numberpad input exceeding the max/available amount" behaviour added on `fix/block-input-over-max`. The same `AmountInputViewModel.setMaxAmount` + -`MaxExceeded` effect path backs both amount-entry screens (Send, External node). +`MaxExceeded` effect path backs all three amount-entry screens (Send, Transfer→Spending, +External node). ## What the feature does - Typing a digit that would push the amount **over the cap is rejected** — the display stays at @@ -19,7 +20,10 @@ behaviour added on `fix/block-input-over-max`. The same `AmountInputViewModel.se - Fund + mine via the `lsp` skill: `./lsp POST /regtest/chain/deposit '{"address":"","amountSat":100000}'` then `./lsp POST /regtest/chain/mine '{"count":3}'` and wait for the balance to sync. -2. **External-node flow needs a reachable LN peer.** The staging LSP node works as the peer: +2. **Transfer→Spending needs Spark connected** so the most Savings can send to the Spark deposit + address can be priced. The number pad is disabled until that max loads — **wait for it** before + typing. +3. **External-node flow needs a reachable LN peer.** The staging LSP node works as the peer: id `028a8910b0048630d4eb17af25668cdd7ea6f2d8ae20956e7a06e2ae46ebcb69fc`, host `34.65.86.104`, port `9400` (from `./lsp GET /info`). @@ -40,6 +44,9 @@ behaviour added on `fix/block-input-over-max`. The same `AmountInputViewModel.se - Send: screen `send_amount_screen`, field `SendNumberField`, available `available_balance`, max `SendAmountMax`, continue `ContinueAmount`; recipient `RecipientManual` / `RecipientInput` / `AddressContinue`; home Send button `Send`. +- Transfer→Spending: screen `SpendingAmount`, field `SpendingAmountNumberField`, + available `SpendingAmountAvailable`, 25% `SpendingAmountQuarter`, max `SpendingAmountMax`, + continue `SpendingAmountContinue`. - External: funding `FundManual`; connection `NodeIdInput`/`HostInput`/`PortInput`/`ExternalContinue`; amount screen `ExternalAmount`, field `ExternalAmountNumberField`, 25% `ExternalAmountQuarter`, max `ExternalAmountMax`, continue `ExternalAmountContinue`. diff --git a/journeys/amount-limits/transfer-spending-over-max.xml b/journeys/amount-limits/transfer-spending-over-max.xml new file mode 100644 index 0000000000..9e1a555c31 --- /dev/null +++ b/journeys/amount-limits/transfer-spending-over-max.xml @@ -0,0 +1,24 @@ + + + Verifies the "Transfer to Spending" amount number pad blocks input exceeding the maximum allowed + transfer amount, shows the "Spending Balance Maximum" warning toast, and still allows deleting + digits while at the cap. + + Precondition: onboarded dev wallet with a POSITIVE on-chain Savings balance and Spark connected on + its regtest, so the most Savings can send to the Spark deposit address can be priced. The pad is + disabled until that maximum loads — wait for it. The maximum is the Savings balance less the network + fee, so it is lower than the Savings balance. Start on the wallet home screen. + + + Tap the Spending balance card on the home screen + Tap "Transfer from Savings" + If a transfer intro screen appears, tap "Get Started" + Verify the spending amount screen (testTag "SpendingAmount") is visible + Wait until the available/maximum amount (testTag "SpendingAmountAvailable") finishes loading and shows a positive value + Tap the "9" key (testTag "N9") nine times to enter an amount far larger than the maximum allowed + Verify a "Spending Balance Maximum" warning toast appears + Verify the amount in the input field (testTag "SpendingAmountNumberField") does not exceed the stated maximum + Tap the delete key (testTag "NRemove") once + Verify the amount in the input field (testTag "SpendingAmountNumberField") decreased after the delete + + diff --git a/journeys/amount-limits/transfer-spending-preset-delete.xml b/journeys/amount-limits/transfer-spending-preset-delete.xml new file mode 100644 index 0000000000..03e299c823 --- /dev/null +++ b/journeys/amount-limits/transfer-spending-preset-delete.xml @@ -0,0 +1,46 @@ + + + Verifies that after the "Transfer to Spending" amount is filled by a preset (25% or MAX) or by + switching the number pad unit from fiat, every delete press removes exactly one digit and + appended digits are accepted. The displayed amount keeps its sats grouping spaces, but the + number pad input underneath does not, so no press is spent on a space (synonymdev/bitkit-android#558). + + Precondition: onboarded dev wallet with the display unit set to modern Bitcoin (sats), primary + display Bitcoin, a POSITIVE on-chain Savings balance of at least 250 000 sats, and Spark connected + on its regtest. Start on the wallet home screen. No funds move: the journey never taps Continue. + + Why 250 000: the number pad rejects any sats input above its max + (AmountInputViewModel.handleNumberPadInput, the guard comparing the new amount to maxAmount), + and that max is `maxSats` — the Savings balance less the network fee to the Spark deposit address + (SparkFundingViewModel.refreshMax, SpendingAmountScreen's `setMaxAmount`). It is the value shown + by "SpendingAmountUnit". Entering 10 fiat units and + switching back to sats gives about 10 000 sats at a BTC price near 100 000 fiat units, and the + append in the step below makes that about 100 001, so a smaller balance has the digit dropped + and the max toast shown instead, which false-fails the step. The guard in the fiat-entry step + below keeps that true if the price moves far enough for 10 fiat units to be worth more than a + tenth of the max. + + iOS counterpart: the same fix shipped in synonymdev/bitkit-ios#289, but the journey is not + ported to the iOS corpus yet. + + + Tap the Savings balance card (testTag "ActivitySavings") on the home screen + Tap "Transfer To Spending" (testTag "TransferToSpending") + If the spending intro screen appears, tap "Get Started" (testTag "SpendingIntro-button") + Verify the spending amount screen (testTag "SpendingAmount") is visible + Wait until the available amount (testTag "SpendingAmountUnit") finishes loading and shows a positive value + Tap the 25% button (testTag "SpendingAmountQuarter") + Verify the amount in the input field (testTag "SpendingAmountNumberField") shows a grouped value with a space, e.g. "78 777" + Tap the delete key (testTag "NRemove") repeatedly until the amount is 0, reading the amount after each press + Verify every delete press changed the amount, e.g. "78 777" → "7 877" → "787" → "78" → "7" → "0", with no press leaving the amount unchanged + Tap the number pad unit toggle (testTag "SpendingNumberPadUnit") so it shows the fiat currency + Tap "1" (testTag "N1") and "0" (testTag "N0") to enter 10 fiat units; if 10 fiat units are worth more than a tenth of the amount shown in "SpendingAmountUnit", tap only "1" (testTag "N1") instead, so the digit appended below still fits under that amount + Tap the number pad unit toggle (testTag "SpendingNumberPadUnit") so it shows "BITCOIN" + Verify the amount in the input field is a grouped sats value of at least 4 digits + Tap "1" (testTag "N1") + Verify the amount gained exactly one trailing digit "1", is not over the amount shown in "SpendingAmountUnit", and that no "Spending Balance Maximum" warning toast appeared + Tap the delete key (testTag "NRemove") repeatedly until the amount is 0, reading the amount after each press + Verify every delete press changed the amount + Tap the back button (testTag "NavigationBack") to leave without transferring + + diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index ae12fd1e29..67aaf59e71 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -76,11 +76,14 @@ the other three rely on, and `passphrase-settings-remove.xml` removes it again. | `connect-flow.xml` | Settings Add button → connect flow with an edited Label Funds → paired device count + name | | `settings-hardware-wallets.xml` | Payments count row, Hardware Wallets screen list, rename sheet, Add button sheet/back dismiss, per-row delete confirm + re-pair | | `detail-overview.xml` | Detail screen overview, Transfer placeholder when funded, activity, Remove confirm + forget | +| `transfer-to-spending.xml` | Happy-path transfer into Spark plus one scoped hardware Transfer activity | +| `transfer-to-spending-node-warmup.xml` | Transfer started during app/node warm-up; verifies loading recovers into the sign screen | | `send-onchain.xml` | Normal Send flow funded by Trezor: source selection, guarded preparation, device signing, broadcast, success, and activity | | `receive-onchain.xml` | Trezor Receive tab: current address and QR display plus exact on-device address verification | | `passphrase-pairing.xml` | Passphrase button on Paired → Enter Passphrase → Passphrase Funds Found; second home tile, own label, no passphrase in logs | | `passphrase-duplicate.xml` | Re-entering a watched passphrase reports "already added" and adds no tile | | `passphrase-settings-remove.xml` | Per-identity settings row, rename and delete; removing the hidden wallet keeps the device paired | +| `passphrase-transfer-to-spending.xml` | Signs with the live session, re-prompts after the session is dropped, refuses a wrong passphrase | Connect-flow testTags: `HardwareWalletSheet`, `HardwareWalletIntroScreen`, `HardwareWalletIntroCancel`, `HardwareWalletIntroContinue`, diff --git a/journeys/hardware-wallet/passphrase-transfer-to-spending.xml b/journeys/hardware-wallet/passphrase-transfer-to-spending.xml new file mode 100644 index 0000000000..091f42d0e4 --- /dev/null +++ b/journeys/hardware-wallet/passphrase-transfer-to-spending.xml @@ -0,0 +1,74 @@ + + + Drives Transfer To Spending from a passphrase (hidden) wallet. While the Trezor session that + holds the passphrase is still open the transfer signs straight away; after the session is + dropped Bitkit asks for the passphrase again, and a wrong one is refused instead of signing + from whichever wallet the device happens to have open. Requires Spark connected on its regtest, the emulator started with + passphrase protection enabled, the hidden wallet from passphrase-pairing.xml paired, and its + native-segwit account holding spendable regtest funds. + + + + Launch the Bitkit app and go to the wallet home screen + + + Tap the hidden wallet tile ("Hidden Trezor") and verify its detail screen opens (testTag "HardwareWalletScreen") + + + Tap "Transfer To Spending" (testTag "HardwareTransferToSpending"), and if the first-run intro is shown tap "Get Started" + + + Tap the "25%" quick button (testTag "HardwareTransferAmountQuarter"), then "Continue" (testTag "HardwareTransferAmountContinue") and wait for the fee estimate + + + Verify the sign screen opens (testTag "HardwareTransferSign") titled "SIGN WITH YOUR DEVICE" + + + Tap "Open Trezor Connect" (testTag "HardwareTransferOpenTrezorConnect") and verify no passphrase sheet appears, because the session opened at pairing still holds the hidden wallet + + + Approve the Recipient, Amount, Locktime, and Summary prompts on the Bridge emulator in order, and verify the transaction signed screen appears (testTag "HardwareTransferSigned") + + + Wait for the setting-up progress screen (testTag "LightningSettingUp"), tap "Continue Using Bitkit", and verify the app returns to the wallet home screen + + + adb: adb shell am force-stop to.bitkit.dev + + + adb: adb shell monkey -p to.bitkit.dev -c android.intent.category.LAUNCHER 1 + + + Once the app is back on the home screen, open the hidden wallet tile and start Transfer To Spending again, setting an amount with the "25%" quick button and continuing to the sign screen + + + Tap "Open Trezor Connect" (testTag "HardwareTransferOpenTrezorConnect") and verify the passphrase sheet opens (testTag "HwTransferPassphraseSheet"), because the session that held the passphrase is gone + + + Type a wrong passphrase "not-the-one" into the input (testTag "HwTransferPassphraseInput") and tap "Continue" (testTag "HwTransferPassphraseContinue") + + + Confirm on the emulated device for every account the passphrase session reads: the device + prompts once per address type and the call blocks until it is acknowledged. Either tap the + emulator UI or run: ../bitkit-docker/scripts/trezor-emulator send-json '{"type":"emulator-press-yes","id":1}' + + + Verify an error toast says the passphrase opens a different wallet, that no signing prompt was shown on the emulator, and that no new transfer appears in the activity list + + + Navigate to the wallet home screen and verify the hardware tile count is unchanged: the wallet the wrong passphrase opened must not be added + + + Reopen the sign screen, tap "Open Trezor Connect", type the correct passphrase "bitkit-hidden" and tap "Continue" + + + Approve the Recipient, Amount, Locktime, and Summary prompts on the Bridge emulator, and verify the transaction signed screen appears (testTag "HardwareTransferSigned") + + + adb: adb shell "run-as to.bitkit.dev sh -c 'grep -rl -e bitkit-hidden -e not-the-one files/logs/ files/datastore/ || echo NO_PASSPHRASE_LEAK'" + + + Verify the previous command printed NO_PASSPHRASE_LEAK: neither the correct nor the rejected passphrase may be written to the logs or the datastore + + + diff --git a/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml b/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml new file mode 100644 index 0000000000..db2076b6b5 --- /dev/null +++ b/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml @@ -0,0 +1,37 @@ + + + Verifies that starting a hardware-wallet transfer while the Lightning node is still + warming up does not fail or strand the CTA in loading. The flow should show the normal + loading/progress UI, continue once the node reaches the needed state, and land on the + sign screen. Requires Spark connected on its regtest and a paired and funded hardware wallet. + + + + adb: adb shell am force-stop to.bitkit.dev + + + adb: adb shell monkey -p to.bitkit.dev -c android.intent.category.LAUNCHER 1 + + + As soon as the wallet home screen is visible, tap the hardware wallet tile beneath the SAVINGS and SPENDING tiles + + + Tap the "Transfer To Spending" button (testTag "HardwareTransferToSpending") + + + Verify the transfer amount screen or loading/progress UI appears, and no reconnect, node-not-ready, or generic failure toast is shown while the node warms up + + + Tap the "25%" quick button (testTag "HardwareTransferAmountQuarter") if the amount screen is shown + + + Tap "Continue" (testTag "HardwareTransferAmountContinue") if the amount screen is shown, then wait for the fee estimate and node warm-up to finish + + + Verify the sign screen opens (testTag "HardwareTransferSign"), titled "SIGN WITH YOUR DEVICE", and the Continue/Open Trezor Connect CTA is no longer loading + + + Navigate back without signing so this journey only covers node warm-up behavior + + + diff --git a/journeys/hardware-wallet/transfer-to-spending.xml b/journeys/hardware-wallet/transfer-to-spending.xml new file mode 100644 index 0000000000..c24949172e --- /dev/null +++ b/journeys/hardware-wallet/transfer-to-spending.xml @@ -0,0 +1,59 @@ + + + Drives the watch-only Transfer To Spending flow for a paired Trezor into Spark: Amount -> Sign With + Your Device -> Transaction Signed -> setting-up progress, then verifies the new transfer is + represented once in the hardware wallet's Core activity scope. Requires Spark connected on its + regtest and a paired Bridge emulator whose native-segwit account holds spendable regtest funds and + at least one older hardware receive row with a distinct amount. + + + + Launch the Bitkit app and go to the wallet home screen + + + Verify the recent activity list contains an older blue hardware received row with a distinct amount + + + Tap the hardware wallet tile beneath the SAVINGS and SPENDING tiles, and verify the hardware wallet detail screen opens (testTag "HardwareWalletScreen") + + + Tap the "Transfer To Spending" button (testTag "HardwareTransferToSpending") + + + If the first-run Transfer To Spending intro is shown, tap "Get Started" + + + Verify the transfer amount screen opens (testTag "HardwareTransferAmount"), titled "TRANSFER TO SPENDING", showing an AVAILABLE row, the 25% and MAX quick buttons, and a number pad + + + Tap the "25%" quick button (testTag "HardwareTransferAmountQuarter") to set a valid amount below the available limit + + + Tap "Continue" (testTag "HardwareTransferAmountContinue") and wait for the fee estimate + + + Verify the sign screen opens (testTag "HardwareTransferSign"), titled "SIGN WITH YOUR DEVICE", showing the NETWORK FEES, SPENDING FEE, TO SPENDING and TOTAL cells, the Instant and Later rows, the Learn More button, and the Trezor illustration + + + Tap "Open Trezor Connect" (testTag "HardwareTransferOpenTrezorConnect"). If the fees rose since they were shown, verify a "Fees changed" toast, the fee cells refresh, and tap "Open Trezor Connect" again; otherwise signing starts immediately + + + Approve the Recipient, Amount, Locktime, and Summary prompts on the Bridge emulator in order + + + Verify the transaction signed screen appears (testTag "HardwareTransferSigned"), titled "TRANSACTION SIGNED", showing the same fee cells and the checkmark illustration + + + Wait for the screen to auto-forward and verify the setting-up progress screen appears (testTag "LightningSettingUp") + + + Tap "Continue Using Bitkit" and verify the app returns to the wallet home screen + + + Verify the recent activity list contains exactly one new blue hardware Transfer row, above the older blue received row + + + Tap the new blue Transfer row and verify its detail screen shows "TO SPENDING" + + + diff --git a/journeys/transfer/savings-select-funds.xml b/journeys/transfer/savings-select-funds.xml new file mode 100644 index 0000000000..3663026dca --- /dev/null +++ b/journeys/transfer/savings-select-funds.xml @@ -0,0 +1,30 @@ + + + Verifies that Transfer to Savings lets the user pick what moves: each open channel and Spark are + rows on the Select funds list, all selected by default, and the confirm screen shows only what is + selected, with Spark's withdrawal fee only while Spark is selected. With a single item (Spark + alone, or one channel without a Spark balance) the confirm screen shows no Advanced button and + moves everything, as before Spark. + + Precondition: onboarded dev wallet on Spark's regtest chain (see the PR's Setup) with a Spark + balance and at least one open channel. Spark's regtest has no Lightning peers, so a channel there + needs a staged channel; on Blocktank's regtest the Spark balance cannot be funded. Start on the + wallet home screen. The journey stops before the swipe. + + + Tap the Spending balance card (testTag "ActivitySpending") + Tap "Transfer To Savings" (testTag "TransferToSavings") + If the transfer to savings intro appears, tap "Get Started" (testTag "SavingsIntro-button") + Tap "Continue" (testTag "AvailabilityContinue") on the funds availability screen + On the confirm screen, verify the amount is the channels' balance plus the Spark balance, a "Spark fee" amount shows, and an "Advanced" button shows + Tap "Advanced" + Verify the "Select funds to transfer" screen lists a "Spark" row with the Spark balance and one "Connection N" row per open channel, every switch on, and "Total selected" equals the confirm amount + Turn off the last "Connection N" row and verify "Total selected" drops by that row's amount + Tap "Continue" and verify the confirm amount equals the new total, "Spark fee" still shows, and the button reads "Transfer all" + Tap "Transfer all", then tap "Advanced", turn off the "Spark" row and every "Connection N" row, and verify "Continue" is disabled + Turn on the "Spark" row only and tap "Continue" + Verify the confirm amount equals the Spark balance and "Spark fee" shows + Tap "Transfer all" and verify the amount returns to the channels' balance plus the Spark balance, and the button reads "Advanced" + Tap "Advanced", turn off the "Spark" row, tap "Continue", and verify the amount equals the channels' balance with no "Spark fee" + + diff --git a/journeys/transfer/spark-transfer-to-spending.xml b/journeys/transfer/spark-transfer-to-spending.xml new file mode 100644 index 0000000000..a5c2a9f0c3 --- /dev/null +++ b/journeys/transfer/spark-transfer-to-spending.xml @@ -0,0 +1,29 @@ + + + Verifies the transfer to spending flow on Spark. With Spark ready, the Spending suggestion card opens the + "Spending Balance" intro once, then Funding, which leads with "Transfer from Savings" (testTag "FundTransfer") + and "Use Other Wallet" (testTag "FundReceive") above "Manual Setup" (testTag "FundManual"). Transfer from + Savings opens the "Transfer to spending" intro once, then the amount screen (testTag "SpendingAmount"). The + confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", and the Instant and Later rows: + Instant shows its fee as "up to", Later as "≈", and picking a row updates the Spending fee and To spending + tiles. Learn more explains Instant and Later. Whether the provider offers Instant needs a real deposit Spark + sees, so this journey stops before the swipe; the states after it are covered by SettingUpScreen previews and + SparkRepoTest. + + Precondition: dev build with Spark connected on its regtest (no key needed), a freshly onboarded wallet (so + neither intro has been seen) with a positive on-chain Savings balance and no channels, and the Spending + suggestion card on Home. Start on the wallet home screen. + + + Tap the Spending suggestion card and verify the "Spending Balance" intro opens; tap "Get Started" (testTag "TransferIntro-button") + Verify "Transfer from Savings" (testTag "FundTransfer") and "Use Other Wallet" (testTag "FundReceive") are enabled above "Manual Setup" (testTag "FundManual") + Tap "Transfer from Savings" and verify the "Transfer to spending" intro opens; tap "Get Started" (testTag "SpendingIntro-button") + Verify the amount screen (testTag "SpendingAmount") opens and wait until the available amount (testTag "SpendingAmountAvailable") shows a positive value + Tap "25%" (testTag "SpendingAmountQuarter") and verify the amount is a quarter of the available amount; tap "Max" (testTag "SpendingAmountMax") and verify it equals the available amount + Tap "Continue" (testTag "SpendingAmountContinue") and verify the confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", with "Instant" (testTag "SpendingConfirmInstant") selected and its fee shown as "up to" + Tap "Later" (testTag "SpendingConfirmLater") and verify the Spending fee shows "≈" with a lower amount and "To spending" grows by the difference + Tap "Learn More" (testTag "SpendingConfirmMore"), verify the "Transfer speed" screen with the spending balance bar, and tap "Understood" (testTag "LiquidityContinue") + Verify the confirm screen still shows Later selected; go back to the wallet home + Tap the Savings balance card (testTag "ActivitySavings"), tap "Transfer To Spending" (testTag "TransferToSpending") and verify the amount screen opens directly, with no intro + + diff --git a/journeys/transfer/spending-confirm-amount-change.xml b/journeys/transfer/spending-confirm-amount-change.xml new file mode 100644 index 0000000000..5343ebb898 --- /dev/null +++ b/journeys/transfer/spending-confirm-amount-change.xml @@ -0,0 +1,33 @@ + + + Verifies that a transfer to spending never pays more than the total Spending Confirm shows + (synonymdev/bitkit-android#1361). The transfer is priced again at swipe. A price that costs the same + or less pays on that swipe, at the new amount. A price whose total is higher, or that leaves less for + the spending balance, pays nothing: the screen shows the new amounts and a "Fees changed" toast, and + the next swipe pays them. The higher-total case needs a spend of the wallet's own UTXO outside the app, + or a fee rate rise, which the Capabilities table does not list, so unit tests and a manual test cover it. + + The amount changes through coin selection: Spending Confirm sizes the network fee for two inputs, + then a larger UTXO confirms before the swipe, so the transfer priced at swipe spends one input and + pays a lower network fee, at once. + + Precondition: a freshly onboarded dev wallet with Spark connected on its regtest, no channel and + exactly two confirmed on-chain UTXOs of 150 000 sats each (two ./lsp deposits to the wallet's + savings address, each followed by a mine). Start on the wallet home screen. + + + Tap Receive (testTag "Receive"), tap the "Savings" receive tab (the tab row carries no test tag), tap "Show Details" (testTag "ShowDetails"), read the address from testTag "ReceiveOnchainAddress", then press back to the home screen + Tap the Savings balance card (testTag "ActivitySavings"), then "Transfer To Spending" (testTag "TransferToSpending") + If the spending intro appears, tap "Get Started" (testTag "SpendingIntro-button") + Enter 200 000 on the number pad (testTags "N2", "N0", "N0", "N0", "N0", "N0") and tap "Continue" (testTag "SpendingAmountContinue") + Verify the confirm screen is visible (testTag "SpendingConfirmMore") and wait until its network fee is shown + Note the amounts under "Network Fees" (testTag "SpendingConfirmNetworkFee") and "Total" (testTag "SpendingConfirmTotal") + Run in one command: ./lsp POST /regtest/chain/deposit '{"address":"<savings addr>","amountSat":500000}' && ./lsp POST /regtest/chain/mine '{"count":1}' + Wait 30s for the wallet to sync the new UTXO + If the received sheet (testTag "ReceivedTransaction") is visible, tap its button (testTag "ReceivedTransactionButton") + Verify the confirm screen still shows the amounts noted before the deposit + Swipe the "Swipe To Transfer" handle (testTag "GRAB") fully to the right + Verify no "Fees changed" toast appears and the setting up screen (testTag "LightningSettingUp") opens within 90s + Tap "Continue Using Bitkit" (testTag "TransferSuccess-button"), open the newest transfer in the activity list and verify its fee is lower than the "Network Fees" amount noted + + diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index e3fe769fee..1f5a9722b5 100644 --- a/journeys/transfer/transfer-unavailable-sheet.xml +++ b/journeys/transfer/transfer-unavailable-sheet.xml @@ -8,7 +8,9 @@ (testTag "TransferUnavailableContinue"), which opens the existing Manual Setup screen. Receive's Lightning path shows the same sheet content. - Precondition: dev build, onboarded wallet with a positive on-chain Savings balance and no channels. Start on + Precondition: dev build, onboarded wallet with a positive on-chain Savings balance, no channels and Spark + not running (a build without a Breez API key, or Spark's regtest unreachable); with Spark ready, see + spark-transfer-to-spending.xml. Start on the wallet home screen. diff --git a/scripts/spark-regtest-esplora.py b/scripts/spark-regtest-esplora.py new file mode 100755 index 0000000000..d5a3863116 --- /dev/null +++ b/scripts/spark-regtest-esplora.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Esplora endpoint on Spark's regtest chain for a dev build's ldk-node. + +Spark's regtest is Lightspark's own chain. Its only public chain API is a mempool.space instance +(the Breez SDK's regtest default), which answers Esplora's address, transaction and block calls +but has no `/fee-estimates`, which ldk-node reads at start, nor `/block//status`, which its +Lightning sync reads. This proxy serves `/fee-estimates` from the instance's `/v1/fees/recommended`, +builds a block's status from `/block/` and `/block-height/`, and forwards everything +else, so a dev build built with `ESPLORA_URL=http://:` runs on Spark's chain. + +Usage: + python3 scripts/spark-regtest-esplora.py [--port 3999] [--bind 0.0.0.0] [--max-seconds 10800] + # emulator on the same host: ESPLORA_URL=http://10.0.2.2:3999 +""" +import argparse +import json +import threading +import time +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +UPSTREAM = "https://regtest-mempool.us-west-2.sparkinfra.net/api" + + +def log(*parts): + print(time.strftime("%H:%M:%S"), *parts, flush=True) + + +def fetch(path): + with urllib.request.urlopen(f"{UPSTREAM}{path}", timeout=15) as response: + return response.read().decode() + + +def block_status(block_hash): + height = json.loads(fetch(f"/block/{block_hash}"))["height"] + in_best_chain = fetch(f"/block-height/{height}").strip() == block_hash + try: + next_best = fetch(f"/block-height/{height + 1}").strip() if in_best_chain else None + except urllib.error.HTTPError: + next_best = None + return {"in_best_chain": in_best_chain, "height": height, "next_best": next_best} + + +def fee_estimates(): + with urllib.request.urlopen(f"{UPSTREAM}/v1/fees/recommended", timeout=15) as response: + fees = json.load(response) + targets = {1: "fastestFee", 2: "fastestFee", 3: "halfHourFee", 6: "hourFee", 12: "economyFee", 144: "minimumFee"} + return {str(blocks): float(fees.get(key, 1)) for blocks, key in targets.items()} + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.forward() + + def do_POST(self): + self.forward() + + def forward(self): + if self.path.rstrip("/") == "/fee-estimates": + return self.reply(200, json.dumps(fee_estimates()).encode(), "application/json") + parts = self.path.strip("/").split("/") + if len(parts) == 3 and parts[0] == "block" and parts[2] == "status": + return self.reply(200, json.dumps(block_status(parts[1])).encode(), "application/json") + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) if self.command == "POST" else None + request = urllib.request.Request(f"{UPSTREAM}{self.path}", data=body, method=self.command) + if self.headers.get("Content-Type"): + request.add_header("Content-Type", self.headers["Content-Type"]) + try: + with urllib.request.urlopen(request, timeout=30) as response: + self.reply(response.status, response.read(), response.headers.get("Content-Type")) + except urllib.error.HTTPError as error: + self.reply(error.code, error.read(), error.headers.get("Content-Type")) + + def reply(self, status, payload, content_type): + self.send_response(status) + if content_type: + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def log_message(self, fmt, *args): + log(self.command, self.path, *args[1:2]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--port", type=int, default=3999) + parser.add_argument("--bind", default="127.0.0.1") + parser.add_argument("--max-seconds", type=int, default=3 * 3600) + args = parser.parse_args() + server = ThreadingHTTPServer((args.bind, args.port), Handler) + threading.Timer(args.max_seconds, server.shutdown).start() + log(f"serving Spark regtest Esplora on {args.bind}:{args.port} for {args.max_seconds}s") + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/scripts/spark-regtest-fund.py b/scripts/spark-regtest-fund.py new file mode 100755 index 0000000000..20a3f7de16 --- /dev/null +++ b/scripts/spark-regtest-fund.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Fund an address on Spark's regtest chain from Lightspark's regtest faucet. + +Use it on a dev build running on Spark's chain (see `spark-regtest-esplora.py`): fund the Savings +address to test Savings to Spending and the deposit claim, or Spark's deposit address on the Spark +screen to fund Spending directly. Lightspark's API faucet takes HTTP basic auth: set +FAUCET_USERNAME and FAUCET_PASSWORD (issued by Lightspark). The web faucet at +https://app.lightspark.com/regtest-faucet works without them, by hand. + +Usage: + FAUCET_USERNAME=… FAUCET_PASSWORD=… python3 scripts/spark-regtest-fund.py [sats] +""" +import base64 +import json +import os +import sys +import urllib.request + +FAUCET_URL = os.environ.get("FAUCET_URL", "https://api.lightspark.com/graphql/spark/rc") +QUERY = ( + "mutation RequestRegtestFunds($address: String!, $amount_sats: Long!) " + "{ request_regtest_funds(input: {address: $address, amount_sats: $amount_sats}) { transaction_hash } }" +) + + +def main(): + if len(sys.argv) < 2: + sys.exit(__doc__) + address = sys.argv[1] + amount_sats = int(sys.argv[2]) if len(sys.argv) > 2 else 100_000 + username, password = os.environ.get("FAUCET_USERNAME"), os.environ.get("FAUCET_PASSWORD") + if not username or not password: + sys.exit("Set FAUCET_USERNAME and FAUCET_PASSWORD, or use https://app.lightspark.com/regtest-faucet") + body = json.dumps({ + "operationName": "RequestRegtestFunds", + "variables": {"address": address, "amount_sats": amount_sats}, + "query": QUERY, + }).encode() + request = urllib.request.Request(FAUCET_URL, data=body, method="POST") + request.add_header("Content-Type", "application/json") + request.add_header("Authorization", "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()) + with urllib.request.urlopen(request, timeout=60) as response: + result = json.load(response) + if result.get("errors"): + sys.exit("Faucet returned errors: " + ", ".join(e["message"] for e in result["errors"])) + print(result["data"]["request_regtest_funds"]["transaction_hash"]) + + +if __name__ == "__main__": + main() diff --git a/settings.gradle.kts b/settings.gradle.kts index 00170049a1..c9570f5271 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -87,6 +87,10 @@ dependencyResolutionManagement { password = pass } } + maven { + url = uri("https://mvn.breez.technology/releases") + content { includeGroup("breez_sdk_spark") } + } maven { url = uri("https://maven.pkg.github.com/pubky/paykit-rs") credentials { From 4632e7057c001b123cc78796800a35f0510f8989 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 12:36:18 +0100 Subject: [PATCH 002/135] feat: spark chain service on bitkit electrs --- app/src/main/java/to/bitkit/env/Env.kt | 7 +++++++ .../java/to/bitkit/services/SparkService.kt | 13 ++++++++---- .../to/bitkit/env/SparkChainServiceTest.kt | 20 +++++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 09b2fd0dab..f4261c3d2c 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -128,6 +128,12 @@ internal object Env { Network.REGTEST -> "https://mempool.bitkit.stag0.blocktank.to/" } + /** Esplora REST that Spark reads the chain from; null keeps the SDK's default, on staging and regtest. */ + fun sparkChainServiceUrl(network: Network): String? = when (network) { + Network.BITCOIN -> bitkitEsploraUrl + else -> null + } + val blocktankBaseUrl get() = when (network) { Network.BITCOIN -> "https://api1.blocktank.to" @@ -151,6 +157,7 @@ internal object Env { const val chatwootUrl = "https://synonym.to/api/chatwoot" const val newsBaseUrl = "https://feeds.synonym.to/news-feed/api" const val mempoolBaseUrl = "https://mempool.space/api" + const val bitkitEsploraUrl = "https://bitkit.to/electrs" const val pricesWidgetBaseUrl = "https://feeds.synonym.to/price-feed/api" const val APP_STORE_URL = "https://apps.apple.com/app/bitkit-wallet/id6502440655" diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index e11294d0b8..7962f87038 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -1,10 +1,10 @@ package to.bitkit.services import breez_sdk_spark.BreezSdk +import breez_sdk_spark.ChainApiType import breez_sdk_spark.ClaimDepositOutcome import breez_sdk_spark.ClaimDepositRequest import breez_sdk_spark.Config -import breez_sdk_spark.ConnectRequest import breez_sdk_spark.DepositInfo import breez_sdk_spark.EventListener import breez_sdk_spark.FeePolicy @@ -25,13 +25,13 @@ import breez_sdk_spark.PrepareSendPaymentRequest import breez_sdk_spark.PrepareSendPaymentResponse import breez_sdk_spark.ReceivePaymentMethod import breez_sdk_spark.ReceivePaymentRequest +import breez_sdk_spark.SdkBuilder import breez_sdk_spark.SdkEvent import breez_sdk_spark.Seed import breez_sdk_spark.SendPaymentMethod import breez_sdk_spark.SendPaymentOptions import breez_sdk_spark.SendPaymentRequest import breez_sdk_spark.SyncWalletRequest -import breez_sdk_spark.connect import breez_sdk_spark.defaultConfig import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow @@ -143,7 +143,12 @@ class SparkService @Inject constructor( val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) val config = configure(defaultConfig(network), Env.breezApiKey) val storageDir = File(Env.sparkStoragePath(walletIndex)).apply { mkdirs() }.path - val connected = connect(ConnectRequest(config, Seed.Mnemonic(mnemonic, passphrase), storageDir)) + val chainServiceUrl = Env.sparkChainServiceUrl(Env.network) + val connected = SdkBuilder(config, Seed.Mnemonic(mnemonic, passphrase)).use { builder -> + builder.withDefaultStorage(storageDir) + chainServiceUrl?.let { builder.withRestChainService(it, ChainApiType.ESPLORA, null) } + builder.build() + } listenerId = connected.addEventListener( object : EventListener { override suspend fun onEvent(event: SdkEvent) { @@ -152,7 +157,7 @@ class SparkService @Inject constructor( }, ) sdk = connected - Logger.info("Connected Spark wallet on '$network'", context = TAG) + Logger.info("Connected Spark wallet on '$network' with chain '${chainServiceUrl ?: "default"}'", context = TAG) } suspend fun disconnect() = mutex.withLock { diff --git a/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt b/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt new file mode 100644 index 0000000000..597e6127b6 --- /dev/null +++ b/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt @@ -0,0 +1,20 @@ +package to.bitkit.env + +import org.junit.Test +import org.lightningdevkit.ldknode.Network +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class SparkChainServiceTest { + @Test + fun `spark reads the chain from bitkit electrs on mainnet`() { + assertEquals("https://bitkit.to/electrs", Env.sparkChainServiceUrl(Network.BITCOIN)) + } + + @Test + fun `spark keeps the sdk default chain service off mainnet`() { + assertNull(Env.sparkChainServiceUrl(Network.REGTEST)) + assertNull(Env.sparkChainServiceUrl(Network.TESTNET)) + assertNull(Env.sparkChainServiceUrl(Network.SIGNET)) + } +} From 4e22b9ca3c3fc0b8e1523e9244e1248fd9e109a0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 22:26:52 +0100 Subject: [PATCH 003/135] chore: bump spark sdk to 0.28.0 --- .../java/to/bitkit/repositories/SparkRepo.kt | 21 +++++++++--- .../java/to/bitkit/services/SparkService.kt | 14 ++++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++ .../to/bitkit/repositories/SparkRepoTest.kt | 32 ++++++++++++++++--- gradle/libs.versions.toml | 2 +- 5 files changed, 61 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 398d92f4b5..c31826b0fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -175,8 +175,9 @@ class SparkRepo @Inject constructor( /** * Pays [bolt11] and returns its payment hash, the id ldk-node payments use, so the send flow can match it. * Fails with [SparkError.SendRefused] when nothing left the wallet: Spark was not connected, could not prepare the - * payment, or its fee was over [maxTotalFeeMsat]; and with [ServiceError.PaymentDeadlineExpired] past - * [paymentDeadlineAt]. A failure inside the send itself stays uncertain, as the payment may have been dispatched. + * payment, or its fee was over [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a [SparkError.SendRefused], + * when Spark refuses an expired invoice at prepare or send; and with [ServiceError.PaymentDeadlineExpired] past + * [paymentDeadlineAt]. Any other failure inside the send stays uncertain, as the payment may have been dispatched. */ suspend fun payInvoice( bolt11: String, @@ -187,8 +188,10 @@ class SparkRepo @Inject constructor( runSuspendCatching { ensurePaymentDeadline(paymentDeadlineAt) if (!sparkService.isConnected) throw SparkError.SendRefused("Spark is not connected") - val prepared = runSuspendCatching { sparkService.prepareSend(bolt11, amountSats) } - .getOrElse { throw SparkError.SendRefused("Spark could not prepare the payment", it) } + val prepared = runSuspendCatching { sparkService.prepareSend(bolt11, amountSats) }.getOrElse { + if (it.isInvoiceExpired()) throw SparkError.InvoiceExpired(it) + throw SparkError.SendRefused("Spark could not prepare the payment", it) + } val method = prepared.paymentMethod as? SendPaymentMethod.Bolt11Invoice ?: throw SparkError.SendRefused("Unexpected Spark payment method '${prepared.paymentMethod}'") val feeSats = method.feeSats() @@ -196,7 +199,10 @@ class SparkRepo @Inject constructor( throw SparkError.SendRefused("Spark fee '$feeSats' sats is over the limit '$maxTotalFeeMsat' msat") } ensurePaymentDeadline(paymentDeadlineAt) - val payment = sparkService.send(prepared) + val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { + if (it.isInvoiceExpired()) throw SparkError.InvoiceExpired(it) + throw it + } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) method.invoiceDetails.paymentHash }.onFailure { @@ -426,6 +432,7 @@ class SparkRepo @Inject constructor( private suspend fun refresh() { val info = sparkService.getInfo() + info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val pending = sparkService.listUnclaimedDeposits().map { SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) } @@ -866,6 +873,10 @@ sealed interface SparkClaimStep { } /** What accepting the early claim of [offer] leaves the deposit at. */ +/** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ +internal fun Throwable.isInvoiceExpired(): Boolean = + this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) + fun SparkEarlyClaim.toDepositClaim(offer: SparkClaimOffer.Choice): SparkDepositClaim = when (this) { SparkEarlyClaim.Claimed -> SparkDepositClaim.Adding SparkEarlyClaim.Waiting -> SparkDepositClaim.Looking diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 7962f87038..b18d646e5b 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -182,7 +182,14 @@ class SparkService @Inject constructor( suspend fun getInfo(): GetInfoResponse = requireSdk().getInfo(GetInfoRequest(ensureSynced = false)) suspend fun receiveBolt11(amountSats: ULong?, description: String, expirySecs: UInt): String { - val method = ReceivePaymentMethod.Bolt11Invoice(description, amountSats, expirySecs, null, null) + val method = ReceivePaymentMethod.Bolt11Invoice( + description = description, + amountSats = amountSats, + expirySecs = expirySecs, + paymentHash = null, + receiverIdentityPublicKey = null, + preimage = null, + ) return requireSdk().receivePayment(ReceivePaymentRequest(method)).paymentRequest } @@ -267,5 +274,8 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me * Spark refused a Lightning payment before anything left the wallet: it was not connected, could not prepare the * payment, or its fee was over the caller's limit. A Paykit request or allowance attempt can then end as failed. */ - class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) + open class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) + + /** Spark refused to pay an expired Lightning invoice, before anything left the wallet. */ + class InvoiceExpired(cause: Throwable? = null) : SendRefused("The Lightning invoice has expired", cause) } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 6fabcf9943..4910e95a4b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -235,6 +235,7 @@ import to.bitkit.services.MigrationService import to.bitkit.services.NodeServiceFgState import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.services.PubkyService +import to.bitkit.services.SparkError import to.bitkit.ui.ID_NOTIFICATION_SKIPPED import to.bitkit.ui.Routes import to.bitkit.ui.components.AllowanceRoute @@ -6684,6 +6685,9 @@ class AppViewModel @Inject constructor( Logger.error("Error sending lightning payment", error, context = TAG) val failure = when (error) { is LightningPaymentFailedError -> error.reason.toSendFailureDetails(context, error.paymentRequest) + is SparkError.InvoiceExpired -> + PaymentFailureReason.PAYMENT_EXPIRED.toSendFailureDetails(context, decodedInvoice.bolt11) + .copy(message = context.getString(R.string.other__scan__error__expired)) else -> error.toSendFailureDetails(context, _sendUiState.value.currentLightningPaymentRequest()) } setSendEffect(SendEffect.NavigateToError(failure)) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index dc56da0703..eb72b5c082 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -98,7 +98,7 @@ class SparkRepoTest : BaseUnitTest() { @Before fun setUp() { Env.initAppStoragePath(tempFolder.root.absolutePath) - whenever { sparkService.getInfo() }.thenReturn(GetInfoResponse("pubkey", 0uL, emptyMap(), 0uL)) + whenever { sparkService.getInfo() }.thenReturn(info(0uL)) whenever { sparkService.listUnclaimedDeposits() }.thenReturn(emptyList()) whenever { sparkService.listPayments() }.thenReturn(emptyList()) whenever(sparkService.events).thenReturn(sparkEvents) @@ -157,7 +157,7 @@ class SparkRepoTest : BaseUnitTest() { .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) val sent = sentPayment(fees = 1_470).copy( method = PaymentMethod.WITHDRAW, - details = PaymentDetails.Withdraw("withdrawal"), + details = PaymentDetails.Withdraw("withdrawal", 0u, ADDRESS), ) whenever { sparkService.send(any()) }.thenReturn(sent) val sut = createSut() @@ -187,7 +187,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { activityRepo.updateActivity(any(), any(), any()) }.thenReturn(Result.success(Unit)) val withdrawal = sentPayment(fees = 1_470).copy( method = PaymentMethod.WITHDRAW, - details = PaymentDetails.Withdraw("withdrawal"), + details = PaymentDetails.Withdraw("withdrawal", 0u, ADDRESS), ) whenever { sparkService.listPayments() }.thenReturn(listOf(withdrawal)) whenever(sparkService.isConnected).thenReturn(true) @@ -411,6 +411,21 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `an expired invoice spark refuses is a typed refusal`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val expired = SdkException.InvalidInput("Invoice has expired") + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { throw expired } + val sut = createSut() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw expired } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + } + @Test fun `a spark send over the fee limit is refused before it leaves`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -486,7 +501,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `can send leaves room for spark's service fee`() = test { whenever(sparkService.isConnected).thenReturn(true) - whenever { sparkService.getInfo() }.thenReturn(GetInfoResponse("pubkey", 100_000uL, emptyMap(), 0uL)) + whenever { sparkService.getInfo() }.thenReturn(info(100_000uL)) val sut = createSut() sut.start(0).getOrThrow() @@ -504,6 +519,15 @@ class SparkRepoTest : BaseUnitTest() { } } + private fun info(balanceSats: ULong) = GetInfoResponse( + identityPubkey = "pubkey", + balanceSats = balanceSats, + tokenBalances = emptyMap(), + recoverableFundsSats = 0uL, + lastSyncError = null, + lastSyncedAt = null, + ) + private fun prepared(feeSats: ULong): PrepareSendPaymentResponse { val details = mock { on { paymentHash } doReturn "hash" } return PrepareSendPaymentResponse( diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a899b0db87..a84ae005dd 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-alpha05" } bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc11" } -breez-sdk-spark = { module = "breez_sdk_spark:bindings-android", version = "0.27.2" } +breez-sdk-spark = { module = "breez_sdk_spark:bindings-android", version = "0.28.0" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } From 9b76a136de342b0f3533400118b4cb5ec2c17e86 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 19:23:47 +0100 Subject: [PATCH 004/135] fix: harden spark backup, wipe, sends and withdrawals --- app/src/main/java/to/bitkit/env/Env.kt | 1 + .../to/bitkit/ext/PaymentFailureReasonExt.kt | 7 +- .../java/to/bitkit/repositories/BackupRepo.kt | 29 ++- .../to/bitkit/repositories/LightningRepo.kt | 34 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 212 +++++++++++++----- .../java/to/bitkit/services/SparkService.kt | 44 +++- .../screens/transfer/SavingsConfirmScreen.kt | 31 ++- .../screens/transfer/SparkFundingViewModel.kt | 18 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 14 +- .../to/bitkit/viewmodels/TransferViewModel.kt | 45 +++- .../bitkit/ext/PaymentFailureReasonExtTest.kt | 13 ++ .../to/bitkit/repositories/BackupRepoTest.kt | 64 +++++- .../to/bitkit/repositories/SparkRepoTest.kt | 134 ++++++++++- .../to/bitkit/services/SparkServiceTest.kt | 40 +++- .../test/java/to/bitkit/test/IdleSparkRepo.kt | 2 + .../viewmodels/TransferViewModelTest.kt | 46 +++- 16 files changed, 610 insertions(+), 124 deletions(-) diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index f4261c3d2c..8f035eb59d 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -39,6 +39,7 @@ internal object Env { */ val regtestEsploraUrl: String? get() = BuildConfig.ESPLORA_URL.takeIf { it.isNotBlank() && network == Network.REGTEST } + val isDebug = BuildConfig.DEBUG const val isE2eTest = BuildConfig.E2E val e2eBackend = BuildConfig.E2E_BACKEND.lowercase() diff --git a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt index accb33f6a1..6ac4dc62ae 100644 --- a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt @@ -1,9 +1,11 @@ package to.bitkit.ext import android.content.Context +import breez_sdk_spark.SdkException import org.lightningdevkit.ldknode.PaymentFailureReason import to.bitkit.R import to.bitkit.models.SendFailureDetails +import to.bitkit.services.SparkError import to.bitkit.utils.LdkError fun PaymentFailureReason?.toUserMessage(context: Context): String = when (this) { @@ -49,7 +51,10 @@ fun Throwable.toSendFailureMessage(context: Context): String { val fallbackMessage = context.getString(R.string.wallet__payment_failed_description) val rawMessage = message?.trim().orEmpty() - if (this is LdkError || rawMessage.isBlank() || rawMessage.looksInternalPaymentError()) { + // Spark and its SDK speak in English developer messages; they go to the log, the user gets the existing copy. + if (this is LdkError || this is SparkError || this is SdkException || rawMessage.isBlank() || + rawMessage.looksInternalPaymentError() + ) { return fallbackMessage } diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 1c02e49080..7fdcaac026 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -439,12 +439,12 @@ class BackupRepo @Inject constructor( // payment and sync traffic does not re-upload the whole metadata envelope. dataListenerJobs.add(observeBackupChanges(activityRepo.activityTagsChanged, BackupCategory.METADATA)) - // SPARK_EXIT - back up once Spark is ready, which replays when observing starts after it connected, + // SPARK_EXIT - back up once Spark is ready and synced, which replays when observing starts after that, // and again whenever Spark announces its unilateral exit data changed dataListenerJobs.add( scope.launch { merge( - sparkRepo.state.map { it.isReady }.distinctUntilChanged().filter { it }, + sparkRepo.state.map { it.isReady && it.hasSynced }.distinctUntilChanged().filter { it }, sparkRepo.exitStateChanged, ).collect { if (shouldSkipBackup()) return@collect @@ -511,7 +511,7 @@ class BackupRepo @Inject constructor( it.copy(running = true) } - delay(BACKUP_DEBOUNCE) + delay(if (category == BackupCategory.SPARK_EXIT) SPARK_EXIT_BACKUP_DEBOUNCE else BACKUP_DEBOUNCE) if (category == BackupCategory.WALLET) paykitSdkService.isPaymentSubmissionActive.first { !it } val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() @@ -638,9 +638,19 @@ class BackupRepo @Inject constructor( } } - /** Nothing to back up until Spark connects, which marks [BackupCategory.SPARK_EXIT] required again. */ + /** + * Defers until Spark has connected and synced, which marks [BackupCategory.SPARK_EXIT] required again. The first + * upload merges the stored backup into Spark before replacing it, and fails rather than replace one it could not + * read, so a failed or skipped restore never loses the stored exit data. + */ private suspend fun uploadSparkExitBackup(): Result = runSuspendCatching { - val backup = sparkRepo.exitBackup().getOrThrow() ?: return@runSuspendCatching + if (!sparkRepo.hasMergedRemoteExitState) { + sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() + val remote = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + ?.let { json.decodeFromString(String(it)) } + sparkRepo.mergeRemoteExitBackup(remote).getOrThrow() + } + val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() vssBackupClient.putObject( key = BackupCategory.SPARK_EXIT.name, data = json.encodeToString(backup).toByteArray(), @@ -708,6 +718,8 @@ class BackupRepo @Inject constructor( when { e is WalletBackupSnapshotChanged -> Logger.debug("Deferred changing backup snapshot for: '$category'", context = TAG) + e is SparkExitBackupDeferred -> + Logger.debug("Deferred backup until Spark syncs for: '$category'", context = TAG) e.isTemporaryBackupFailure() -> retryAfterTemporaryFailure(category, backupRequired, e) else -> Logger.error("Backup failed for: '$category'", e, context = TAG) } @@ -988,7 +1000,7 @@ class BackupRepo @Inject constructor( // SETTINGS is optional; preserving explicit local corrections is required. connectionSession.replay() // Before the slower categories, so the exit data is staged before Spark connects and syncs. - performRestore(BackupCategory.SPARK_EXIT) { dataBytes -> + performRestore(BackupCategory.SPARK_EXIT, failedCategories) { dataBytes -> val parsed = json.decodeFromString(String(dataBytes)) sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow() parsed.createdAt @@ -1383,6 +1395,9 @@ class BackupRepo @Inject constructor( private const val MINUTE_IN_MS = 60_000 private const val BACKUP_DEBOUNCE = 5000L // 5 seconds + /** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */ + private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L + /** Maximum captures before deferring a changing wallet to the next scheduled backup. */ private const val WALLET_SNAPSHOT_ATTEMPTS = 3 @@ -1411,6 +1426,8 @@ class BackupRepo @Inject constructor( internal class WalletBackupSnapshotChanged : AppError("Private payment state changed during wallet snapshot") +internal class SparkExitBackupDeferred : AppError("Spark has not connected and synced yet") + private class PublicAddressRestoreFailed(cause: Throwable) : AppError( "Failed to retain public address exclusion during restore", cause, diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index ad995b68cc..bf146c5f87 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -374,7 +374,7 @@ class LightningRepo @Inject constructor( if (shouldCancelPendingStop) cancelPendingStop() // Spark needs no node, so it starts alongside it and stays up while the node stops in background. - scope.launch { sparkRepo.start(walletIndex) } + if (!isWiping) scope.launch { sparkRepo.start(walletIndex) } eventHandler?.let { _eventHandlers.add(it) } @@ -683,7 +683,10 @@ class LightningRepo @Inject constructor( fun setRecoveryMode(enabled: Boolean) = _isRecoveryMode.update { enabled } - fun setWiping(enabled: Boolean) = run { isWiping = enabled } + fun setWiping(enabled: Boolean) = run { + isWiping = enabled + sparkRepo.setWiping(enabled) + } fun setInitNodeLifecycleState() { _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Initializing) } @@ -931,7 +934,7 @@ class LightningRepo @Inject constructor( lastKnownNodeId = null _lastKnownChannels.update { persistentListOf() } lightningService.wipeStorage(walletIndex) - sparkRepo.wipe(walletIndex) + sparkRepo.wipe(walletIndex).getOrThrow() clearProbeOutcomes() _lightningState.update { LightningState( @@ -1341,9 +1344,11 @@ class LightningRepo @Inject constructor( expirySeconds: UInt = Defaults.bolt11ExpirySec, ): Result = executeWhenNodeRunning("createInvoiceMsats") { requireWalletRestoreComplete() - if (shouldReceiveWithSpark(amountMsats / MSATS_PER_SAT)) { - val amountSats = (amountMsats / MSATS_PER_SAT).takeIf { it > 0uL } - return@executeWhenNodeRunning sparkRepo.createInvoice(amountSats, description, expirySeconds) + // Spark invoices hold whole sats, so a sub-sat part rounds up rather than dropping the amount. + val amountSats = (amountMsats.safe() + (MSATS_PER_SAT - 1uL).safe()) / MSATS_PER_SAT + if (shouldReceiveWithSpark(amountSats)) { + val invoiceSats = amountSats.takeIf { it > 0uL } + return@executeWhenNodeRunning sparkRepo.createInvoice(invoiceSats, description, expirySeconds) } runCatching { lightningService.receiveMsats(amountMsats, description, expirySeconds) } } @@ -2455,6 +2460,20 @@ class LightningRepo @Inject constructor( } } + /** + * What a Max send of the amountless [bolt11] keeps below [maxSendSats] for its fees: Spark's quote for sending its + * whole balance when Spark pays it, otherwise the routing fee for [maxSendSats] with a small buffer. + */ + suspend fun estimateMaxSendFee(bolt11: String, maxSendSats: ULong): Result { + if (shouldPayWithSpark(bolt11, maxSendSats)) { + sparkRepo.maxSendReserveSats(bolt11) + .onSuccess { return Result.success(it) } + .onFailure { Logger.warn("Failed to price a Max Spark send", it, context = TAG) } + } + val amountSats = maxSendSats.safe() - MAX_SEND_FEE_BUFFER_SATS.safe() + return estimateRoutingFeesForAmount(bolt11, amountSats).map { it.safe() + MAX_SEND_FEE_BUFFER_SATS.safe() } + } + // region debug fun getNetworkGraphInfo() = lightningService.getNetworkGraphInfo() @@ -2749,6 +2768,9 @@ class LightningRepo @Inject constructor( private const val MS_SYNC_LOOP_DEBOUNCE = 500L private const val SYNC_RETRY_DELAY_MS = 15_000L private const val MSATS_PER_SAT = 1_000uL + + /** Sats a Max Lightning send keeps beyond its estimated routing fee, as routes can price slightly higher. */ + private const val MAX_SEND_FEE_BUFFER_SATS = 2uL private val BACKGROUND_STOP_DELAY = 5.seconds private val CHANNELS_USABLE_TIMEOUT = 15.seconds private val CHANNELS_USABLE_POLL_DELAY = 1.seconds diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c31826b0fc..4fe97e6afa 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -32,6 +32,8 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason @@ -39,6 +41,7 @@ import org.lightningdevkit.ldknode.PaymentId import to.bitkit.async.appScope import to.bitkit.data.CacheStore import to.bitkit.di.BgDispatcher +import to.bitkit.env.Defaults import to.bitkit.env.Env import to.bitkit.ext.create import to.bitkit.ext.nowMillis @@ -52,6 +55,7 @@ import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import java.io.File import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @@ -105,7 +109,16 @@ class SparkRepo @Inject constructor( /** Sends recorded before Spark knew their fee; its completion event reports 0 until a later sync. */ private val sendsRecordedWithoutFee = ConcurrentHashMap.newKeySet() - private var eventsJob: Job? = null + private val isCollectingEvents = AtomicBoolean(false) + + private val refreshMutex = Mutex() + + private val sendsInFlight = ConcurrentHashMap.newKeySet() + + /** The remote exit data backup was merged in, or there was none, so an upload cannot drop what it held. */ + @Volatile + var hasMergedRemoteExitState = false + private set /** Watchers of the claims of deposits this app sent, by txid; they outlive the screens that start them. */ private val claimJobs = ConcurrentHashMap() @@ -129,9 +142,15 @@ class SparkRepo @Inject constructor( suspend fun start(walletIndex: Int): Result = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext Result.success(Unit) runSuspendCatching { - if (eventsJob == null) eventsJob = scope.launch { sparkService.events.collect { onSdkEvent(it) } } + if (isCollectingEvents.compareAndSet(false, true)) { + scope.launch { sparkService.events.collect { onSdkEvent(it) } } + } sparkService.connect(walletIndex) importRestoredExitState(walletIndex) + // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. + runSuspendCatching { sparkService.syncWallet() } + .onSuccess { _state.update { it.copy(hasSynced = true) } } + .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } _exitStateChanged.emit(Unit) refresh() syncActivities() @@ -140,16 +159,25 @@ class SparkRepo @Inject constructor( } } - suspend fun stop() = withContext(bgDispatcher) { - runSuspendCatching { sparkService.disconnect() } - .onFailure { Logger.warn("Failed to stop Spark wallet", it, context = TAG) } - _state.update { it.copy(isReady = false, hasSynced = false) } - } + /** Holds Spark's start off for the whole wallet wipe. */ + fun setWiping(isWiping: Boolean) = run { sparkService.isWiping = isWiping } - suspend fun wipe(walletIndex: Int) = withContext(bgDispatcher) { - runSuspendCatching { sparkService.wipeStorage(walletIndex) } - .onFailure { Logger.error("Failed to wipe Spark wallet", it, context = TAG) } + /** + * Disconnects Spark and deletes its storage and in-memory state. Spark stays connected for the life of the + * process otherwise, so a node stopped in background keeps Lightning available through it. + */ + suspend fun wipe(walletIndex: Int): Result = withContext(bgDispatcher) { + claimJobs.values.forEach { it.cancel() } + claimJobs.clear() + preparedWithdrawal = null + withdrawalTxids.clear() + broadcastDeposits.clear() + sendsRecordedWithoutFee.clear() + sendsInFlight.clear() + hasMergedRemoteExitState = false + _depositClaims.update { emptyMap() } _state.update { SparkState(isSupported = sparkService.isSupported) } + runSuspendCatching { sparkService.wipeStorage(walletIndex) } } fun canReceive(): Boolean = _state.value.isReady @@ -169,6 +197,21 @@ class SparkRepo @Inject constructor( } } + /** + * How far a Max send of the amountless [bolt11] stays below [SparkState.sendableSats], which keeps only the + * service fee: the SDK prices sending the whole balance with its fees included, so the amount plus its routing + * and service fees fits the balance. + */ + suspend fun maxSendReserveSats(bolt11: String): Result = withContext(bgDispatcher) { + runSuspendCatching { + val balanceSats = sparkService.getInfo().balanceSats + val method = sparkService.prepareSend(bolt11, balanceSats, FeePolicy.FEES_INCLUDED).paymentMethod + val feeSats = (method as SendPaymentMethod.Bolt11Invoice).feeSats() + val maxSats = balanceSats.safe() - feeSats.safe() + SparkFees.sendableSats(balanceSats).safe() - maxSats.safe() + } + } + private fun SendPaymentMethod.Bolt11Invoice.feeSats(): ULong = sparkTransferFeeSats?.takeIf { sparkService.prefersSpark } ?: lightningFeeSats @@ -177,7 +220,9 @@ class SparkRepo @Inject constructor( * Fails with [SparkError.SendRefused] when nothing left the wallet: Spark was not connected, could not prepare the * payment, or its fee was over [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a [SparkError.SendRefused], * when Spark refuses an expired invoice at prepare or send; and with [ServiceError.PaymentDeadlineExpired] past - * [paymentDeadlineAt]. Any other failure inside the send stays uncertain, as the payment may have been dispatched. + * [paymentDeadlineAt]. A failure inside the send is a [PaymentPendingException], as the payment may have been + * dispatched, and its event decides it. An invoice this wallet already sends is not sent again: one in flight or + * pending fails with [PaymentPendingException], and one Spark completed returns its hash. */ suspend fun payInvoice( bolt11: String, @@ -199,17 +244,50 @@ class SparkRepo @Inject constructor( throw SparkError.SendRefused("Spark fee '$feeSats' sats is over the limit '$maxTotalFeeMsat' msat") } ensurePaymentDeadline(paymentDeadlineAt) - val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { + val paymentHash = method.invoiceDetails.paymentHash + when (val earlier = lightningSend(paymentHash)) { + is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> { + Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) + return@runSuspendCatching paymentHash + } + is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> + throw PaymentPendingException(paymentHash) + else -> Unit + } + if (!sendsInFlight.add(paymentHash.lowercase())) throw PaymentPendingException(paymentHash) + val sent = try { + runSuspendCatching { sparkService.send(prepared) } + } finally { + sendsInFlight.remove(paymentHash.lowercase()) + } + val payment = sent.getOrElse { if (it.isInvoiceExpired()) throw SparkError.InvoiceExpired(it) - throw it + Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) + settleUncertainSend(paymentHash) + throw PaymentPendingException(paymentHash) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) - method.invoiceDetails.paymentHash + paymentHash }.onFailure { Logger.error("Failed to pay invoice with Spark", it, context = TAG) } } + private fun settleUncertainSend(paymentHash: String) { + scope.launch { + runSuspendCatching { sparkService.syncWallet() } + .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } + .onSuccess { _state.update { it.copy(hasSynced = true) } } + val event = when (lightningSend(paymentHash)) { + SparkLightningSend.NotFound -> + Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR) + is SparkLightningSend.Found -> settledSendEvent(paymentHash) + SparkLightningSend.Unavailable -> null + } + event?.let { _nodeEvents.emit(it) } + } + } + private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) { if (paymentDeadlineAt != null && clock.now() > paymentDeadlineAt) throw ServiceError.PaymentDeadlineExpired() } @@ -302,28 +380,30 @@ class SparkRepo @Inject constructor( /** Accepts the early claim of [offer] at its quoted fee. */ suspend fun claimEarly(offer: SparkClaimOffer.Choice): Result = withContext(bgDispatcher) { - runSuspendCatching { - try { - SparkEarlyClaim.from(sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats)) - } catch (_: SdkException.DepositClaimInProgress) { - SparkEarlyClaim.Claimed + runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats) } + .map { SparkEarlyClaim.from(it) } + .recover { if (it is SdkException.DepositClaimInProgress) SparkEarlyClaim.Claimed else throw it } + .onSuccess { + Logger.info("Early claim of Spark deposit '${offer.txid}': '$it'", context = TAG) + refresh() } - }.onSuccess { - Logger.info("Early claim of Spark deposit '${offer.txid}': '$it'", context = TAG) - refresh() - }.onFailure { - Logger.error("Failed to claim Spark deposit '${offer.txid}' early", it, context = TAG) - } + .onFailure { Logger.error("Failed to claim Spark deposit '${offer.txid}' early", it, context = TAG) } } suspend fun depositAddress(): Result = withContext(bgDispatcher) { runSuspendCatching { sparkService.depositAddress() } } - /** Moves the whole Spark balance to the on-chain [address], fees included, for Spending to Savings. */ - suspend fun withdrawAll(address: String): Result = withContext(bgDispatcher) { + /** + * Moves the whole Spark balance to the on-chain [address], fees included, for Spending to Savings. Fails with + * [SparkError.WithdrawalFeeChanged] when its fee is above [confirmedFeeSats], the fee the user confirmed, and with + * [SparkError.WithdrawalTooSmall] when what reaches [address] would be dust. + */ + suspend fun withdrawAll(address: String, confirmedFeeSats: ULong): Result = withContext(bgDispatcher) { runSuspendCatching { - val payment = sparkService.send(prepareWithdrawAll(address)) + val prepared = prepareWithdrawAll(address) + if (prepared.feeSats() > confirmedFeeSats) throw SparkError.WithdrawalFeeChanged() + val payment = sparkService.send(prepared.response) preparedWithdrawal = null (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } refresh() @@ -335,28 +415,28 @@ class SparkRepo @Inject constructor( /** The fee [withdrawAll] pays at its speed, which comes out of the balance it moves. */ suspend fun estimateWithdrawAllFeeSats(address: String): Result = withContext(bgDispatcher) { runSuspendCatching { - val speed = prepareWithdrawAll(address).withdrawalQuote().speedMedium - speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe() + prepareWithdrawAll(address).feeSats() } } - /** - * Reuses the provider's withdrawal quote while it holds for the same address and balance, so the fee the confirm - * screen shows is the one the withdrawal pays; asking for a second quote while one held took minutes on regtest. - */ - private suspend fun prepareWithdrawAll(address: String): PrepareSendPaymentResponse { - val balanceSats = _state.value.balanceSats + private suspend fun prepareWithdrawAll(address: String): PreparedWithdrawal { + // A held quote is reused, as asking for a second one took minutes on regtest. + val balanceSats = sparkService.getInfo().balanceSats val nowSecs = clock.now().epochSeconds.toULong() preparedWithdrawal ?.takeIf { it.address == address && it.balanceSats == balanceSats } ?.takeIf { it.response.withdrawalQuote().expiresAt > nowSecs.safe() + QUOTE_EXPIRY_MARGIN_SECS.safe() } - ?.let { return it.response } - return sparkService.prepareSend(address, balanceSats, FeePolicy.FEES_INCLUDED) - .also { preparedWithdrawal = PreparedWithdrawal(address, balanceSats, it) } + ?.let { return it } + val response = sparkService.prepareSend(address, balanceSats, FeePolicy.FEES_INCLUDED) + return PreparedWithdrawal(address, balanceSats, response).also { preparedWithdrawal = it } } - private fun PrepareSendPaymentResponse.withdrawalQuote(): SendOnchainFeeQuote = - (paymentMethod as SendPaymentMethod.BitcoinAddress).feeQuote + private fun PreparedWithdrawal.feeSats(): ULong { + val speed = response.withdrawalQuote().speedMedium + val feeSats = speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe() + if (balanceSats < feeSats.safe() + Defaults.dustLimit.toULong().safe()) throw SparkError.WithdrawalTooSmall() + return feeSats + } /** * Lists a deposit the app just broadcast as pending right away, then syncs so Spark sees it sooner than its @@ -385,15 +465,32 @@ class SparkRepo @Inject constructor( ) } - /** The exit data backup, or null while Spark is not connected and there is nothing to back up. */ + /** + * The exit data backup, or null until Spark has connected and synced once, since an export taken before its + * first sync can miss what the wallet holds. + */ suspend fun exitBackup(): Result = withContext(bgDispatcher) { runSuspendCatching { val network = sparkService.networkName - if (!sparkService.isConnected || network == null) return@runSuspendCatching null + if (!sparkService.isConnected || network == null || !_state.value.hasSynced) return@runSuspendCatching null SparkExitBackupV1(createdAt = nowMillis(), network = network, exitState = sparkService.exportExitState()) } } + /** + * Merges the exit data backup already stored, [remote], or none, into Spark before the first upload replaces it, + * so that upload holds everything the stored one did. Spark must be connected. + */ + suspend fun mergeRemoteExitBackup(remote: SparkExitBackupV1?): Result = withContext(bgDispatcher) { + runSuspendCatching { + if (remote != null && remote.network == sparkService.networkName) { + val merged = sparkService.importExitState(remote.exitState) + Logger.info("Merged stored Spark exit data: '${merged.importedLeaves}' leaves", context = TAG) + } + hasMergedRemoteExitState = true + } + } + /** * Puts a restored exit data backup back: at once while Spark is connected, otherwise right after it connects, * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. @@ -430,7 +527,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() }.onFailure { Logger.warn("Failed to refresh Spark state", it, context = TAG) } } - private suspend fun refresh() { + private suspend fun refresh() = refreshMutex.withLock { val info = sparkService.getInfo() info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val pending = sparkService.listUnclaimedDeposits().map { @@ -457,7 +554,6 @@ class SparkRepo @Inject constructor( pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), withdrawals = payments.toWithdrawals(), - recoverableFundsSats = info.recoverableFundsSats, ).withBroadcastDeposits() } payments.filter { it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0 }.forEach { recordActivity(it) } @@ -508,10 +604,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() - ?.firstOrNull { - val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash - it.paymentType == SparkPaymentType.SEND && hash.equals(paymentHash, ignoreCase = true) - } + ?.latestSend(paymentHash) ?.toNodeEvent() } @@ -533,17 +626,18 @@ class SparkRepo @Inject constructor( val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext SparkLightningSend.Unavailable } - payments - .filter { - val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash - it.paymentType == SparkPaymentType.SEND && hash.equals(paymentHash, ignoreCase = true) - } - // A retry of a failed send shares its hash, so the outcome that settles it wins. - .minByOrNull { SEND_STATUS_PRIORITY.indexOf(it.status) } + payments.latestSend(paymentHash) ?.let { SparkLightningSend.Found(it.status, (it.details as PaymentDetails.Lightning).htlcDetails.preimage) } ?: SparkLightningSend.NotFound } + private fun List.latestSend(paymentHash: String): Payment? = filter { + val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash + it.paymentType == SparkPaymentType.SEND && hash.equals(paymentHash, ignoreCase = true) + } + // A retry of a failed send shares its hash, so the outcome that settles it wins. + .minByOrNull { SEND_STATUS_PRIORITY.indexOf(it.status) } + /** Payment hashes of the Lightning payments Spark received. */ suspend fun receivedLightningPaymentHashes(): Set = lightningPaymentHashes { it.paymentType == SparkPaymentType.RECEIVE && it.status == PaymentStatus.COMPLETED } @@ -660,6 +754,9 @@ class SparkRepo @Inject constructor( } } +private fun PrepareSendPaymentResponse.withdrawalQuote(): SendOnchainFeeQuote = + (paymentMethod as SendPaymentMethod.BitcoinAddress).feeQuote + private class PreparedWithdrawal( val address: String, val balanceSats: ULong, @@ -676,7 +773,6 @@ data class SparkState( val pendingDepositSats: ULong = 0uL, val deposits: ImmutableList = persistentListOf(), val withdrawals: ImmutableList = persistentListOf(), - val recoverableFundsSats: ULong = 0uL, ) { /** The most Spark can send once its service fee is paid, so a payment near the full balance isn't offered. */ val sendableSats: ULong get() = SparkFees.sendableSats(balanceSats) @@ -872,11 +968,11 @@ sealed interface SparkClaimStep { } } -/** What accepting the early claim of [offer] leaves the deposit at. */ /** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ internal fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) +/** What accepting the early claim of [offer] leaves the deposit at. */ fun SparkEarlyClaim.toDepositClaim(offer: SparkClaimOffer.Choice): SparkDepositClaim = when (this) { SparkEarlyClaim.Claimed -> SparkDepositClaim.Adding SparkEarlyClaim.Waiting -> SparkDepositClaim.Looking diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index b18d646e5b..cef9e61f39 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -41,6 +41,7 @@ import kotlinx.coroutines.sync.withLock import org.lightningdevkit.ldknode.Network import to.bitkit.data.keychain.Keychain import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.safe import to.bitkit.utils.AppError import to.bitkit.utils.Logger @@ -63,13 +64,15 @@ class SparkService @Inject constructor( private const val TAG = "SparkService" /** - * Bitkit's settings over the SDK's [defaults]. Breez's real-time data sync server and its Lightning address - * (LNURL) server stay off on every network. + * Bitkit's settings over the SDK's [defaults]. Breez's real-time data sync server, its Lightning address + * (LNURL) server and its default external input parsers stay off on every network. */ internal fun configure(defaults: Config, apiKey: String?): Config = defaults.apply { this.apiKey = apiKey realTimeSyncServerUrl = null lnurlDomain = null + // Bitkit parses what the user scans itself, so the SDK never sends it to third-party parsers. + useDefaultExternalInputParsers = false // Lowering it below the spread keeps the deposit from being claimed early, and does not hold back its // claim at maturity. maxDepositClaimFee = MaxFee( @@ -130,6 +133,10 @@ class SparkService @Inject constructor( val isConnected: Boolean get() = sdk != null + /** Set for the whole wallet wipe, so a start that races it cannot connect and recreate the deleted storage. */ + @Volatile + var isWiping: Boolean = false + /** * Spark's regtest has no Lightning network, so there a Lightning invoice from another Spark wallet is paid as a * Spark transfer, which lets two dev builds pay each other's invoices. @@ -138,6 +145,7 @@ class SparkService @Inject constructor( suspend fun connect(walletIndex: Int) = mutex.withLock { if (sdk != null) return@withLock + if (isWiping) throw SparkError.WipeInProgress() val network = sparkNetwork() ?: throw SparkError.Unsupported() val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) @@ -162,16 +170,26 @@ class SparkService @Inject constructor( suspend fun disconnect() = mutex.withLock { val current = sdk ?: return@withLock - listenerId?.let { current.removeEventListener(it) } - current.disconnect() - sdk = null - listenerId = null - Logger.info("Disconnected Spark wallet", context = TAG) + try { + listenerId?.let { current.removeEventListener(it) } + current.disconnect() + Logger.info("Disconnected Spark wallet", context = TAG) + } finally { + sdk = null + listenerId = null + } } + /** Deletes Spark's storage and any staged exit data restore, even when disconnecting failed. */ suspend fun wipeStorage(walletIndex: Int) { - disconnect() - File(Env.sparkStoragePath(walletIndex)).deleteRecursively() + val disconnected = runSuspendCatching { disconnect() } + listOf(Env.sparkStoragePath(walletIndex), File(Env.sparkExitRestorePath(walletIndex)).parent) + .filterNotNull() + .forEach { path -> + val dir = File(path) + if (!dir.deleteRecursively() && dir.exists()) throw SparkError.WipeFailed(path) + } + disconnected.getOrThrow() } /** Syncs with Spark now instead of waiting for the SDK's next background sync. */ @@ -269,6 +287,14 @@ class SparkService @Inject constructor( sealed class SparkError(message: String, cause: Throwable? = null) : AppError(message, cause) { class Unsupported : SparkError("Spark is not available on this network or build") class NotConnected : SparkError("Spark wallet is not connected") + class WipeInProgress : SparkError("Spark wallet cannot connect while the wallet is wiped") + class WipeFailed(path: String) : SparkError("Failed to delete Spark storage at '$path'") + + /** What the withdrawal leaves after its fee is below the on-chain dust limit. */ + class WithdrawalTooSmall : SparkError("Spark balance is too small to withdraw after its fee") + + /** The withdrawal fee rose above the fee the user confirmed. */ + class WithdrawalFeeChanged : SparkError("Spark withdrawal fee changed since it was confirmed") /** * Spark refused a Lightning payment before anything left the wallet: it was not connected, could not prepare the diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 743cdc390a..fedb717780 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -43,6 +43,7 @@ import to.bitkit.ext.filterOpen import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.safe import to.bitkit.ui.components.AmountSlider +import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Caption13Up import to.bitkit.ui.components.ConnectionIssuesView @@ -98,6 +99,8 @@ fun SavingsConfirmScreen( val swapState by transfer.savingsSwapState.collectAsStateWithLifecycle() val sparkFeeSats by transfer.sparkWithdrawFeeSats.collectAsStateWithLifecycle() + val isSparkFeePricing by transfer.isSparkFeePricing.collectAsStateWithLifecycle() + val isSparkTooSmall by transfer.isSparkWithdrawTooSmall.collectAsStateWithLifecycle() // Pull the latest node balances so a just-received payment is reflected in the amounts below. LaunchedEffect(Unit) { @@ -119,6 +122,10 @@ fun SavingsConfirmScreen( fallbackAmount = channelsAmount, sparkAmount = sparkAmount, sparkFeeSats = sparkFeeSats.takeIf { withdrawsSpark }, + // Spark's part moves only at the fee shown, so nothing is confirmed before it is priced. + isSparkFeePricing = withdrawsSpark && isSparkFeePricing, + isSparkUnpriced = withdrawsSpark && sparkFeeSats == null, + isSparkTooSmall = withdrawsSpark && isSparkTooSmall, isSwapEnabled = swapState.isSwapEnabled, quote = swapState.quote, isQuoteLoading = swapState.isLoading, @@ -158,6 +165,9 @@ private fun SavingsConfirmContent( fallbackAmount: ULong, sparkAmount: ULong, sparkFeeSats: ULong?, + isSparkFeePricing: Boolean, + isSparkUnpriced: Boolean, + isSparkTooSmall: Boolean, isSwapEnabled: Boolean, quote: SavingsSwapQuote?, isQuoteLoading: Boolean, @@ -267,6 +277,20 @@ private fun SavingsConfirmContent( } } + if (isSparkUnpriced && !isSparkFeePricing) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource( + if (isSparkTooSmall) { + R.string.lightning__savings_confirm__amount_too_low + } else { + R.string.lightning__savings_spark_failed + } + ), + color = Colors.Red, + ) + } + if (hasMultiple) { VerticalSpacer(24.dp) if (hasSelected) { @@ -319,7 +343,8 @@ private fun SavingsConfirmContent( var isLoading by remember { mutableStateOf(false) } SwipeToConfirm( text = stringResource(R.string.lightning__transfer__swipe), - loading = isLoading || isPricingSwap, + loading = isLoading || isPricingSwap || isSparkFeePricing, + enabled = !isSparkUnpriced, color = Colors.Brand, onConfirm = { scope.launch { @@ -334,6 +359,7 @@ private fun SavingsConfirmContent( // Fallback: drain a whole channel on-chain by closing it instead of swapping. TertiaryButton( text = stringResource(R.string.lightning__savings_confirm__close_instead), + enabled = !isSparkUnpriced, onClick = onCloseConfirm, ) } @@ -350,6 +376,9 @@ private fun SavingsConfirmScreenPreview() { fallbackAmount = 50_123u, sparkAmount = 12_000u, sparkFeeSats = 1_470u, + isSparkFeePricing = false, + isSparkUnpriced = false, + isSparkTooSmall = false, isSwapEnabled = true, quote = SavingsSwapQuote( amountSat = 50_123u, 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 a639272fc7..bd911461fd 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 @@ -164,11 +164,7 @@ class SparkFundingViewModel @Inject constructor( description = context.getString(R.string.lightning__spending_amount__error_balance__description), ) - quote.amountSats <= quote.instantFeeSats -> toast( - title = R.string.lightning__spending_amount__error_min__title, - description = context.getString(R.string.lightning__spending_amount__error_min__description) - .replace("{amount}", quote.instantFeeSats.formatToModernDisplay()), - ) + quote.amountSats <= quote.instantFeeSats -> toastBelowClaimFee(quote) else -> { showQuote(quote) @@ -178,6 +174,12 @@ class SparkFundingViewModel @Inject constructor( } } + private fun toastBelowClaimFee(quote: Quote) = toast( + title = R.string.lightning__spending_amount__error_min__title, + description = context.getString(R.string.lightning__spending_amount__error_min__description) + .replace("{amount}", quote.instantFeeSats.formatToModernDisplay()), + ) + /** Re-prices the confirm screen, so it never shows a stale quote. */ fun onConfirmAppear() = requote() @@ -225,6 +227,12 @@ class SparkFundingViewModel @Inject constructor( _uiState.update { it.copy(isSending = false) } return@launch } + if (quote.amountSats <= quote.instantFeeSats) { + Logger.info("Refused transfer that no longer covers its claim fee", context = TAG) + toastBelowClaimFee(quote) + _uiState.update { it.copy(isSending = false) } + return@launch + } val totalRise = quote.totalSats - shownQuote.totalSats val spendingDrop = shownQuote.toSpendingSats(shown.speed) - quote.toSpendingSats(shown.speed) if (totalRise > 0 || spendingDrop > 0) { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9534f44ed3..5e885e5a3e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7441,18 +7441,8 @@ class AppViewModel @Inject constructor( return } - val buffer = 2uL - val amountToEstimate = maxSendLightning.safe() - buffer.safe() - - val feeResult = lightningRepo.estimateRoutingFeesForAmount( - bolt11 = bolt11, - amountSats = amountToEstimate - ) - - feeResult.onSuccess { fee -> - _sendUiState.update { - it.copy(estimatedRoutingFee = fee + buffer) - } + lightningRepo.estimateMaxSendFee(bolt11, maxSendLightning).onSuccess { fee -> + _sendUiState.update { it.copy(estimatedRoutingFee = fee) } }.onFailure { e -> Logger.error("Failed to estimate routing fee for max amount", e, context = TAG) _sendUiState.update { it.copy(estimatedRoutingFee = 0uL) } diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index b11f8cc82c..769dcd8d1a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -40,6 +40,7 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.services.BoltzService +import to.bitkit.services.SparkError import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.Logger import javax.inject.Inject @@ -72,7 +73,14 @@ class TransferViewModel @Inject constructor( private val _sparkWithdrawFeeSats = MutableStateFlow(null) val sparkWithdrawFeeSats = _sparkWithdrawFeeSats.asStateFlow() + private val _isSparkFeePricing = MutableStateFlow(false) + val isSparkFeePricing = _isSparkFeePricing.asStateFlow() + + private val _isSparkWithdrawTooSmall = MutableStateFlow(false) + val isSparkWithdrawTooSmall = _isSparkWithdrawTooSmall.asStateFlow() + private var sparkFeeJob: Job? = null + private var sparkWithdrawJob: Job? = null private var sparkFeeBalanceSats: ULong? = null private var sparkAddress: String? = null @@ -310,15 +318,26 @@ class TransferViewModel @Inject constructor( sparkFeeJob?.cancel() sparkFeeBalanceSats = balanceSats _sparkWithdrawFeeSats.update { null } - sparkFeeJob = viewModelScope.launch { - val address = sparkWithdrawAddress() ?: return@launch - val result = withTimeoutOrNull(SWAP_QUOTE_TIMEOUT) { sparkRepo.estimateWithdrawAllFeeSats(address) } - if (result == null) Logger.warn("Timed out estimating Spark withdrawal fee", context = TAG) + _isSparkWithdrawTooSmall.update { false } + _isSparkFeePricing.update { true } + val job = viewModelScope.launch { + val address = sparkWithdrawAddress() + val result = address?.let { + withTimeoutOrNull(SWAP_QUOTE_TIMEOUT) { sparkRepo.estimateWithdrawAllFeeSats(it) } + } + if (address != null && result == null) { + Logger.warn("Timed out estimating Spark withdrawal fee", context = TAG) + } result ?.onSuccess { fee -> _sparkWithdrawFeeSats.update { fee } } - ?.onFailure { Logger.warn("Failed to estimate Spark withdrawal fee", it, context = TAG) } + ?.onFailure { + if (it is SparkError.WithdrawalTooSmall) _isSparkWithdrawTooSmall.update { true } + Logger.warn("Failed to estimate Spark withdrawal fee", it, context = TAG) + } if (result?.isSuccess != true) sparkFeeBalanceSats = null } + sparkFeeJob = job + job.invokeOnCompletion { if (sparkFeeJob === job) _isSparkFeePricing.update { false } } } /** One Savings address for Spark's withdrawal, priced on the confirm screen and then paid to. */ @@ -344,6 +363,7 @@ class TransferViewModel @Inject constructor( // Drop any outcome from an earlier attempt so the progress screen cannot act on it. _savingsSwapResult.update { null } _isSparkWithdrawFailed.update { false } + sparkWithdrawJob = null _savingsSelection.update { SavingsSelection() } channelsToClose = channels withdrawsSpark = withdrawSpark @@ -366,15 +386,22 @@ class TransferViewModel @Inject constructor( } private suspend fun withdrawSparkToSavings() { + // Once per confirmed transfer, in viewModelScope, so leaving the progress screen cannot cut it short. + val job = sparkWithdrawJob ?: viewModelScope.launch { runSparkWithdrawal() }.also { sparkWithdrawJob = it } + job.join() + } + + private suspend fun runSparkWithdrawal() { sparkFeeJob?.join() - val balance = sparkRepo.state.value.balanceSats - if (balance == 0uL) return + if (sparkRepo.state.value.balanceSats == 0uL) return val address = sparkWithdrawAddress() - if (address == null) { + val confirmedFeeSats = _sparkWithdrawFeeSats.value + if (address == null || confirmedFeeSats == null) { + Logger.warn("Skipped Spark withdrawal without an address or a priced fee", context = TAG) _isSparkWithdrawFailed.update { true } return } - sparkRepo.withdrawAll(address) + sparkRepo.withdrawAll(address, confirmedFeeSats) .onSuccess { sparkAddress = null sparkFeeBalanceSats = null diff --git a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt index 2fe3a8c264..1ac125eb12 100644 --- a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt @@ -1,6 +1,7 @@ package to.bitkit.ext import android.content.Context +import breez_sdk_spark.SdkException import org.junit.Test import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.PaymentFailureReason @@ -8,6 +9,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.R import to.bitkit.models.SendFailureDetails +import to.bitkit.services.SparkError import to.bitkit.utils.LdkError import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -47,6 +49,17 @@ class PaymentFailureReasonExtTest { ) } + @Test + fun `spark failures show the existing payment failure copy`() { + val message = "Generic payment failed" + whenever(context.getString(R.string.wallet__payment_failed_description)).thenReturn(message) + + val refused = SparkError.SendRefused("Spark could not prepare the payment") + + assertEquals(message, refused.toSendFailureMessage(context)) + assertEquals(message, SdkException.Generic("insufficient funds").toSendFailureMessage(context)) + } + @Test fun `payment failure reason compact failure types use lower camel case`() { assertEquals("routeNotFound", PaymentFailureReason.ROUTE_NOT_FOUND.toCompactFailureType()) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index b2d8b7d33c..0c7c1bf375 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -103,6 +103,7 @@ import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertNotEquals import kotlin.test.assertNull import kotlin.test.assertTrue @@ -223,6 +224,8 @@ class BackupRepoTest : BaseUnitTest() { whenever { vssBackupClient.listKeys() }.thenReturn(Result.success(emptyList())) whenever { sparkRepo.exitBackup() }.thenReturn(Result.success(null)) whenever { sparkRepo.restoreExitBackup(any(), any()) }.thenReturn(Result.success(Unit)) + whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenReturn(Result.success(Unit)) + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(true) whenever(sparkRepo.exitStateChanged).thenReturn(MutableSharedFlow()) whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) @@ -285,13 +288,15 @@ class BackupRepoTest : BaseUnitTest() { val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} stubBackupObservers() - whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState(isSupported = true, isReady = true))) + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) try { sut.startObservingBackups() runCurrent() - advanceTimeBy(6_000) + advanceTimeBy(61_000) runCurrent() verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) @@ -301,12 +306,65 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `spark exit backup uploads nothing while Spark is not connected`() = test { + fun `spark exit backup defers, without uploading, until Spark has connected and synced`() = test { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + + assertIs(sut.triggerBackup(BackupCategory.SPARK_EXIT).exceptionOrNull()) + + verify(vssBackupClient, never()).getObject(BackupCategory.SPARK_EXIT.name) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `first spark exit backup merges the stored one into Spark before replacing it`() = test { + val stored = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "stored") + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(stored).toByteArray(), + version = 1, + ) + ) + ) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "merged")) + ) + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(stored) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `spark exit backup never replaces a stored one it could not read`() = test { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.failure(AppError("unreachable"))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + + verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } + @Test + fun `a failed spark exit restore is reported as an incomplete restore`() = test { + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.failure(AppError("unreachable"))) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertTrue(BackupCategory.SPARK_EXIT in failed) + } + @Test fun `wallet backup waits for submission and includes the latest pending state`() = test { val statuses = MutableStateFlow( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index eb72b5c082..31a40a1354 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -25,18 +25,24 @@ import breez_sdk_spark.SparkHtlcDetails import breez_sdk_spark.SparkHtlcStatus import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.OnchainActivity +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import org.lightningdevkit.ldknode.Event import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -153,6 +159,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { activityRepo.getOnchainActivityByTxId(eq("withdrawal"), any()) }.thenReturn(arrival) whenever { activityRepo.updateActivity(any(), any(), any()) }.thenReturn(Result.success(Unit)) whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) val sent = sentPayment(fees = 1_470).copy( @@ -163,7 +170,7 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut() assertFalse(sut.markWithdrawalAsTransfer("withdrawal")) - sut.withdrawAll(ADDRESS).getOrThrow() + sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).getOrThrow() assertTrue(sut.markWithdrawalAsTransfer("withdrawal")) assertFalse(sut.markWithdrawalAsTransfer("other")) @@ -384,6 +391,7 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(SparkLightningSend.Unavailable, sut.lightningSend("hash")) whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.syncWallet() }.thenAnswer { throw SdkException.Generic("offline") } val failed = sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED) sut.start(0).getOrThrow() whenever { sparkService.listPayments() }.thenReturn(listOf(failed, sentPayment(fees = 1))) @@ -443,13 +451,14 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a spark withdrawal pays the quote its fee estimate priced while it holds`() = test { whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) val held = withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(held) whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut() assertEquals(500uL, sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow()) - sut.withdrawAll(ADDRESS).getOrThrow() + sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).getOrThrow() verify(sparkService, times(1)).prepareSend(any(), anyOrNull(), anyOrNull()) verify(sparkService).send(held) @@ -458,6 +467,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a spark withdrawal asks again once its quote expired or the address changed`() = test { whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) val expiring = withdrawal(expiresAt = now.epochSeconds.toULong() + 10uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(expiring) val sut = createSut() @@ -487,15 +497,125 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a failure inside the spark send stays uncertain`() = test { + fun `a failure inside the spark send is pending, not failed`() = test { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } - val error = createSut().payInvoice("lnbc1", 100uL).exceptionOrNull() + val sut = createSut() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + val error = sut.payInvoice("lnbc1", 100uL).exceptionOrNull() + advanceUntilIdle() + + assertEquals("hash", assertIs(error).paymentHash) + // Spark synced and holds no such send, so nothing left and the pending send ends as failed. + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a max send keeps the routing fee spark quotes for its whole balance`() = test { + whenever { sparkService.getInfo() }.thenReturn(info(100_000uL)) + val details = mock { on { paymentHash } doReturn "hash" } + val wholeBalance = PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 400uL), + amount = BigInteger.valueOf(99_600), + tokenIdentifier = null, + conversionEstimate = null, + feePolicy = FeePolicy.FEES_INCLUDED, + ) + whenever { sparkService.prepareSend("lnbc1", 100_000uL, FeePolicy.FEES_INCLUDED) }.thenReturn(wholeBalance) + + val reserve = createSut().maxSendReserveSats("lnbc1").getOrThrow() + + // The service fee alone leaves 99_750 sendable; routing on top caps the send at 99_600. + assertEquals(99_600uL, SparkFees.sendableSats(100_000uL) - reserve) + } + + @Test + fun `an invoice is not sent again while its send is in flight`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sending = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { sending.await() } + val sut = createSut() + + val first = async { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + val second = sut.payInvoice("lnbc1", 100uL) + sending.complete(sentPayment(fees = 0)) + + assertIs(second.exceptionOrNull()) + assertEquals("hash", first.await().getOrThrow()) + verify(sparkService, times(1)).send(any()) + } + + @Test + fun `an invoice spark already paid or is paying is not sent again`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sut = createSut() + sut.start(0).getOrThrow() - assertIs(error) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 0))) + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING))) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any()) + } + + @Test + fun `a withdrawal whose fee rose above the confirmed one or leaves dust never leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + val sut = createSut() + + assertIs(sut.withdrawAll(ADDRESS, confirmedFeeSats = 499uL).exceptionOrNull()) + + whenever { sparkService.getInfo() }.thenReturn(info(1_000uL)) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL, amountSats = 1_000)) + assertIs(sut.estimateWithdrawAllFeeSats(ADDRESS).exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `exit backup waits for spark's first sync`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.exportExitState() }.thenReturn("state") + whenever { sparkService.syncWallet() }.thenAnswer { throw SdkException.Generic("offline") } + val sut = createSut() + sut.start(0).getOrThrow() + + assertNull(sut.exitBackup().getOrThrow()) + + sparkEvents.emit(SdkEvent.Synced) + assertEquals("state", sut.exitBackup().getOrThrow()?.exitState) + } + + @Test + fun `wipe fails when spark storage is not deleted and clears what spark held`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(5_000uL)) + val sut = createSut() + sut.start(0).getOrThrow() + sut.onDepositBroadcast("txid", 50_000uL) + whenever { sparkService.wipeStorage(0) }.thenAnswer { throw SdkException.Generic("busy") } + + assertIs(sut.wipe(0).exceptionOrNull()) + + assertEquals(SparkState(isSupported = true), sut.state.value) + assertTrue(sut.depositClaims.value.isEmpty()) } @Test @@ -539,12 +659,12 @@ class SparkRepoTest : BaseUnitTest() { ) } - private fun withdrawal(expiresAt: ULong): PrepareSendPaymentResponse { + private fun withdrawal(expiresAt: ULong, amountSats: Long = 10_000): PrepareSendPaymentResponse { val speed = SendOnchainSpeedFeeQuote(userFeeSat = 300uL, l1BroadcastFeeSat = 200uL) val quote = SendOnchainFeeQuote("quote", expiresAt, speed, speed, speed, isEstimate = false) return PrepareSendPaymentResponse( paymentMethod = SendPaymentMethod.BitcoinAddress(mock(), quote), - amount = BigInteger.valueOf(100), + amount = BigInteger.valueOf(amountSats), tokenIdentifier = null, conversionEstimate = null, feePolicy = FeePolicy.FEES_INCLUDED, diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index cb005cedc8..6d2d37def5 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -5,12 +5,49 @@ import breez_sdk_spark.LeafOptimizationConfig import breez_sdk_spark.Network import breez_sdk_spark.SendPaymentOptions import breez_sdk_spark.TokenOptimizationConfig +import kotlinx.coroutines.test.runTest +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.mockito.kotlin.mock +import org.mockito.kotlin.verifyNoInteractions +import to.bitkit.data.keychain.Keychain +import to.bitkit.env.Env +import java.io.File import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull class SparkServiceTest { + @get:Rule + val tempFolder = TemporaryFolder() + + @Test + fun `connect is refused during a wallet wipe`() = runTest { + val keychain = mock() + val sut = SparkService(keychain).apply { isWiping = true } + + assertIs(runCatching { sut.connect(0) }.exceptionOrNull()) + + assertFalse(sut.isConnected) + verifyNoInteractions(keychain) + } + + @Test + fun `wipe deletes spark storage and a staged exit data restore`() = runTest { + Env.initAppStoragePath(tempFolder.root.absolutePath) + val storage = File(Env.sparkStoragePath(0)).apply { mkdirs() } + File(storage, "db").writeText("old wallet") + val staged = File(Env.sparkExitRestorePath(0)).apply { parentFile?.mkdirs() } + staged.writeText("state") + + SparkService(mock()).wipeStorage(0) + + assertFalse(storage.exists()) + assertFalse(staged.exists()) + } + @Test fun `lightning sends return before completion so callers see the completion event`() { val options = assertIs(SparkService.bolt11SendOptions(prefersSpark = true)) @@ -61,12 +98,13 @@ class SparkServiceTest { ) @Test - fun `config turns off breez data sync and the lightning address server on every network`() { + fun `config turns off breez data sync, the lightning address server and default parsers on every network`() { Network.entries.forEach { network -> val config = SparkService.configure(defaults(network), apiKey = "key") assertNull(config.realTimeSyncServerUrl, "$network") assertNull(config.lnurlDomain, "$network") + assertFalse(config.useDefaultExternalInputParsers, "$network") assertEquals("key", config.apiKey) } } diff --git a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt index e77e84ceb7..05f0b04e0b 100644 --- a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt +++ b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt @@ -2,6 +2,7 @@ package to.bitkit.test import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import to.bitkit.repositories.SparkRepo @@ -11,4 +12,5 @@ import to.bitkit.repositories.SparkState fun idleSparkRepo(): SparkRepo = mock { on { state } doReturn MutableStateFlow(SparkState()) on { nodeEvents } doReturn MutableSharedFlow() + on { wipe(any()) } doReturn Result.success(Unit) } diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index d970738dfa..7721d6463b 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -35,6 +35,7 @@ import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState import to.bitkit.repositories.TransferRepo import to.bitkit.services.BoltzService +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import kotlin.math.roundToLong @@ -74,7 +75,8 @@ class TransferViewModelTest : BaseUnitTest() { whenever(boltzService.isSwapSupported).thenReturn(true) whenever { boltzService.isSwapEnabled() }.thenReturn(true) whenever(sparkRepo.state).thenReturn(sparkState) - whenever { sparkRepo.withdrawAll(any()) }.thenReturn(Result.success(Unit)) + whenever { sparkRepo.withdrawAll(any(), any()) }.thenReturn(Result.success(Unit)) + whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) }.thenReturn(Result.success(SPARK_FEE)) whenever { lightningRepo.newAddress() }.thenReturn(Result.success(CLAIM_ADDRESS)) whenever { lightningRepo.closeChannel(any(), any(), anyOrNull()) }.thenReturn(Result.success(Unit)) @@ -114,12 +116,13 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `transfer to savings with only spark withdraws spark and closes no channel`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) assertFalse(sut.hasChannelsToClose()) assertTrue(sut.closeSelectedChannels().isEmpty()) - verify(sparkRepo).withdrawAll(CLAIM_ADDRESS) + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) verify(lightningRepo, never()).awaitPeerConnected(any()) verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } @@ -130,7 +133,7 @@ class TransferViewModelTest : BaseUnitTest() { sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_B), withdrawSpark = false) assertTrue(sut.closeSelectedChannels().isEmpty()) - verify(sparkRepo, never()).withdrawAll(any()) + verify(sparkRepo, never()).withdrawAll(any(), any()) verify(lightningRepo).closeChannel(CHANNEL_B, false, null) verify(lightningRepo, never()).closeChannel(CHANNEL_A, false, null) } @@ -138,7 +141,8 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `a failed spark withdrawal is reported while the selected channels still close`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) - whenever { sparkRepo.withdrawAll(any()) }.thenReturn(Result.failure(AppError(PAY_ERROR))) + whenever { sparkRepo.withdrawAll(any(), any()) }.thenReturn(Result.failure(AppError(PAY_ERROR))) + sut.loadSparkWithdrawFee(SPARK_SATS) sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = true) assertTrue(sut.closeSelectedChannels().isEmpty()) @@ -153,10 +157,11 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `transfer to savings with channels and spark moves both`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A, CHANNEL_B), withdrawSpark = true) assertTrue(sut.closeSelectedChannels().isEmpty()) - verify(sparkRepo).withdrawAll(CLAIM_ADDRESS) + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) verify(lightningRepo).closeChannel(CHANNEL_A, false, null) verify(lightningRepo).closeChannel(CHANNEL_B, false, null) } @@ -189,10 +194,39 @@ class TransferViewModelTest : BaseUnitTest() { sut.startSavingsSwap() advanceUntilIdle() - verify(sparkRepo, never()).withdrawAll(any()) + verify(sparkRepo, never()).withdrawAll(any(), any()) verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } + @Test + fun `spark is not withdrawn at a fee the user was never shown`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) } + .thenReturn(Result.failure(SparkError.WithdrawalTooSmall())) + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + assertTrue(sut.isSparkWithdrawTooSmall.value) + assertFalse(sut.isSparkFeePricing.value) + + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + sut.closeSelectedChannels() + + assertTrue(sut.isSparkWithdrawFailed.value) + verify(sparkRepo, never()).withdrawAll(any(), any()) + } + + @Test + fun `spark is withdrawn once per confirmed transfer`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + + sut.closeSelectedChannels() + sut.closeSelectedChannels() + + verify(sparkRepo, times(1)).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) + } + @Test fun `loadSparkWithdrawFee prices spark's withdrawal once per balance`() = test { whenever(sparkRepo.estimateWithdrawAllFeeSats(CLAIM_ADDRESS)).thenReturn(Result.success(SPARK_FEE)) From b29e9e5446e6794a4bf5718845781c242652b3c7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 20:30:32 +0100 Subject: [PATCH 005/135] fix: settle spark payments, deposits and fundings --- .../repositories/PaykitAllowanceExecutor.kt | 8 ++- .../repositories/PaykitPaymentProofRepo.kt | 7 +- .../java/to/bitkit/repositories/SparkRepo.kt | 71 +++++++++++++++---- app/src/main/java/to/bitkit/ui/ContentView.kt | 1 + .../screens/transfer/SparkFundingViewModel.kt | 20 +++++- .../screens/transfer/SpendingConfirmScreen.kt | 8 ++- .../transfer/hardware/SpendingHwSignScreen.kt | 1 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 17 +++++ .../repositories/PaykitAllowancePayerTest.kt | 18 +++++ .../PaykitPaymentProofRepoTest.kt | 34 +++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 55 ++++++++++++++ .../transfer/SparkFundingViewModelTest.kt | 35 +++++++++ 12 files changed, 254 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 8de62100b9..2e1123c70d 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -146,15 +146,17 @@ class PaykitAllowancePayer @Inject constructor( * not running). PENDING while Spark cannot list its payments, so a Spark send is never read as never sent. */ suspend fun lightningPaymentStatus(paymentHash: String): PaymentStatus? { - runSuspendCatching { lightningRepo.listPaymentsOrNull() } + val node = runSuspendCatching { lightningRepo.listPaymentsOrNull() } .getOrNull() ?.firstOrNull { it.direction == PaymentDirection.OUTBOUND && it.id.equals(paymentHash, ignoreCase = true) } - ?.let { return it.status } + ?.status + // A Spark retry of an invoice the node failed shares its hash and decides the payment. + if (node != null && node != PaymentStatus.FAILED) return node val spark = runSuspendCatching { lightningRepo.sparkLightningSend(paymentHash) } .getOrDefault(SparkLightningSend.Unavailable) return when (spark) { SparkLightningSend.Unavailable -> PaymentStatus.PENDING - SparkLightningSend.NotFound -> null + SparkLightningSend.NotFound -> node is SparkLightningSend.Found -> when (spark.status) { SparkPaymentStatus.COMPLETED -> PaymentStatus.SUCCEEDED SparkPaymentStatus.PENDING -> PaymentStatus.PENDING diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 6036008521..c759ca37f7 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -1304,7 +1304,12 @@ class PaykitPaymentProofRepo @Inject constructor( } when (payment.status) { PaymentStatus.PENDING -> Unit - PaymentStatus.FAILED -> removeLightningProofsLocked(paymentHash) + // A Spark retry of an invoice the node failed shares its hash and decides the payment. + PaymentStatus.FAILED -> when (lightningRepo.sparkLightningSend(paymentHash)) { + is SparkLightningSend.Found -> reconcileSparkLightningProof(proof, paymentHash) + SparkLightningSend.Unavailable -> Unit + SparkLightningSend.NotFound -> removeLightningProofsLocked(paymentHash) + } PaymentStatus.SUCCEEDED -> completeLightningProofLocked( proof, paymentHash, diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 4fe97e6afa..7f49f35f2f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -35,6 +35,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId @@ -77,6 +78,7 @@ class SparkRepo @Inject constructor( private val activityRepo: Provider, private val cacheStore: CacheStore, private val contactResolver: Provider, + private val pendingPaymentRepo: PendingPaymentRepo, private val clock: Clock, ) { companion object { @@ -91,6 +93,14 @@ class SparkRepo @Inject constructor( private val SEND_STATUS_PRIORITY = listOf(PaymentStatus.COMPLETED, PaymentStatus.PENDING, PaymentStatus.FAILED) + /** How long a send's settlement waits for the send screen to track it as pending before it reports. */ + private val PENDING_TRACK_WAIT = 10.seconds + + /** Tries to learn the outcome of a send whose result was lost while Spark cannot list its payments. */ + private const val SETTLE_ATTEMPTS = 10 + + private val SETTLE_RETRY_INTERVAL = 30.seconds + /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL } @@ -275,16 +285,30 @@ class SparkRepo @Inject constructor( private fun settleUncertainSend(paymentHash: String) { scope.launch { - runSuspendCatching { sparkService.syncWallet() } - .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } - .onSuccess { _state.update { it.copy(hasSynced = true) } } - val event = when (lightningSend(paymentHash)) { - SparkLightningSend.NotFound -> - Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR) - is SparkLightningSend.Found -> settledSendEvent(paymentHash) - SparkLightningSend.Unavailable -> null + // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. + withTimeoutOrNull(PENDING_TRACK_WAIT) { + pendingPaymentRepo.state.first { paymentHash in it.pendingPayments } + } + repeat(SETTLE_ATTEMPTS) { + runSuspendCatching { sparkService.syncWallet() } + .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } + .onSuccess { _state.update { it.copy(hasSynced = true) } } + when (val send = lightningSend(paymentHash)) { + SparkLightningSend.NotFound -> { + val reason = PaymentFailureReason.UNEXPECTED_ERROR + _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, reason)) + return@launch + } + // A pending send ends with its own payment event. + is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@launch + is SparkLightningSend.Found -> { + settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + return@launch + } + SparkLightningSend.Unavailable -> delay(SETTLE_RETRY_INTERVAL) + } } - event?.let { _nodeEvents.emit(it) } + Logger.warn("Stopped settling Spark send '$paymentHash'", context = TAG) } } @@ -406,7 +430,10 @@ class SparkRepo @Inject constructor( val payment = sparkService.send(prepared.response) preparedWithdrawal = null (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } - refresh() + Unit + }.onSuccess { + runSuspendCatching { refresh() } + .onFailure { Logger.warn("Failed to refresh Spark after its withdrawal", it, context = TAG) } }.onFailure { Logger.error("Failed to withdraw from Spark", it, context = TAG) } @@ -503,14 +530,14 @@ class SparkRepo @Inject constructor( return@runSuspendCatching } File(Env.sparkExitRestorePath(walletIndex)).writeText(backup.exitState) - if (sparkService.isConnected) importRestoredExitState(walletIndex) + if (sparkService.isConnected) importRestoredExitState(walletIndex).getOrThrow() } } - private suspend fun importRestoredExitState(walletIndex: Int) { + private suspend fun importRestoredExitState(walletIndex: Int): Result { val file = File(Env.sparkExitRestorePath(walletIndex)) - if (!file.exists()) return - runSuspendCatching { sparkService.importExitState(file.readText()) } + if (!file.exists()) return Result.success(Unit) + return runSuspendCatching { sparkService.importExitState(file.readText()) } .onSuccess { file.delete() Logger.info( @@ -520,6 +547,7 @@ class SparkRepo @Inject constructor( ) } .onFailure { Logger.error("Failed to import Spark exit data", it, context = TAG) } + .map {} } suspend fun refreshState(): Result = withContext(bgDispatcher) { @@ -556,10 +584,21 @@ class SparkRepo @Inject constructor( withdrawals = payments.toWithdrawals(), ).withBroadcastDeposits() } + markClaimedDeposits(claimed) payments.filter { it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0 }.forEach { recordActivity(it) } markTransfers(payments) } + private fun markClaimedDeposits(claimed: List) { + val claimedTxids = claimed.map { it.txid.lowercase() }.toSet() + _depositClaims.update { claims -> + claims.mapValues { (txid, claim) -> + if (txid.lowercase() in claimedTxids) SparkDepositClaim.Claimed else claim + } + } + claimJobs.keys.filter { it.lowercase() in claimedTxids }.forEach { claimJobs.remove(it)?.cancel() } + } + private fun List.toWithdrawals() = filter { it.status != PaymentStatus.FAILED } .mapNotNull { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@mapNotNull null @@ -685,7 +724,9 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { - refresh() + // The event carries its outcome, so a failed balance read never holds back its settlement. + runSuspendCatching { refresh() } + .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 74149b5d4c..ee82fb0e95 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -1184,6 +1184,7 @@ private fun RootNavHost( onBackClick = { navController.popBackStack() }, onLearnMoreClick = { navController.navigateTo(Routes.TransferLearnMore) }, onSent = { navController.navigateToSettingUp() }, + onFundingPending = { attempt -> appViewModel.showPendingTransfer(attempt) }, ) } composableWithDefaultTransitions { 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 bd911461fd..5a662be52c 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 @@ -32,6 +32,8 @@ import to.bitkit.models.safe import to.bitkit.repositories.CurrencyRepo import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.OnchainSendAttempt +import to.bitkit.repositories.OnchainSendBlockedError import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim @@ -293,7 +295,11 @@ class SparkFundingViewModel @Inject constructor( isTransfer = true, isMaxAmount = state.isMax, ).getOrThrow() - check(outcome is OnchainSendOutcome.Accepted) { "Spark funding was not accepted: '$outcome'" } + if (outcome !is OnchainSendOutcome.Accepted) { + Logger.warn("Spark funding was not accepted: '$outcome'", context = TAG) + if (showRetainedFunding()) return@runSuspendCatching + error("Spark funding was not accepted: '$outcome'") + } withContext(NonCancellable) { runSuspendCatching { lightningRepo.completeAcceptedTransferFollowup(orderId = null, txid = outcome.txid) @@ -308,6 +314,7 @@ class SparkFundingViewModel @Inject constructor( _effects.emit(SideEffect.Sent) }.onFailure { Logger.error("Failed to fund Spark", it, context = TAG) + if (it is OnchainSendBlockedError && showRetainedFunding()) return@onFailure toast( title = R.string.lightning__close_error, description = context.getString(R.string.wallet__send_error_create_tx), @@ -316,6 +323,14 @@ class SparkFundingViewModel @Inject constructor( _uiState.update { it.copy(isSending = false) } } + // A signed funding that was not accepted is kept; Payment Pending shows it and retries it at a new fee. + private suspend fun showRetainedFunding(): Boolean { + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() + if (attempt == null || !attempt.isTransfer || !attempt.blocksNextSend) return false + _effects.emit(SideEffect.FundingPending(attempt)) + return true + } + fun onPayRepriced() { val txid = _uiState.value.txid ?: return sparkRepo.payRepricedClaim(txid) @@ -456,6 +471,9 @@ interface SparkFundingContract { data object AmountReady : SideEffect data object Sent : SideEffect + /** The funding transaction is signed but not accepted; its recovery opens on Payment Pending. */ + data class FundingPending(val attempt: OnchainSendAttempt) : SideEffect + /** Priced and checked; the hardware wallet signs [request] next. */ data class SignHw(val request: HwSendRequest) : SideEffect } 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 a5d2e52b50..546b4d1bf8 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,7 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R +import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BodySSB @@ -76,6 +77,7 @@ fun SpendingConfirmScreen( onBackClick: () -> Unit = {}, onLearnMoreClick: () -> Unit = {}, onSent: () -> Unit = {}, + onFundingPending: (OnchainSendAttempt) -> Unit = {}, ) { val state by viewModel.uiState.collectAsStateWithLifecycle() @@ -87,7 +89,11 @@ fun SpendingConfirmScreen( LaunchedEffect(viewModel, onSent) { viewModel.effects.collect { - if (it == SideEffect.Sent) onSent() + when (it) { + SideEffect.Sent -> onSent() + is SideEffect.FundingPending -> onFundingPending(it.attempt) + else -> Unit + } } } 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 d8702be5b4..0cce2e0f49 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 @@ -87,6 +87,7 @@ fun SpendingHwSignScreen( SideEffect.Sent -> onSent() SideEffect.AmountReady -> Unit + is SideEffect.FundingPending -> Unit } } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 5e885e5a3e..1d0107e432 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6663,6 +6663,23 @@ class AppViewModel @Inject constructor( } } + /** Opens Payment Pending for a transfer whose signed funding was not accepted, so it can be retried. */ + fun showPendingTransfer(attempt: OnchainSendAttempt) { + if (!attempt.isTransfer || !attempt.blocksNextSend) return + showSheet( + Sheet.Send( + SendRoute.Pending( + paymentHash = attempt.txid.orEmpty(), + amount = attempt.amountSats.toLong(), + observeResolution = false, + isOnchain = true, + walletId = attempt.walletId, + refusalReason = attempt.refusalReason, + ) + ) + ) + } + private fun showUnresolvedOnchainSend( txid: String?, amount: ULong, diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt index cb79fdac3d..b65fc9014a 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowancePayerTest.kt @@ -3,8 +3,11 @@ package to.bitkit.repositories import com.synonym.paykit.PaymentOutcome import org.junit.Before import org.junit.Test +import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentStatus import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.models.WalletScope @@ -46,6 +49,21 @@ class PaykitAllowancePayerTest : BaseUnitTest() { } } + @Test + fun `a spark retry of an invoice the node failed decides its status`() = test { + val failed = mock { + on { direction } doReturn PaymentDirection.OUTBOUND + on { id } doReturn paymentHash + on { status } doReturn PaymentStatus.FAILED + } + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(failed)) + assertEquals(PaymentStatus.FAILED, sut.lightningPaymentStatus(paymentHash)) + + whenever(lightningRepo.sparkLightningSend(paymentHash)) + .thenReturn(SparkLightningSend.Found(SparkPaymentStatus.COMPLETED, "preimage")) + assertEquals(PaymentStatus.SUCCEEDED, sut.lightningPaymentStatus(paymentHash)) + } + @Test fun `a lightning send neither rail knows is one the wallet never made`() = test { assertTrue(sut.canListLightningPayments()) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 9001d10569..92741be3cd 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -848,6 +848,40 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(storedProofs.isEmpty()) } + @Test + fun `a spark retry decides a lightning proof the node failed`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.Bolt11.rawValue) + val failed = mock { + on { id } doReturn PAYMENT_HASH + on { direction } doReturn PaymentDirection.OUTBOUND + on { status } doReturn PaymentStatus.FAILED + } + whenever(lightningRepo.getPayments()).thenReturn(Result.success(listOf(failed))) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever( + paykitSdkService.submitPaymentProof(any(), any(), any(), any(), any(), isNull(), isNull(), isNull(), any()) + ).thenReturn(record) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + + val sparkPending = SparkLightningSend.Found(SparkPaymentStatus.PENDING, null) + for (pending in listOf(SparkLightningSend.Unavailable, sparkPending)) { + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)).thenReturn(pending) + paymentProofRepo().reconcile() + assertEquals(PAYMENT_HASH, storedProofs.single().paymentIdentifier) + } + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)) + .thenReturn(SparkLightningSend.Found(SparkPaymentStatus.COMPLETED, PREIMAGE)) + paymentProofRepo().reconcile() + + verify(paykitSdkService).submitPaymentProof( + any(), any(), any(), any(), any(), isNull(), isNull(), isNull(), any(), + ) + assertTrue(storedProofs.isEmpty()) + } + @Test fun `lightning proof is removed when spark failed the send`() = test { whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 31a40a1354..5309c629bb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -84,6 +84,7 @@ class SparkRepoTest : BaseUnitTest() { private val cacheData = MutableStateFlow(AppCacheData()) private val cacheStore = mock { on { data } doReturn cacheData } private val contactResolver = mock() + private val pendingPaymentRepo = PendingPaymentRepo() private val now = Instant.fromEpochSeconds(1_800_000_000) private val clock = object : Clock { override fun now() = this@SparkRepoTest.now @@ -95,6 +96,7 @@ class SparkRepoTest : BaseUnitTest() { activityRepo = { activityRepo }, cacheStore = cacheStore, contactResolver = { contactResolver }, + pendingPaymentRepo = pendingPaymentRepo, clock = clock, ) @@ -333,6 +335,59 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).claimDeposit(any(), any(), any()) } + @Test + fun `a later deposit reads as claimed once spark claims it`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + sut.followDepositClaim("txid", SparkClaimSpeed.Later, ceilingSats = 500uL) + + whenever { sparkService.listPayments() }.thenReturn(listOf(depositPayment())) + sparkEvents.emit(SdkEvent.ClaimedDeposits(emptyList())) + + assertEquals(SparkDepositClaim.Claimed, sut.depositClaims.value["txid"]) + } + + @Test + fun `a payment event settles even when the balance read fails`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + whenever { sparkService.getInfo() }.thenAnswer { throw SdkException.Generic("offline") } + + sparkEvents.emit(SdkEvent.PaymentSucceeded(sentPayment(fees = 1))) + runCurrent() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a restore whose exit data spark rejects fails and keeps it staged`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.Generic("bad state") } + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertTrue(result.isFailure) + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `a sent withdrawal succeeds even when the refresh after it fails`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 500)) + whenever { sparkService.listPayments() }.thenAnswer { throw SdkException.Generic("offline") } + + assertTrue(createSut().withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isSuccess) + } + @Test fun `instant says Spark has not seen the deposit when it is never listed`() = test { val sut = createSut() 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 bf92b5c5d0..713db8c2bf 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 @@ -21,11 +21,14 @@ import to.bitkit.R import to.bitkit.models.BalanceState import to.bitkit.models.Toast import to.bitkit.models.TransactionSpeed +import to.bitkit.models.WalletScope import to.bitkit.repositories.CurrencyRepo import to.bitkit.repositories.CurrencyState import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.OnchainSendAttempt +import to.bitkit.repositories.OnchainSendEvidence import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim @@ -191,6 +194,38 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.claim == SparkDepositClaim.Later) } + @Test + fun `a funding that was signed but not accepted opens its recovery instead of an error`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) + val retained = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "attempt", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(retained) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + val effects = mutableListOf() + backgroundScope.launch { sut.effects.collect { effects += it } } + + val toasts = collectToasts { sut.onConfirm() } + + assertTrue(toasts.isEmpty()) + assertEquals(SideEffect.FundingPending(retained), effects.last()) + verify(sparkRepo, never()).onDepositBroadcast(any(), any()) + } + @Test fun `hardware transfer prices from the device and hands signing a transfer request`() = test { whenever { hwWalletRepo.maxSpendableFunding("trezor", "bcrt1qspark", 5uL) }.thenReturn(Result.success(80_000uL)) From 07440f690cc3e6da611b42bf2e2e7707e202946e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 21:12:15 +0100 Subject: [PATCH 006/135] fix: settle each lightning send from its own rail --- .../to/bitkit/repositories/LightningRepo.kt | 33 ++++++++++-- .../java/to/bitkit/services/CoreService.kt | 6 +++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 + .../bitkit/repositories/LightningRepoTest.kt | 51 +++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 22 ++++++++ 5 files changed, 110 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index bf146c5f87..5e42ac535b 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -164,6 +164,9 @@ class LightningRepo @Inject constructor( @Volatile private var isWiping = false + /** The rail each Lightning send last went out on, by payment hash, so a retry settles only from its own rail. */ + private val sendRails = ConcurrentHashMap() + @Volatile private var lastKnownNodeId: String? = null @@ -624,6 +627,11 @@ class LightningRepo @Inject constructor( } private suspend fun onSparkEvent(event: Event) { + // An earlier Spark attempt's failure never fails a retry the node is paying. + if (event is Event.PaymentFailed && event.paymentHash?.let { isLdkSend(it) } == true) { + Logger.info("Skipped Spark failure of '${event.paymentHash}', its retry went over a channel", context = TAG) + return + } val settledReceiveInvoice = (event as? Event.PaymentReceived)?.let { invalidateSettledReceiveInvoice(it) } _eventHandlers.toList().forEach { runCatching { it.invoke(event) } @@ -1473,6 +1481,10 @@ class LightningRepo @Inject constructor( if (!onBeforeSend()) return Result.failure(PaymentAbortedBeforeSend()) runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) + .onSuccess { recordSendRail(it, LightningRail.Spark) } + .onFailure { + if (it is PaymentPendingException) recordSendRail(it.paymentHash, LightningRail.Spark) + } } return payInvoiceWithLdk(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) } @@ -1489,11 +1501,20 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() - runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) }.also { - syncState() - } + runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } + .onSuccess { recordSendRail(it, LightningRail.Ldk) } + .also { syncState() } + } + + private fun recordSendRail(paymentHash: String, rail: LightningRail) { + sendRails[paymentHash.lowercase()] = rail } + /** Whether the latest send of [paymentHash] went out on Spark, so the node's record of it is an older attempt. */ + fun isSparkSend(paymentHash: String): Boolean = sendRails[paymentHash.lowercase()] == LightningRail.Spark + + private fun isLdkSend(paymentHash: String): Boolean = sendRails[paymentHash.lowercase()] == LightningRail.Ldk + /** Confirmations of an on-chain transaction this wallet sent or received, 0 while unconfirmed. */ suspend fun onchainConfirmations(txid: String): UInt? = withContext(bgDispatcher) { val kind = lightningService.listPayments() @@ -2354,7 +2375,8 @@ class LightningRepo @Inject constructor( } /** The completion event of a Spark send that settled before its caller started watching for it. */ - suspend fun settledSparkSendEvent(paymentHash: String): Event? = sparkRepo.settledSendEvent(paymentHash) + suspend fun settledSparkSendEvent(paymentHash: String): Event? = + if (isLdkSend(paymentHash)) null else sparkRepo.settledSendEvent(paymentHash) /** Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. */ suspend fun sparkLightningSend(paymentHash: String): SparkLightningSend = sparkRepo.lightningSend(paymentHash) @@ -2968,3 +2990,6 @@ sealed interface ProbeOutcome { */ internal fun isOnchainSyncAfter(latest: ULong?, previous: ULong, requestedSyncSucceeded: Boolean = false): Boolean = requestedSyncSucceeded || (latest ?: 0uL) > previous + +/** The Lightning rail a send went out on. */ +enum class LightningRail { Ldk, Spark } diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index 9de71dab56..02a865f1ca 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -880,6 +880,12 @@ class ActivityService( ?.let { cacheStore.data.first().pendingLightningMessages[it] } val existingActivity = getActivityById(walletId = defaultWalletId, activityId = payment.id) + // A Spark retry of an invoice the node failed shares its hash; the earlier failure never undoes its success. + if (existingActivity is Activity.Lightning && existingActivity.v1.status == PaymentState.SUCCEEDED && + state == PaymentState.FAILED + ) { + return + } if (existingActivity is Activity.Lightning) { val statusChanging = existingActivity.v1.status != state val needsPrivateContactAttribution = existingActivity.v1.contact == null && diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1d0107e432..117f8a84e5 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -2981,6 +2981,8 @@ class AppViewModel @Inject constructor( } private suspend fun refreshPaymentActivity(paymentHash: String) { + // Spark records its own sends; the node's record of the hash is an earlier attempt that would overwrite it. + if (lightningRepo.isSparkSend(paymentHash)) return runSuspendCatching { activityRepo.handlePaymentEvent(paymentHash) }.onFailure { Logger.warn("Failed to refresh payment activity for '$paymentHash'", it, context = TAG) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 8e3c2ec285..3306d1f24a 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -40,6 +40,7 @@ import org.lightningdevkit.ldknode.Node import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PeerDetails import org.lightningdevkit.ldknode.SpendableUtxo import org.lightningdevkit.ldknode.TransactionDetails @@ -1133,6 +1134,56 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).payInvoice("invoice", 1_000uL, deadline, 10_000uL) } + @Test + fun `an earlier spark failure never settles a retry the node is paying`() = test { + startNodeForTesting() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenReturn(Result.failure(PaymentPendingException("hash"))) + sut.payInvoice("bolt11", 1_000uL) + assertTrue(sut.isSparkSend("hash")) + + whenever(sparkRepo.canSend(1_000uL)).thenReturn(false) + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send("bolt11", 1_000uL)).thenReturn("hash") + assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + @Suppress("UNCHECKED_CAST") + (sparkRepo.nodeEvents as MutableSharedFlow) + .emit(Event.PaymentFailed("hash", "hash", PaymentFailureReason.UNEXPECTED_ERROR)) + runCurrent() + + assertTrue(events.none { it is Event.PaymentFailed }) + assertNull(sut.settledSparkSendEvent("hash")) + verify(sparkRepo, never()).settledSendEvent(any()) + assertFalse(sut.isSparkSend("hash")) + } + + @Test + fun `a spark retry of an invoice the node failed is the send that settles it`() = test { + startNodeForTesting() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send("bolt11", 1_000uL)).thenReturn("hash") + sut.payInvoice("bolt11", 1_000uL).getOrThrow() + assertFalse(sut.isSparkSend("hash")) + + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(Result.success("hash")) + sut.payInvoice("bolt11", 1_000uL).getOrThrow() + val succeeded = Event.PaymentSuccessful("hash", "hash", "preimage", 0uL) + @Suppress("UNCHECKED_CAST") + (sparkRepo.nodeEvents as MutableSharedFlow).emit(succeeded) + runCurrent() + + assertTrue(sut.isSparkSend("hash")) + assertEquals(listOf(succeeded), events) + } + @Test fun `restore beginning during spark payment authorization prevents dispatch`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 650d942594..3db0c29d29 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -8173,6 +8173,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pendingPaymentRepo, never()).resolve(any()) } + @Test + fun `a spark retry's success is not overwritten by the node's earlier failure`() = test { + val paymentHash = "spark_retry_hash" + whenever(lightningRepo.isSparkSend(paymentHash)).thenReturn(true) + whenever(pendingPaymentRepo.isPending(paymentHash)).thenReturn(true) + + emitNodeEvent( + Event.PaymentSuccessful( + paymentId = paymentHash, + paymentHash = paymentHash, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + advanceUntilIdle() + + verify(activityRepo, never()).handlePaymentEvent(paymentHash) + verify(pendingPaymentRepo).resolve( + PendingPaymentResolution.Success(paymentHash = paymentHash, amountWithFeeSats = null), + ) + } + @Test fun `pending success still resolves if activity sync fails`() = test { val paymentHash = "pending_sync_fail" From 2aba1219e87093c68cc2205bdba8be292e96f21a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 22:40:23 +0100 Subject: [PATCH 007/135] fix: receive amountless invoices on spark --- .../to/bitkit/repositories/LightningRepo.kt | 13 ++++++- .../bitkit/repositories/LightningRepoTest.kt | 39 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 5e42ac535b..856693de89 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1361,14 +1361,17 @@ class LightningRepo @Inject constructor( runCatching { lightningService.receiveMsats(amountMsats, description, expirySeconds) } } - /** Receives on Spark when no ready channel has the inbound capacity for [amountSats]. */ + /** + * Receives on Spark when no ready channel has the inbound capacity for [amountSats]. An amountless invoice can be + * paid any amount, so it stays on the node only when its inbound covers [AMOUNTLESS_NODE_INBOUND_SATS]. + */ private fun shouldReceiveWithSpark(amountSats: ULong?): Boolean { if (!sparkRepo.canReceive()) return false val readyChannels = _lightningState.value.channels.filter { it.isChannelReady } return !ReceiveLiquidityDecision.canCreateLightningInvoice( hasReadyChannels = readyChannels.isNotEmpty(), inboundCapacitySats = readyChannels.calculateRemoteBalance(), - invoiceAmountSats = amountSats, + invoiceAmountSats = amountSats?.takeIf { it > 0uL } ?: AMOUNTLESS_NODE_INBOUND_SATS, ) } @@ -2321,6 +2324,9 @@ class LightningRepo @Inject constructor( } } + /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ + fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) + fun canSend(amountSats: ULong): Boolean { val state = _lightningState.value if (sparkRepo.canSend(amountSats)) return true @@ -2791,6 +2797,9 @@ class LightningRepo @Inject constructor( private const val SYNC_RETRY_DELAY_MS = 15_000L private const val MSATS_PER_SAT = 1_000uL + /** Inbound capacity the node's ready channels need before an amountless invoice goes to the node, not Spark. */ + private const val AMOUNTLESS_NODE_INBOUND_SATS = 1_000_000uL + /** Sats a Max Lightning send keeps beyond its estimated routing fee, as routes can price slightly higher. */ private const val MAX_SEND_FEE_BUFFER_SATS = 2uL private val BACKGROUND_STOP_DELAY = 5.seconds diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 3306d1f24a..81ed966918 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1305,6 +1305,45 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(testInvoice, result.getOrNull()) } + @Test + fun `amountless invoice goes to spark when the channel inbound is small`() = test { + startNodeForTesting() + readyChannelWithInbound(50_000uL) + whenever(sparkRepo.canReceive()).thenReturn(true) + whenever(sparkRepo.createInvoice(null, "test", 86_400u)).thenReturn(Result.success("spark")) + + assertEquals("spark", sut.createInvoice(description = "test").getOrThrow()) + verify(lightningService, never()).receive(anyOrNull(), any(), any()) + } + + @Test + fun `amountless invoice stays on the node when the channel inbound is large`() = test { + startNodeForTesting() + readyChannelWithInbound(1_000_000uL) + whenever(sparkRepo.canReceive()).thenReturn(true) + whenever(lightningService.receive(null, "test", 86_400u)).thenReturn("node") + + assertEquals("node", sut.createInvoice(description = "test").getOrThrow()) + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + @Test + fun `amount invoice stays on the node when the channel inbound covers it`() = test { + startNodeForTesting() + readyChannelWithInbound(50_000uL) + whenever(sparkRepo.canReceive()).thenReturn(true) + whenever(lightningService.receive(20_000uL, "test", 86_400u)).thenReturn("node") + + assertEquals("node", sut.createInvoice(20_000uL, "test").getOrThrow()) + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + private fun readyChannelWithInbound(sats: ULong) { + val channel = createChannelDetails().copy(isChannelReady = true, inboundCapacityMsat = sats * 1_000uL) + whenever(lightningService.channels).thenReturn(listOf(channel)) + sut.syncState() + } + @Test fun `fetchLnurlInvoice delegates to core and decodes after success`() = test { val data = lnurlPayData() From d4a0dd16ad399b6eb044517a4b2ed4c12f635207 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 22:40:23 +0100 Subject: [PATCH 008/135] fix: auto-pay allowances over spark without a node --- .../repositories/PaykitAllowanceRepo.kt | 15 ++++++---- .../repositories/PaykitAllowanceRepoTest.kt | 28 +++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt index 02a8f5c5aa..2d65788086 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt @@ -610,11 +610,12 @@ class PaykitAllowanceRepo @Inject constructor( it.requiresAcceptance && coversRequest(it) && manualRequestSignatures[it.id] != signature } if (covered.isEmpty()) return@withContext false - if (!canPayNow()) return@withContext markAboveLimitManual(covered, identity, signature) + val payable = payableNow(covered) + if (payable.isEmpty()) return@withContext markAboveLimitManual(covered, identity, signature) if (!isProcessingRequests.compareAndSet(false, true)) return@withContext false try { - whileUpdating { payCovered(covered, identity, signature) } + whileUpdating { payCovered(payable, identity, signature) } } finally { isProcessingRequests.set(false) } @@ -633,11 +634,15 @@ class PaykitAllowanceRepo @Inject constructor( /** * A node that just started lists its channels before they reconnect, and a payment sent then fails with no route. - * Covered requests wait for the next refresh instead of falling back to the manual flow. + * Covered requests wait for the next refresh instead of falling back to the manual flow, except those Spark can + * pay: Spark pays whenever the node cannot, so it needs neither a running node nor a usable channel. */ - private fun canPayNow(): Boolean { + private fun payableNow(covered: List): List { val state = lightningRepo.lightningState.value - return state.nodeLifecycleState.isRunning() && (state.channels.isEmpty() || state.channels.any { it.isUsable }) + val nodeCanPay = state.nodeLifecycleState.isRunning() && + (state.channels.isEmpty() || state.channels.any { it.isUsable }) + if (nodeCanPay) return covered + return covered.filter { request -> request.allowanceSats()?.let { lightningRepo.canSendWithSpark(it) } == true } } /** While the node cannot pay, a request that fits no allowance must not wait for channels: it asks at once. */ diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt index 1eb22a6984..f602cebca3 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt @@ -1071,6 +1071,34 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { verify(executor, never()).autoPay(any(), any(), any()) } + @Test + fun `covered request Spark can pay is paid while the node is stopped`() = test { + records = listOf(fixtures.record()) + sut.activate(identity) + whenever(lightningRepo.canSendWithSpark(1_000uL)).thenReturn(true) + val request = fixtures.paymentRequest() + + sut.processIncomingRequests(listOf(request)) + + verify(executor).autoPay(eq(request), any(), eq(identity)) + } + + @Test + fun `covered request Spark can pay is paid while no channel is usable`() = test { + records = listOf(fixtures.record()) + sut.activate(identity) + val reconnecting = mock { on { isUsable } doReturn false } + lightningState.update { + it.copy(nodeLifecycleState = NodeLifecycleState.Running, channels = persistentListOf(reconnecting)) + } + whenever(lightningRepo.canSendWithSpark(1_000uL)).thenReturn(true) + val request = fixtures.paymentRequest() + + sut.processIncomingRequests(listOf(request)) + + verify(executor).autoPay(eq(request), any(), eq(identity)) + } + @Test fun `nothing is processed without an identity`() = test { assertFalse(sut.processIncomingRequests(listOf(fixtures.paymentRequest()))) From 125e7c1645d443f9bb5c2ab92457fd3792bb99fb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 23:26:36 +0100 Subject: [PATCH 009/135] fix: keep the receive rule for plain invoices --- .../to/bitkit/repositories/LightningRepo.kt | 18 +++-- .../bitkit/repositories/PrivatePaykitRepo.kt | 1 + .../bitkit/repositories/PublicPaykitRepo.kt | 1 + .../bitkit/repositories/LightningRepoTest.kt | 17 +++- .../repositories/PrivatePaykitRepoTest.kt | 43 +++++----- .../repositories/PublicPaykitRepoTest.kt | 3 +- .../PublicPaykitSharingAdmissionTest.kt | 14 ++-- .../to/bitkit/repositories/WalletRepoTest.kt | 78 +++++++++---------- 8 files changed, 98 insertions(+), 77 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 856693de89..d4273466d1 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1334,13 +1334,18 @@ class LightningRepo @Inject constructor( runSuspendCatching { lightningService.revealReceiveAddresses(toReceiveIndex, forType) } } + /** + * Creates an invoice on the node or on Spark. A [isContactEndpoint] invoice is published to Paykit contacts, who + * pay it any amount, so it prefers Spark unless the node's inbound covers [AMOUNTLESS_NODE_INBOUND_SATS]. + */ suspend fun createInvoice( amountSats: ULong? = null, description: String, expirySeconds: UInt = Defaults.bolt11ExpirySec, + isContactEndpoint: Boolean = false, ): Result = executeWhenNodeRunning("createInvoice") { requireWalletRestoreComplete() - if (shouldReceiveWithSpark(amountSats)) { + if (shouldReceiveWithSpark(amountSats, isContactEndpoint)) { return@executeWhenNodeRunning sparkRepo.createInvoice(amountSats, description, expirySeconds) } runCatching { lightningService.receive(amountSats, description, expirySeconds) } @@ -1362,16 +1367,17 @@ class LightningRepo @Inject constructor( } /** - * Receives on Spark when no ready channel has the inbound capacity for [amountSats]. An amountless invoice can be - * paid any amount, so it stays on the node only when its inbound covers [AMOUNTLESS_NODE_INBOUND_SATS]. + * Receives on Spark when no ready channel has the inbound capacity for [amountSats]. An amountless contact endpoint + * stays on the node only when its inbound covers [AMOUNTLESS_NODE_INBOUND_SATS]. */ - private fun shouldReceiveWithSpark(amountSats: ULong?): Boolean { + private fun shouldReceiveWithSpark(amountSats: ULong?, isContactEndpoint: Boolean = false): Boolean { if (!sparkRepo.canReceive()) return false val readyChannels = _lightningState.value.channels.filter { it.isChannelReady } + val neededSats = amountSats?.takeIf { it > 0uL } ?: AMOUNTLESS_NODE_INBOUND_SATS.takeIf { isContactEndpoint } return !ReceiveLiquidityDecision.canCreateLightningInvoice( hasReadyChannels = readyChannels.isNotEmpty(), inboundCapacitySats = readyChannels.calculateRemoteBalance(), - invoiceAmountSats = amountSats?.takeIf { it > 0uL } ?: AMOUNTLESS_NODE_INBOUND_SATS, + invoiceAmountSats = neededSats, ) } @@ -2797,7 +2803,7 @@ class LightningRepo @Inject constructor( private const val SYNC_RETRY_DELAY_MS = 15_000L private const val MSATS_PER_SAT = 1_000uL - /** Inbound capacity the node's ready channels need before an amountless invoice goes to the node, not Spark. */ + /** Inbound the node's ready channels need before an amountless contact endpoint goes to the node, not Spark. */ private const val AMOUNTLESS_NODE_INBOUND_SATS = 1_000_000uL /** Sats a Max Lightning send keeps beyond its estimated routing fee, as routes can price slightly higher. */ diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index 6a1ed57b8a..451ec44ef4 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -1967,6 +1967,7 @@ class PrivatePaykitRepo @Inject constructor( amountSats = null, description = "", expirySeconds = privateInvoiceExpiry.inWholeSeconds.toUInt(), + isContactEndpoint = true, ).getOrThrow() if (!forceRefresh) reusablePrivateInvoice(publicKey)?.let { return@runSuspendCatching it } diff --git a/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt index a35a24fde0..b109ab6583 100644 --- a/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt @@ -582,6 +582,7 @@ class PublicPaykitRepo @Inject constructor( amountSats = null, description = "", expirySeconds = publicBolt11Expiry.inWholeSeconds.toUInt(), + isContactEndpoint = true, ).getOrThrow() val invoice = (coreService.decode(bolt11) as? Scanner.Lightning)?.invoice ?: throw PublicPaykitError.InvalidPayload diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 81ed966918..5d0d14a1a3 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1306,23 +1306,34 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `amountless invoice goes to spark when the channel inbound is small`() = test { + fun `amountless contact endpoint goes to spark when the channel inbound is small`() = test { startNodeForTesting() readyChannelWithInbound(50_000uL) whenever(sparkRepo.canReceive()).thenReturn(true) whenever(sparkRepo.createInvoice(null, "test", 86_400u)).thenReturn(Result.success("spark")) - assertEquals("spark", sut.createInvoice(description = "test").getOrThrow()) + assertEquals("spark", sut.createInvoice(description = "test", isContactEndpoint = true).getOrThrow()) verify(lightningService, never()).receive(anyOrNull(), any(), any()) } @Test - fun `amountless invoice stays on the node when the channel inbound is large`() = test { + fun `amountless contact endpoint stays on the node when the channel inbound is large`() = test { startNodeForTesting() readyChannelWithInbound(1_000_000uL) whenever(sparkRepo.canReceive()).thenReturn(true) whenever(lightningService.receive(null, "test", 86_400u)).thenReturn("node") + assertEquals("node", sut.createInvoice(description = "test", isContactEndpoint = true).getOrThrow()) + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + @Test + fun `plain amountless invoice stays on the node when a channel has inbound`() = test { + startNodeForTesting() + readyChannelWithInbound(50_000uL) + whenever(sparkRepo.canReceive()).thenReturn(true) + whenever(lightningService.receive(null, "test", 86_400u)).thenReturn("node") + assertEquals("node", sut.createInvoice(description = "test").getOrThrow()) verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) } diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index ec451e7887..f36c50c6a2 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -495,7 +495,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { Scanner.Lightning(lightningInvoice(PRIVATE_BOLT11, byteArrayOf(9, 9, 9)).copy(isExpired = true)) ) val renewed = "lnbcrt1renewed" - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(renewed)) whenever(coreService.decode(renewed)) .thenReturn(Scanner.Lightning(lightningInvoice(renewed, byteArrayOf(8, 8, 8)))) @@ -505,7 +505,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { val reservation = updates.secondValue.single().reservations.single() assertEquals(MethodId.Bolt11.rawValue, reservation.identifier) assertEquals(PublicPaykitRepo.serializePayload(renewed), reservation.payload) - verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) } @Test @@ -2192,6 +2192,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { amountSats = null, description = "", expirySeconds = PRIVATE_BOLT11_EXPIRY_SECONDS, + isContactEndpoint = true, ) }.thenReturn(Result.success(PRIVATE_BOLT11)) whenever(coreService.decode(PRIVATE_BOLT11)) @@ -3144,7 +3145,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { settingsData.update { it.copy(sharesPrivatePaykitEndpoints = false) } sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() runCurrent() - verify(lightningRepo).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) settingsData.update { it.copy(sharesPrivatePaykitEndpoints = true) } whenever(paykitSdkService.syncPrivatePaymentListsWithReservations(any(), any())).thenReturn( @@ -3152,17 +3153,17 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { ) sut.enableSharingAndPrepareSavedContacts({ listOf(CONTACT_KEY) }).getOrThrow() runCurrent() - verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) whenever(paykitSdkService.syncPrivatePaymentListsWithReservations(any(), any())).thenReturn( privateListDeliveryReport(queuedCounterparties = listOf(CONTACT_KEY)), ) sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() runCurrent() - verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() runCurrent() - verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) val publications = argumentCaptor>() verify(paykitSdkService, times(3)).syncPrivatePaymentListsWithReservations(publications.capture(), eq(false)) assertEquals(CONTACT_KEY, publications.secondValue.single().counterparty) @@ -3175,14 +3176,14 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { preparePrivateLightningContact() settingsData.update { it.copy(publicPaykitOnchainEnabled = true) } clearInvocations(paykitSdkService) - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.failure(AppError("invoice unavailable"))) sut.refreshKnownSavedContactEndpoints("channel ready", forceRefreshLightning = true).getOrThrow() runCurrent() verify(paykitSdkService, never()).syncPrivatePaymentListsWithReservations(any(), any()) val refreshedInvoice = "lnbcrt1refreshed" - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(refreshedInvoice)) whenever(coreService.decode(refreshedInvoice)) .thenReturn(Scanner.Lightning(lightningInvoice(refreshedInvoice, byteArrayOf(8, 8, 8)))) @@ -3199,7 +3200,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { fun `private Lightning invoice paid through Spark is replaced`() = test { preparePrivateLightningContact() val refreshedInvoice = "lnbcrt1refreshed" - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(refreshedInvoice)) whenever(coreService.decode(refreshedInvoice)) .thenReturn(Scanner.Lightning(lightningInvoice(refreshedInvoice, byteArrayOf(8, 8, 8)))) @@ -3227,7 +3228,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { runCurrent() val refreshedInvoice = "lnbcrt1refreshed" - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(refreshedInvoice)) whenever(coreService.decode(refreshedInvoice)) .thenReturn(Scanner.Lightning(lightningInvoice(refreshedInvoice, byteArrayOf(8, 8, 8)))) @@ -3242,11 +3243,11 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { PublicPaykitRepo.serializePayload(refreshedInvoice), publication.firstValue.single().reservations.single().payload, ) - verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.scheduleSavedContactPreparation(listOf(CONTACT_KEY)).getOrThrow() runCurrent() sut.awaitContactPreparation() - verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(2)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.closeAndClear() } @@ -3272,10 +3273,10 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { runCurrent() sut.awaitContactPreparation() - verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() runCurrent() - verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(3)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.closeAndClear() } @@ -3296,7 +3297,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.scheduleSavedContactPreparation(listOf(CONTACT_KEY)).getOrThrow() runCurrent() - verify(lightningRepo).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.closeAndClear() } @@ -3312,10 +3313,10 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { ) sut.refreshKnownSavedContactEndpoints("channel ready", forceRefreshLightning = true).getOrThrow() runCurrent() - verify(lightningRepo, times(4)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(4)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) val refreshedInvoice = "lnbcrt1refreshed" - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(refreshedInvoice)) whenever(coreService.decode(refreshedInvoice)) .thenReturn(Scanner.Lightning(lightningInvoice(refreshedInvoice, byteArrayOf(8, 8, 8)))) @@ -3325,7 +3326,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { clearInvocations(paykitSdkService) sut.scheduleSavedContactPreparation(keys).getOrThrow() runCurrent() - verify(lightningRepo, times(5)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(5)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) val publication = argumentCaptor>() verify(paykitSdkService).syncPrivatePaymentListsWithReservations(publication.capture(), eq(false)) assertEquals( @@ -3335,7 +3336,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { ) sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() runCurrent() - verify(lightningRepo, times(5)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS) + verify(lightningRepo, times(5)).createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true) sut.closeAndClear() } @@ -3348,7 +3349,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { publicPaykitUsdtEnabled = false, ) whenever(lightningRepo.canReceive()).thenReturn(true) - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(PRIVATE_BOLT11)) whenever(coreService.decode(PRIVATE_BOLT11)) .thenReturn(Scanner.Lightning(lightningInvoice(PRIVATE_BOLT11, byteArrayOf(9, 9, 9)))) @@ -4828,7 +4829,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { publicPaykitUsdtEnabled = false, ) whenever(lightningRepo.canReceive()).thenReturn(true) - whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS)) + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) .thenReturn(Result.success(PRIVATE_BOLT11)) whenever(coreService.decode(PRIVATE_BOLT11)) .thenReturn(Scanner.Lightning(lightningInvoice(PRIVATE_BOLT11, byteArrayOf(9, 9, 9)))) diff --git a/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt index 4116119f9f..dbba7e0d65 100644 --- a/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt @@ -265,7 +265,7 @@ class PublicPaykitRepoTest : BaseUnitTest() { stubPublicInvoice("lnbc1replacement", byteArrayOf(4, 5, 6)) val invoiceStarted = CompletableDeferred() val resumeInvoice = CompletableDeferred() - whenever(lightningRepo.createInvoice(null, "", PUBLIC_BOLT11_EXPIRY_SECONDS)).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(null, "", PUBLIC_BOLT11_EXPIRY_SECONDS, true)).doSuspendableAnswer { invoiceStarted.complete(Unit) resumeInvoice.await() Result.success("lnbc1replacement") @@ -962,6 +962,7 @@ class PublicPaykitRepoTest : BaseUnitTest() { amountSats = null, description = "", expirySeconds = PUBLIC_BOLT11_EXPIRY_SECONDS, + isContactEndpoint = true, ) ).thenReturn(Result.success(bolt11)) whenever(coreService.decode(bolt11)).thenReturn(Scanner.Lightning(lightningInvoice(bolt11, paymentHash))) diff --git a/app/src/test/java/to/bitkit/repositories/PublicPaykitSharingAdmissionTest.kt b/app/src/test/java/to/bitkit/repositories/PublicPaykitSharingAdmissionTest.kt index 4cb5c1d64d..33c639e095 100644 --- a/app/src/test/java/to/bitkit/repositories/PublicPaykitSharingAdmissionTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PublicPaykitSharingAdmissionTest.kt @@ -304,7 +304,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { ) whenever(lightningRepo.canReceive()).thenReturn(true) PublicPaykitRepo.lightningRouteHintsValidator = { true } - whenever(lightningRepo.createInvoice(null, "", 86_400u)).thenReturn(Result.success("ln-new")) + whenever(lightningRepo.createInvoice(null, "", 86_400u, true)).thenReturn(Result.success("ln-new")) whenever(coreService.decode("ln-new")).thenReturn(Scanner.Lightning(invoice("ln-new"))) whenever(usdtRepo.paymentEndpoint()).thenReturn(Result.failure(AppError("USDT unavailable"))) @@ -327,7 +327,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { verifyBlocking(paykitSdkService, times(2)) { syncPublicEndpoints(endpoints.capture(), any()) } assertEquals(listOf("ln-new"), endpoints.firstValue.map { it.value }) assertEquals(listOf("ln-new", usdt.value), endpoints.secondValue.map { it.value }) - verifyBlocking(lightningRepo, times(1)) { createInvoice(null, "", 86_400u) } + verifyBlocking(lightningRepo, times(1)) { createInvoice(null, "", 86_400u, true) } assertFalse(settingsFlow.value.publicPaykitCleanupPending) } @@ -347,7 +347,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { publicPaykitBolt11PaymentHash = "01", publicPaykitBolt11ExpiresAtMillis = Long.MAX_VALUE, ) - whenever(lightningRepo.createInvoice(null, "", 86_400u)) + whenever(lightningRepo.createInvoice(null, "", 86_400u, true)) .thenReturn(Result.success("ln-first"), Result.success("ln-second")) for (bolt11 in listOf("ln-first", "ln-second")) { whenever(coreService.decode(bolt11)).thenReturn(Scanner.Lightning(invoice(bolt11))) @@ -376,7 +376,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { sut.syncCurrentPublishedEndpoints().getOrThrow() assertEquals(listOf(expectedInvoice), published.last(), outcome) verifyBlocking(lightningRepo, times(if (outcome == "superseded") 2 else 1)) { - createInvoice(null, "", 86_400u) + createInvoice(null, "", 86_400u, true) } } } @@ -401,7 +401,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { publicPaykitBolt11PaymentHash = "01", publicPaykitBolt11ExpiresAtMillis = Long.MAX_VALUE, ) - whenever(lightningRepo.createInvoice(null, "", 86_400u)).thenReturn(Result.success("ln-refreshed")) + whenever(lightningRepo.createInvoice(null, "", 86_400u, true)).thenReturn(Result.success("ln-refreshed")) whenever(coreService.decode("ln-refreshed")).thenReturn(Scanner.Lightning(invoice("ln-refreshed"))) sut.requestLightningRefresh(null) { ownsIdentity } repeat(2) { @@ -450,7 +450,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { val preparing = CompletableDeferred() val resume = CompletableDeferred() var invoiceCount = 0 - whenever(lightningRepo.createInvoice(null, "", 86_400u)).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(null, "", 86_400u, true)).doSuspendableAnswer { invoiceCount += 1 if (invoiceCount == 1) { preparing.complete(Unit) @@ -509,7 +509,7 @@ class PublicPaykitSharingAdmissionTest : BaseUnitTest() { generation += 1 assertFalse(sut.hasPendingLightningRefresh) sut.syncCurrentPublishedEndpoints().getOrThrow() - verifyBlocking(lightningRepo, never()) { createInvoice(any(), any(), any()) } + verifyBlocking(lightningRepo, never()) { createInvoice(any(), any(), any(), any()) } assertEquals("ln-replacement-session", settingsFlow.value.publicPaykitBolt11) } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index 68c7bed28c..c295c767c0 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -639,7 +639,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.nodeEventUpdates).thenReturn(events) whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.failure(error)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.failure(error)) when (decoderMode) { 0 -> whenever(coreService.decode(INVOICE)) .thenReturn(Scanner.Lightning(lightningInvoice(INVOICE, true))) @@ -664,7 +664,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.nodeEventUpdates).thenReturn(events) whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.failure(error), Result.success(INVOICE_REPLACEMENT)) val decodeStarted = CompletableDeferred() val releaseDecode = CompletableDeferred() @@ -720,7 +720,7 @@ class WalletRepoTest : BaseUnitTest() { sut.loadFromCache() whenever(coreService.isAddressUsed(any())).thenThrow(error) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) assertTrue(sut.refreshReceiveState().isSuccess) assertEquals(ADDRESS, sut.walletState.value.onchainAddress) @@ -728,7 +728,7 @@ class WalletRepoTest : BaseUnitTest() { assertTrue(sut.retryReceiveInvoice().isSuccess) assertEquals(INVOICE, sut.walletState.value.bolt11) assertFalse(sut.walletState.value.hasReceiveInvoiceError) - verify(lightningRepo, times(2)).createInvoice(anyOrNull(), any(), any()) + verify(lightningRepo, times(2)).createInvoice(anyOrNull(), any(), any(), any()) } @Test @@ -792,7 +792,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.nodeEventUpdates).thenReturn(events) whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.failure(error)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.failure(error)) sut = createSut() sut.setOnchainAddress(ADDRESS) sut.setBolt11(INVOICE) @@ -812,7 +812,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.nodeEventUpdates).thenReturn(events) whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.failure(error)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.failure(error)) sut = createSut() sut.setOnchainAddress(ADDRESS) @@ -827,7 +827,7 @@ class WalletRepoTest : BaseUnitTest() { sut.loadFromCache() whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseInvoice = CompletableDeferred() - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { releaseInvoice.await() Result.success(INVOICE) } @@ -848,7 +848,7 @@ class WalletRepoTest : BaseUnitTest() { sut.setBolt11(INVOICE) whenever(coreService.isAddressUsed(any())).thenReturn(false) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.failure(error)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.failure(error)) assertTrue(sut.updateBip21Invoice(SATS, "failed edit").isFailure) sut.refreshReusableReceiveAddress().getOrThrow() @@ -864,7 +864,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.nodeEventUpdates).thenReturn(events) whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.failure(error)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.failure(error)) sut = createSut() sut.setOnchainAddress(ADDRESS) sut.setBolt11(INVOICE) @@ -932,7 +932,7 @@ class WalletRepoTest : BaseUnitTest() { releaseCheck.await() false } - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.success(INVOICE_REPLACEMENT)) val maintenance = launch { sut.refreshReusableReceiveAddress() } val settlement = launch { @@ -996,7 +996,7 @@ class WalletRepoTest : BaseUnitTest() { dispatcher.runOldestFirst() sut.setOnchainAddress(ADDRESS) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { invocation -> + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { invocation -> val amount = invocation.getArgument(0) Result.success(if (amount == SATS) INVOICE else INVOICE_REPLACEMENT) } @@ -1020,7 +1020,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(coreService.isAddressUsed(any())).thenReturn(false) sut.loadFromCache() whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.success(INVOICE), Result.failure(error), Result.success(INVOICE_REPLACEMENT)) sut.updateBip21Invoice(SATS, "old invoice").getOrThrow() val editedAmount = SATS / 2uL @@ -1031,7 +1031,7 @@ class WalletRepoTest : BaseUnitTest() { assertEquals(editedAmount, sut.walletState.value.bip21AmountSats) assertEquals("old invoice", sut.walletState.value.bip21Description) - verify(lightningRepo, times(2)).createInvoice(eq(editedAmount), eq("old invoice"), any()) + verify(lightningRepo, times(2)).createInvoice(eq(editedAmount), eq("old invoice"), any(), any()) } @Test @@ -1039,7 +1039,7 @@ class WalletRepoTest : BaseUnitTest() { sut.loadFromCache() whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseInvoice = CompletableDeferred() - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { releaseInvoice.await() Result.success(INVOICE) } @@ -1059,7 +1059,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.getChannels()).thenReturn(channels) whenever(privatePaykitAddressReservationRepo.nextReusableReceiveAddress()) .thenReturn(Result.failure(error), Result.success(ADDRESS_NEW)) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.success(INVOICE)) assertTrue(sut.refreshReceiveState().isFailure) assertTrue(sut.walletState.value.hasReceiveInvoiceError) @@ -1276,7 +1276,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseOlder = CompletableDeferred() var invoiceCalls = 0 - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { if (invoiceCalls++ == 0) { releaseOlder.await() Result.success(INVOICE) @@ -1303,7 +1303,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.nodeEventUpdates).thenReturn(events) whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.success(INVOICE)) var cacheCalls = 0 whenever(cacheStore.update(any())).doSuspendableAnswer { @@ -1316,7 +1316,7 @@ class WalletRepoTest : BaseUnitTest() { events.emit(NodeEventUpdate(channelReady)) - verify(lightningRepo, times(2)).createInvoice(anyOrNull(), any(), any()) + verify(lightningRepo, times(2)).createInvoice(anyOrNull(), any(), any(), any()) assertFalse(sut.walletState.value.hasReceiveInvoiceError) assertEquals(INVOICE, sut.walletState.value.bolt11) } @@ -1328,7 +1328,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseFirstInvoice = CompletableDeferred() var invoiceCalls = 0 - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { invoiceCalls += 1 if (invoiceCalls == 1) { releaseFirstInvoice.await() @@ -1354,7 +1354,7 @@ class WalletRepoTest : BaseUnitTest() { sut.loadFromCache() whenever(coreService.isAddressUsed(any())).thenReturn(false) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.failure(error), Result.success(INVOICE)) assertTrue(sut.refreshReceiveState().isFailure) @@ -1371,7 +1371,7 @@ class WalletRepoTest : BaseUnitTest() { sut.loadFromCache() whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseInvoice = CompletableDeferred() - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { releaseInvoice.await() Result.success(INVOICE) } @@ -1385,7 +1385,7 @@ class WalletRepoTest : BaseUnitTest() { assertEquals(SATS * 2uL, state.bip21AmountSats) assertEquals("changed during creation", state.bip21Description) assertEquals(sut.buildBip21Url(ADDRESS, SATS, "requested", INVOICE), state.bip21) - verify(lightningRepo).createInvoice(eq(SATS), eq("requested"), any()) + verify(lightningRepo).createInvoice(eq(SATS), eq("requested"), any(), any()) assertFalse(state.isReceiveInvoiceUpdating) } @@ -1395,7 +1395,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.getChannels()).thenReturn(channels) sut.setBolt11(INVOICE) val previous = sut.walletState.value - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.failure(error)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.failure(error)) assertTrue(sut.updateBip21Invoice(SATS, "unsaved edit").isFailure) @@ -1432,7 +1432,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseFirstInvoice = CompletableDeferred() var invoiceCalls = 0 - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { invoiceCalls += 1 if (invoiceCalls == 1) { releaseFirstInvoice.await() @@ -1459,7 +1459,7 @@ class WalletRepoTest : BaseUnitTest() { sut.loadFromCache() whenever(lightningRepo.getChannels()).thenReturn(channels) val releaseInvoice = CompletableDeferred() - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { releaseInvoice.await() Result.success(INVOICE) } @@ -1480,7 +1480,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.getChannels()).thenReturn(channels) val neverReleased = CompletableDeferred() var invoiceCalls = 0 - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).doSuspendableAnswer { + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).doSuspendableAnswer { if (invoiceCalls++ == 0) neverReleased.await() Result.success(INVOICE_REPLACEMENT) } @@ -1499,7 +1499,7 @@ class WalletRepoTest : BaseUnitTest() { fun `invoice publication never exposes new bolt11 with onchain only bip21`() = test { sut.loadFromCache() whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) val states = mutableListOf() sut.walletState.onEach { states.add(it) }.launchIn(backgroundScope) @@ -1514,7 +1514,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.canReceive()).thenReturn(true) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState(channels = channels))) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) sut.updateBip21Invoice(amountSats = SATS, description = "test").let { result -> assertTrue(result.isSuccess) @@ -1535,7 +1535,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.lightningState) .thenReturn(MutableStateFlow(LightningState(channels = readyButNotUsableChannels))) whenever(lightningRepo.getChannels()).thenReturn(readyButNotUsableChannels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) sut.updateBip21Invoice(amountSats = SATS, description = "test").let { result -> assertTrue(result.isSuccess) @@ -1556,7 +1556,7 @@ class WalletRepoTest : BaseUnitTest() { @Test fun `updateBip21Invoice should build correct BIP21 URL`() = test { whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(onchainAddress = ADDRESS))) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) sut = createSut() sut.loadFromCache() @@ -1760,7 +1760,7 @@ class WalletRepoTest : BaseUnitTest() { sut.setOnchainAddress(ADDRESS) sut.setBolt11(INVOICE) sut.setBip21Description("test") - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) val result = sut.updateOnchainBip21Amount(2000uL) @@ -1771,7 +1771,7 @@ class WalletRepoTest : BaseUnitTest() { assertTrue(sut.walletState.value.bip21.contains("amount=0.00002")) assertTrue(sut.walletState.value.bip21.contains("message=test")) assertFalse(sut.walletState.value.bip21.contains("lightning=")) - verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any()) + verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any(), any()) } @Test @@ -1791,7 +1791,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.canReceive()).thenReturn(true) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState(channels = channels))) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) sut.refreshBip21ForEvent(channelReady) @@ -1808,7 +1808,7 @@ class WalletRepoTest : BaseUnitTest() { sut.refreshBip21ForEvent(channelReady) - verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any()) + verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any(), any()) verify(lightningRepo).syncState() } @@ -1836,11 +1836,11 @@ class WalletRepoTest : BaseUnitTest() { sut.setBip21AmountSats(SATS) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success(INVOICE)) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) sut.refreshBip21ForEvent(channelReady) - verify(lightningRepo).createInvoice(anyOrNull(), any(), any()) + verify(lightningRepo).createInvoice(anyOrNull(), any(), any(), any()) verify(lightningRepo).syncState() assertEquals(INVOICE, sut.walletState.value.bolt11) } @@ -1928,7 +1928,7 @@ class WalletRepoTest : BaseUnitTest() { fun `refreshBip21ForEvent PaymentReceived should invalidate the settled invoice`() = test { whenever(coreService.isAddressUsed(any())).thenReturn(false) whenever(lightningRepo.canReceive()).thenReturn(true) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.success(INVOICE_REPLACEMENT)) sut.setOnchainAddress(ADDRESS) sut.setBolt11(INVOICE) @@ -1948,7 +1948,7 @@ class WalletRepoTest : BaseUnitTest() { assertFalse(sut.walletState.value.bip21.contains(INVOICE)) assertTrue(sut.walletState.value.bip21.contains(ADDRESS)) verify(cacheStore, never()).invalidateReceiveLightningInvoice(any()) - verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any()) + verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any(), any()) verify(preActivityMetadataRepo, never()).addPreActivityMetadata(any()) } @@ -2040,7 +2040,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(lightningRepo.canReceive()).thenReturn(true) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState(channels = channels))) whenever(lightningRepo.getChannels()).thenReturn(channels) - whenever(lightningRepo.createInvoice(anyOrNull(), any(), any())) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())) .thenReturn(Result.success(INVOICE_REPLACEMENT)) sut.setOnchainAddress(ADDRESS) sut.setBolt11(INVOICE) From 321412b4114f8b2da213041e5c11fdf5d0df7725 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 00:23:52 +0100 Subject: [PATCH 010/135] fix: check a paykit payment is still allowed right before it sends --- .../to/bitkit/repositories/LightningRepo.kt | 7 ++++--- .../java/to/bitkit/repositories/SparkRepo.kt | 3 +++ .../bitkit/repositories/LightningRepoTest.kt | 19 +++++++++++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 17 +++++++++++++++++ 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index d4273466d1..55e3666ab9 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1487,9 +1487,10 @@ class LightningRepo @Inject constructor( ): Result { if (shouldPayWithSpark(bolt11, sats)) { runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } - if (!onBeforeSend()) return Result.failure(PaymentAbortedBeforeSend()) - runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } - return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) + val authorizeSend: suspend () -> Boolean = { + onBeforeSend().also { if (it) requireWalletRestoreComplete() } + } + return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat, authorizeSend) .onSuccess { recordSendRail(it, LightningRail.Spark) } .onFailure { if (it is PaymentPendingException) recordSendRail(it.paymentHash, LightningRail.Spark) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7f49f35f2f..c4874e9468 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -239,6 +239,7 @@ class SparkRepo @Inject constructor( amountSats: ULong?, paymentDeadlineAt: Instant? = null, maxTotalFeeMsat: ULong? = null, + onBeforeSend: suspend () -> Boolean = { true }, ): Result = withContext(bgDispatcher) { runSuspendCatching { ensurePaymentDeadline(paymentDeadlineAt) @@ -264,6 +265,8 @@ class SparkRepo @Inject constructor( throw PaymentPendingException(paymentHash) else -> Unit } + // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. + if (!onBeforeSend()) throw PaymentAbortedBeforeSend() if (!sendsInFlight.add(paymentHash.lowercase())) throw PaymentPendingException(paymentHash) val sent = try { runSuspendCatching { sparkService.send(prepared) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 5d0d14a1a3..23f6750bdd 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1118,20 +1118,21 @@ class LightningRepoTest : BaseUnitTest() { assertIs(result.exceptionOrNull()) assertFalse(beforeSend) - verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } @Test fun `spark payment keeps the deadline and the fee limit`() = test { startNodeForTesting() whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) - whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(Result.success("hash")) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) val deadline = Instant.fromEpochSeconds(1_800_000_000) val result = sut.payInvoice("invoice", 1_000uL, deadline, maxTotalRoutingFeeMsat = 10_000uL) { true } assertEquals("hash", result.getOrThrow()) - verify(sparkRepo).payInvoice("invoice", 1_000uL, deadline, 10_000uL) + verify(sparkRepo).payInvoice(eq("invoice"), eq(1_000uL), eq(deadline), eq(10_000uL), any()) } @Test @@ -1141,7 +1142,7 @@ class LightningRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } runCurrent() whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) - whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.failure(PaymentPendingException("hash"))) sut.payInvoice("bolt11", 1_000uL) assertTrue(sut.isSparkSend("hash")) @@ -1173,7 +1174,8 @@ class LightningRepoTest : BaseUnitTest() { assertFalse(sut.isSparkSend("hash")) whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) - whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(Result.success("hash")) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) sut.payInvoice("bolt11", 1_000uL).getOrThrow() val succeeded = Event.PaymentSuccessful("hash", "hash", "preimage", 0uL) @Suppress("UNCHECKED_CAST") @@ -1188,6 +1190,11 @@ class LightningRepoTest : BaseUnitTest() { fun `restore beginning during spark payment authorization prevents dispatch`() = test { startNodeForTesting() whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var dispatched = false + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + val authorize = it.getArgument Boolean>(4) + runCatching { if (authorize()) dispatched = true }.map { "hash" } + } val result = sut.payInvoice("invoice", 1_000uL, onBeforeSend = { whenever(keychain.exists(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name)).thenReturn(true) @@ -1195,7 +1202,7 @@ class LightningRepoTest : BaseUnitTest() { }) assertIs(result.exceptionOrNull()) - verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull()) + assertFalse(dispatched) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5309c629bb..a3af316c76 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -474,6 +474,23 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a cancel landing while spark prepares sends nothing`() = test { + whenever(sparkService.isConnected).thenReturn(true) + var cancelled = false + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { + cancelled = true + prepared + } + val sut = createSut() + + val result = sut.payInvoice("lnbc1", 100uL, onBeforeSend = { !cancelled }) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + @Test fun `an expired invoice spark refuses is a typed refusal`() = test { whenever(sparkService.isConnected).thenReturn(true) From 7083719639f8f7e861fe7d7a8b6e1acd3542e3da Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 10:52:31 +0100 Subject: [PATCH 011/135] fix: never pay an invoice on both rails --- .../to/bitkit/repositories/LightningRepo.kt | 37 ++++++++++++- .../java/to/bitkit/repositories/SparkRepo.kt | 32 +++++++++-- .../bitkit/repositories/LightningRepoTest.kt | 54 +++++++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 11 ++++ 4 files changed, 130 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 55e3666ab9..23962250ce 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -56,9 +56,11 @@ import org.lightningdevkit.ldknode.Network import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.OutPoint import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentHash import org.lightningdevkit.ldknode.PaymentId import org.lightningdevkit.ldknode.PaymentKind +import org.lightningdevkit.ldknode.PaymentStatus import org.lightningdevkit.ldknode.PeerDetails import org.lightningdevkit.ldknode.SpendableUtxo import org.lightningdevkit.ldknode.Txid @@ -1485,8 +1487,11 @@ class LightningRepo @Inject constructor( maxTotalRoutingFeeMsat: ULong?, onBeforeSend: suspend () -> Boolean, ): Result { + // The rail is picked again on every attempt, so each one checks the other holds no live send of the invoice. + val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() if (shouldPayWithSpark(bolt11, sats)) { runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } + earlierNodeSend(bolt11, paymentHash)?.let { return it.toResult() } val authorizeSend: suspend () -> Boolean = { onBeforeSend().also { if (it) requireWalletRestoreComplete() } } @@ -1496,12 +1501,32 @@ class LightningRepo @Inject constructor( if (it is PaymentPendingException) recordSendRail(it.paymentHash, LightningRail.Spark) } } - return payInvoiceWithLdk(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) + return payInvoiceWithLdk(bolt11, sats, paymentHash, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) + } + + private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { + val send = listPaymentsOrNull()?.firstOrNull { + val kind = it.kind as? PaymentKind.Bolt11 ?: return@firstOrNull false + it.direction == PaymentDirection.OUTBOUND && + (kind.bolt11.equals(bolt11, ignoreCase = true) || kind.hash.equals(paymentHash, ignoreCase = true)) + } ?: return null + val hash = (send.kind as PaymentKind.Bolt11).hash + return when (send.status) { + PaymentStatus.PENDING -> EarlierSend.Pending(hash) + PaymentStatus.SUCCEEDED -> EarlierSend.Paid(hash) + PaymentStatus.FAILED -> null + } + } + + private fun EarlierSend.toResult(): Result = when (this) { + is EarlierSend.Pending -> Result.failure(PaymentPendingException(paymentHash)) + is EarlierSend.Paid -> Result.success(paymentHash) } private suspend fun payInvoiceWithLdk( bolt11: String, sats: ULong?, + paymentHash: String?, paymentDeadlineAt: Instant?, maxTotalRoutingFeeMsat: ULong?, onBeforeSend: suspend () -> Boolean, @@ -1509,6 +1534,7 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() waitForUsableChannels() requireWalletRestoreComplete() + sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } @@ -3009,3 +3035,12 @@ internal fun isOnchainSyncAfter(latest: ULong?, previous: ULong, requestedSyncSu /** The Lightning rail a send went out on. */ enum class LightningRail { Ldk, Spark } + +/** A pending or paid send of an invoice on one rail, which a retry routed to the other must not repeat. */ +sealed interface EarlierSend { + val paymentHash: String + + data class Pending(override val paymentHash: String) : EarlierSend + + data class Paid(override val paymentHash: String) : EarlierSend +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c4874e9468..8f01d308a5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -673,9 +673,35 @@ class SparkRepo @Inject constructor( ?: SparkLightningSend.NotFound } - private fun List.latestSend(paymentHash: String): Payment? = filter { - val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash - it.paymentType == SparkPaymentType.SEND && hash.equals(paymentHash, ignoreCase = true) + /** + * Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it + * again; null when Spark's send failed or none is known. + */ + suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = + withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext null + val send = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrNull() + ?.latestSend { + it.invoice.equals(bolt11, ignoreCase = true) || + it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) + } + ?: return@withContext null + val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash + when (send.status) { + PaymentStatus.PENDING -> EarlierSend.Pending(hash) + PaymentStatus.COMPLETED -> EarlierSend.Paid(hash) + PaymentStatus.FAILED -> null + } + } + + private fun List.latestSend(paymentHash: String): Payment? = + latestSend { it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } + + private fun List.latestSend(matches: (PaymentDetails.Lightning) -> Boolean): Payment? = filter { + val details = it.details as? PaymentDetails.Lightning + it.paymentType == SparkPaymentType.SEND && details != null && matches(details) } // A retry of a failed send shares its hash, so the outcome that settles it wins. .minByOrNull { SEND_STATUS_PRIORITY.indexOf(it.status) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 23f6750bdd..d40c9ca649 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -40,7 +40,10 @@ import org.lightningdevkit.ldknode.Node import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentFailureReason +import org.lightningdevkit.ldknode.PaymentKind +import org.lightningdevkit.ldknode.PaymentStatus import org.lightningdevkit.ldknode.PeerDetails import org.lightningdevkit.ldknode.SpendableUtxo import org.lightningdevkit.ldknode.TransactionDetails @@ -1186,6 +1189,57 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(listOf(succeeded), events) } + @Test + fun `an invoice the node is still paying is not sent again through spark`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send("bolt11", 1_000uL)).thenReturn("hash") + sut.payInvoice("bolt11", 1_000uL).getOrThrow() + val inFlight = PaymentDetails( + id = "hash", + kind = PaymentKind.Bolt11( + hash = "hash", + preimage = null, + secret = null, + description = null, + bolt11 = "bolt11", + ), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = PaymentStatus.PENDING, + latestUpdateTimestamp = 0uL, + ) + whenever(lightningService.listPayments()).thenReturn(listOf(inFlight)) + // The HTLC in flight leaves the channel too little outbound, so the retry falls to Spark. + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + val retry = sut.payInvoice("bolt11", 1_000uL) + + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + assertIs(retry.exceptionOrNull()) + } + + @Test + fun `an invoice spark is still paying is not sent again through the node`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.failure(PaymentPendingException("hash"))) + sut.payInvoice("bolt11", 1_000uL) + // Channels come up, so the retry goes to the node while Spark still pays the first attempt. + whenever(sparkRepo.canSend(1_000uL)).thenReturn(false) + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(sparkRepo.earlierLightningSend("bolt11", null)).thenReturn(EarlierSend.Pending("hash")) + + val retry = sut.payInvoice("bolt11", 1_000uL) + + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + assertIs(retry.exceptionOrNull()) + } + @Test fun `restore beginning during spark payment authorization prevents dispatch`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a3af316c76..22de18fc27 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -132,6 +132,17 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `an invoice spark is still paying is reported pending`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 2).copy(status = PaymentStatus.PENDING))) + + val earlier = createSut().earlierLightningSend("lnbc1280n1send", null) + + assertEquals(EarlierSend.Pending("hash"), earlier) + } + @Test fun `records a send's fee once a sync reports it`() = test { whenever(sparkService.isConnected).thenReturn(true) From 891e355b6d0689243b482d32a26b6a1c7a5683de Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 10:52:31 +0100 Subject: [PATCH 012/135] fix: redo spark's exit backup only when it connects --- .../java/to/bitkit/repositories/SparkRepo.kt | 10 +++++++--- .../java/to/bitkit/services/SparkService.kt | 6 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8f01d308a5..944286f81b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -125,6 +125,9 @@ class SparkRepo @Inject constructor( private val sendsInFlight = ConcurrentHashMap.newKeySet() + @Volatile + private var hasSyncedActivities = false + /** The remote exit data backup was merged in, or there was none, so an upload cannot drop what it held. */ @Volatile var hasMergedRemoteExitState = false @@ -155,15 +158,15 @@ class SparkRepo @Inject constructor( if (isCollectingEvents.compareAndSet(false, true)) { scope.launch { sparkService.events.collect { onSdkEvent(it) } } } - sparkService.connect(walletIndex) + val connected = sparkService.connect(walletIndex) importRestoredExitState(walletIndex) // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. runSuspendCatching { sparkService.syncWallet() } .onSuccess { _state.update { it.copy(hasSynced = true) } } .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } - _exitStateChanged.emit(Unit) + if (connected) _exitStateChanged.emit(Unit) refresh() - syncActivities() + if (!hasSyncedActivities) syncActivities().also { hasSyncedActivities = true } }.onFailure { Logger.error("Failed to start Spark wallet", it, context = TAG) } @@ -184,6 +187,7 @@ class SparkRepo @Inject constructor( broadcastDeposits.clear() sendsRecordedWithoutFee.clear() sendsInFlight.clear() + hasSyncedActivities = false hasMergedRemoteExitState = false _depositClaims.update { emptyMap() } _state.update { SparkState(isSupported = sparkService.isSupported) } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index cef9e61f39..413710108b 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -143,8 +143,9 @@ class SparkService @Inject constructor( */ val prefersSpark: Boolean get() = Env.network == Network.REGTEST - suspend fun connect(walletIndex: Int) = mutex.withLock { - if (sdk != null) return@withLock + /** Connects the SDK and returns true, or false when it was already connected. */ + suspend fun connect(walletIndex: Int): Boolean = mutex.withLock { + if (sdk != null) return@withLock false if (isWiping) throw SparkError.WipeInProgress() val network = sparkNetwork() ?: throw SparkError.Unsupported() val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() @@ -166,6 +167,7 @@ class SparkService @Inject constructor( ) sdk = connected Logger.info("Connected Spark wallet on '$network' with chain '${chainServiceUrl ?: "default"}'", context = TAG) + true } suspend fun disconnect() = mutex.withLock { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 22de18fc27..0f652000d0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -110,6 +110,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.listUnclaimedDeposits() }.thenReturn(emptyList()) whenever { sparkService.listPayments() }.thenReturn(emptyList()) whenever(sparkService.events).thenReturn(sparkEvents) + whenever { sparkService.connect(any()) }.thenReturn(true) whenever { activityRepo.getActivity(any(), any()) }.thenReturn(Result.success(null)) whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) whenever(sparkService.isSupported).thenReturn(true) @@ -132,6 +133,24 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `a start while already connected neither redoes the exit backup nor rewrites every activity`() = test { + whenever(sparkService.isConnected).thenReturn(false, true) + whenever(sparkService.connect(0)).thenReturn(true, false) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + val sut = createSut() + val exitSignals = mutableListOf() + backgroundScope.launch { sut.exitStateChanged.collect { exitSignals += it } } + runCurrent() + + sut.start(0).getOrThrow() + sut.start(0).getOrThrow() + runCurrent() + + assertEquals(1, exitSignals.size, "exit data backup signals after two starts") + verify(activityRepo, times(1)).upsertActivity(any()) + } + @Test fun `an invoice spark is still paying is reported pending`() = test { whenever(sparkService.isConnected).thenReturn(true) From d93b1311c7236ac123652e7243634585d88e7143 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 10:52:31 +0100 Subject: [PATCH 013/135] fix: cap spark send fees at the node's default limit --- .../to/bitkit/repositories/LightningRepo.kt | 20 ++++++++++++++++--- .../bitkit/repositories/LightningRepoTest.kt | 12 +++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 23962250ce..8aa4777e2a 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1385,14 +1385,17 @@ class LightningRepo @Inject constructor( /** Pays with Spark when no channel has the outbound capacity for the invoice amount. */ private fun shouldPayWithSpark(bolt11: String, sats: ULong?): Boolean { - val amountSats = sats ?: runCatching { Bolt11Invoice.fromStr(bolt11).amountMilliSatoshis() }.getOrNull() - ?.let { it / MSATS_PER_SAT } ?: return false + val amountSats = invoiceAmountSats(bolt11, sats) ?: return false val state = _lightningState.value val ldkCanSend = state.nodeLifecycleState.canRun() && state.channels.totalNextOutboundHtlcLimitSats() >= amountSats return !ldkCanSend && sparkRepo.canSend(amountSats) } + private fun invoiceAmountSats(bolt11: String, sats: ULong?): ULong? = + sats ?: runCatching { Bolt11Invoice.fromStr(bolt11).amountMilliSatoshis() }.getOrNull() + ?.let { it / MSATS_PER_SAT } + suspend fun fetchLnurlInvoice( data: LnurlPayData, amountMsats: ULong, @@ -1495,7 +1498,12 @@ class LightningRepo @Inject constructor( val authorizeSend: suspend () -> Boolean = { onBeforeSend().also { if (it) requireWalletRestoreComplete() } } - return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat, authorizeSend) + // Without a caller's limit Spark keeps to the node's default, so a re-quote cannot raise the fee past it. + val maxTotalFeeMsat = maxTotalRoutingFeeMsat ?: invoiceAmountSats(bolt11, sats)?.let { + (it.safe() * MSATS_PER_SAT.safe() / DEFAULT_ROUTING_FEE_DIVISOR).safe() + + DEFAULT_ROUTING_FEE_BASE_MSAT.safe() + } + return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalFeeMsat, authorizeSend) .onSuccess { recordSendRail(it, LightningRail.Spark) } .onFailure { if (it is PaymentPendingException) recordSendRail(it.paymentHash, LightningRail.Spark) @@ -2830,6 +2838,12 @@ class LightningRepo @Inject constructor( private const val SYNC_RETRY_DELAY_MS = 15_000L private const val MSATS_PER_SAT = 1_000uL + /** LDK's default routing fee limit is 1% of the amount, this divisor, plus [DEFAULT_ROUTING_FEE_BASE_MSAT]. */ + private const val DEFAULT_ROUTING_FEE_DIVISOR = 100uL + + /** The flat 50 sats in LDK's default routing fee limit. */ + private const val DEFAULT_ROUTING_FEE_BASE_MSAT = 50_000uL + /** Inbound the node's ready channels need before an amountless contact endpoint goes to the node, not Spark. */ private const val AMOUNTLESS_NODE_INBOUND_SATS = 1_000_000uL diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index d40c9ca649..c870bb601b 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1240,6 +1240,18 @@ class LightningRepoTest : BaseUnitTest() { assertIs(retry.exceptionOrNull()) } + @Test + fun `spark payment without a fee limit keeps to the node's default one`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + sut.payInvoice("invoice", 1_000uL).getOrThrow() + + verify(sparkRepo).payInvoice(eq("invoice"), eq(1_000uL), isNull(), eq(60_000uL), any()) + } + @Test fun `restore beginning during spark payment authorization prevents dispatch`() = test { startNodeForTesting() From c85259fe2a12b4b58efa810b90667a6447ce0004 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:00:23 +0100 Subject: [PATCH 014/135] fix: refuse a node retry while spark is still sending --- .../java/to/bitkit/repositories/SparkRepo.kt | 12 +++- .../bitkit/repositories/LightningRepoTest.kt | 62 +++++++++++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 944286f81b..000ea263c6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -123,7 +123,8 @@ class SparkRepo @Inject constructor( private val refreshMutex = Mutex() - private val sendsInFlight = ConcurrentHashMap.newKeySet() + /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ + private val sendsInFlight = ConcurrentHashMap() @Volatile private var hasSyncedActivities = false @@ -271,7 +272,9 @@ class SparkRepo @Inject constructor( } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - if (!sendsInFlight.add(paymentHash.lowercase())) throw PaymentPendingException(paymentHash) + if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { + throw PaymentPendingException(paymentHash) + } val sent = try { runSuspendCatching { sparkService.send(prepared) } } finally { @@ -679,10 +682,13 @@ class SparkRepo @Inject constructor( /** * Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it - * again; null when Spark's send failed or none is known. + * again; a send still inside Spark's send call is pending. Null when Spark's send failed or none is known. */ suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = withContext(bgDispatcher) { + sendsInFlight.entries + .firstOrNull { it.value.equals(bolt11, ignoreCase = true) || it.key == paymentHash?.lowercase() } + ?.let { return@withContext EarlierSend.Pending(it.key) } if (!sparkService.isConnected) return@withContext null val send = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index c870bb601b..650c955d24 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1,6 +1,11 @@ package to.bitkit.repositories import app.cash.turbine.test +import breez_sdk_spark.Bolt11InvoiceDetails +import breez_sdk_spark.FeePolicy +import breez_sdk_spark.Payment +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.SendPaymentMethod import com.synonym.bitkitcore.AddressType import com.synonym.bitkitcore.BlocktankException import com.synonym.bitkitcore.FeeRates @@ -91,12 +96,14 @@ import to.bitkit.services.LightningService import to.bitkit.services.LnurlService import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler +import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.test.idleSparkRepo import to.bitkit.utils.AppError import to.bitkit.utils.LdkError import to.bitkit.utils.UrlValidator +import java.math.BigInteger import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -105,6 +112,7 @@ import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Clock import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -1240,6 +1248,60 @@ class LightningRepoTest : BaseUnitTest() { assertIs(retry.exceptionOrNull()) } + @Test + fun `an invoice spark is still sending is not sent again through the node`() = test { + val sparkService = mock() + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val details = mock { on { paymentHash } doReturn "hash" } + val prepared = PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 1uL), + amount = BigInteger.valueOf(1_000), + tokenIdentifier = null, + conversionEstimate = null, + feePolicy = FeePolicy.FEES_EXCLUDED, + ) + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sending = CompletableDeferred() + whenever(sparkService.send(any())).doSuspendableAnswer { sending.await() } + val spark = SparkRepo( + bgDispatcher = testDispatcher, + sparkService = sparkService, + activityRepo = { mock() }, + cacheStore = cacheStore, + contactResolver = { mock() }, + pendingPaymentRepo = PendingPaymentRepo(), + clock = Clock.System, + ) + sut = LightningRepo( + bgDispatcher = testDispatcher, + lightningService = lightningService, + settingsStore = settingsStore, + coreService = coreService, + keychain = keychain, + lnurlService = lnurlService, + cacheStore = cacheStore, + preActivityMetadataRepo = preActivityMetadataRepo, + onchainSendAttemptStore = onchainSendAttemptStore, + connectivityRepo = connectivityRepo, + vssBackupClientLdk = vssBackupClientLdk, + urlValidator = urlValidator, + electrumProbeService = electrumProbeService, + sparkRepo = spark, + ) + startNodeForTesting() + val first = async { spark.payInvoice("bolt11", 1_000uL) } + runCurrent() + verify(sparkService).send(prepared) + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + + val retry = sut.payInvoice("bolt11", 1_000uL) + + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + assertIs(retry.exceptionOrNull()) + first.cancel() + } + @Test fun `spark payment without a fee limit keeps to the node's default one`() = test { startNodeForTesting() From bf734b579f78895865610d3838f8687935bbc3f4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:02:42 +0100 Subject: [PATCH 015/135] fix: hold spark's receive refresh until a restore reads its backup --- .../java/to/bitkit/repositories/BackupRepo.kt | 3 ++ .../java/to/bitkit/repositories/WalletRepo.kt | 4 +- .../bitkit/repositories/LightningRepoTest.kt | 1 + .../to/bitkit/repositories/WalletRepoTest.kt | 40 ++++++++++++++++++- 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 7fdcaac026..e710084160 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -197,6 +197,9 @@ class BackupRepo @Inject constructor( Logger.debug("Set restore pending to '$isPending'", context = TAG) } + /** A restore was announced and its backup is not applied yet. */ + fun isRestoreInProgress(): Boolean = _isRestoring.value || isRestorePending() + suspend fun hasPendingWalletRestore(): Boolean = withContext(ioDispatcher) { keychain.hasPendingWalletRestore() } diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index d988881a95..85b52a7425 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -79,6 +79,7 @@ class WalletRepo @Inject constructor( private val hwWalletRepo: HwWalletRepo, private val connectionRecovery: WalletConnectionRecovery, private val sparkRepo: SparkRepo, + private val backupRepo: BackupRepo, ) { private val repoScope = appScope(bgDispatcher, TAG) @@ -120,7 +121,8 @@ class WalletRepo @Inject constructor( } repoScope.launch { sparkRepo.state.map { it.isReady }.distinctUntilChanged().collect { isReady -> - if (isReady && walletExists()) refreshBip21() + // An address revealed before the restore reads the backup leaves an unused index behind it. + if (isReady && walletExists() && !backupRepo.isRestoreInProgress()) refreshBip21() } } repoScope.launch { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 650c955d24..c5c7fa2473 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -246,6 +246,7 @@ class LightningRepoTest : BaseUnitTest() { hwWalletRepo = hardware, connectionRecovery = connectionRecoveryFixture(settingsStore), sparkRepo = sparkRepo, + backupRepo = mock(), ) } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index c295c767c0..aeb0a50c56 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher @@ -91,6 +92,7 @@ class WalletRepoTest : BaseUnitTest() { private val onchainService = mock() private val activityRepo = mock() private val hwWalletRepo = mock() + private val backupRepo = mock() private val connectionRecovery = connectionRecoveryFixture(settingsStore) companion object Fixtures { @@ -175,6 +177,7 @@ class WalletRepoTest : BaseUnitTest() { private fun createSut( dispatcher: CoroutineDispatcher = testDispatcher, reservationRepo: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + spark: SparkRepo = sparkRepo, ) = WalletRepo( bgDispatcher = dispatcher, keychain = keychain, @@ -190,7 +193,8 @@ class WalletRepoTest : BaseUnitTest() { activityRepo = activityRepo, hwWalletRepo = hwWalletRepo, connectionRecovery = connectionRecovery, - sparkRepo = sparkRepo, + sparkRepo = spark, + backupRepo = backupRepo, ) private fun lightningInvoice(bolt11: String, isExpired: Boolean = false) = LightningInvoice( @@ -205,6 +209,40 @@ class WalletRepoTest : BaseUnitTest() { payeeNodeId = null, ) + @Test + fun `spark becoming ready during a restore reveals no receive address`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + whenever(backupRepo.isRestoreInProgress()).thenReturn(true) + val sparkState = MutableStateFlow(SparkState()) + sut = createSut(spark = sparkRepoWith(sparkState)) + testScheduler.runCurrent() + + sparkState.update { it.copy(isReady = true) } + testScheduler.runCurrent() + + verify(privatePaykitAddressReservationRepo, never()).nextReusableReceiveAddress() + } + + @Test + fun `spark becoming ready outside a restore refreshes the receive address`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + whenever(backupRepo.isRestoreInProgress()).thenReturn(false) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + val sparkState = MutableStateFlow(SparkState()) + sut = createSut(spark = sparkRepoWith(sparkState)) + testScheduler.runCurrent() + + sparkState.update { it.copy(isReady = true) } + testScheduler.runCurrent() + + verify(privatePaykitAddressReservationRepo).nextReusableReceiveAddress() + } + + private fun sparkRepoWith(state: MutableStateFlow): SparkRepo = mock { + on { this.state } doReturn state + on { nodeEvents } doReturn MutableSharedFlow() + } + @Test fun `concurrent cache loads keep receive pending until both complete`() = test { val firstSnapshot = CompletableDeferred() From 4e59bce144e52a5c94885fe716bcaf5ed2359670 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:06:22 +0100 Subject: [PATCH 016/135] fix: retain spark send-all funding receipts --- .../repositories/OnchainSendAttemptStore.kt | 3 +- .../OnchainSendAttemptStoreTest.kt | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt index 7d9f9a5452..b8f9199175 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt @@ -390,7 +390,8 @@ class OnchainSendAttemptStore @Inject constructor( } else { require(current.originalInputs == null && current.candidateTxids.isEmpty() && current.txid == null) require((current.isMaxAmount && current.requestId == null) || receipt.amountSats == current.amountSats) - if (current.isTransfer && current.isMaxAmount) { + // Spark funding has no order, so only a Blocktank send-all is bound to its order's amounts. + if (current.isBlocktankFunding && current.isMaxAmount) { val context = requireNotNull(current.transferContext) val originalFee = requireNotNull(context.originalOrderFeeSats) val miningFee = requireNotNull(receipt.miningFeeSats) diff --git a/app/src/test/java/to/bitkit/repositories/OnchainSendAttemptStoreTest.kt b/app/src/test/java/to/bitkit/repositories/OnchainSendAttemptStoreTest.kt index d87dfb2895..6845c8378b 100644 --- a/app/src/test/java/to/bitkit/repositories/OnchainSendAttemptStoreTest.kt +++ b/app/src/test/java/to/bitkit/repositories/OnchainSendAttemptStoreTest.kt @@ -636,6 +636,50 @@ class OnchainSendAttemptStoreTest : BaseUnitTest() { assertEquals(context, retained.transferContext) } + @Test + fun `spark send-all funding retains its receipt without a transfer context`() = test { + val store = sendAllStore() + val attempt = store.admitSendAllTransfer(orderId = null) + + val retained = store.retainPreparedReceipt(attempt.attemptId, 0, sendAllReceipt, false) + + assertEquals(99_500uL, retained.amountSats) + assertEquals(sendAllReceipt.txid, retained.txid) + } + + @Test + fun `blocktank send-all funding still needs its transfer context to retain a receipt`() = test { + val store = sendAllStore() + val attempt = store.admitSendAllTransfer(orderId = "order-1") + + assertFailsWith { + store.retainPreparedReceipt(attempt.attemptId, 0, sendAllReceipt, false) + } + assertNull(store.current()?.txid) + } + + private val sendAllReceipt = OnchainPreparedReceipt( + "ab".repeat(32), + listOf(OnchainSendInput("11".repeat(32), 0u)), + "bcrt1qfunding", + 99_500uL, + miningFeeSats = 500uL, + ) + + private suspend fun sendAllStore(): OnchainSendAttemptStore { + var saved: String? = null + val keychain = mock() + whenever(keychain.loadString(key, 0)).thenAnswer { saved } + whenever(keychain.upsertString(eq(key), any(), eq(0))).doSuspendableAnswer { saved = it.getArgument(1) } + return OnchainSendAttemptStore(testDispatcher, keychain, mock(), kotlin.time.Clock.System) + } + + private suspend fun OnchainSendAttemptStore.admitSendAllTransfer(orderId: String?) = admit( + walletId = "wallet-1", requestId = null, orderId = orderId, address = sendAllReceipt.address, + amountSats = 99_000uL, isMaxAmount = true, feeRateSatsPerVByte = 1uL, isTransfer = true, + channelId = null, tags = emptyList(), beforeSendAttempt = {}, + ) + @Test fun `transfer balance context is durable before dispatch and survives reopen`() = test { var saved: String? = null From 83356a292546a1a6fcb6140c48e71520ab3116c1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:10:59 +0100 Subject: [PATCH 017/135] fix: resolve payment pending after a spark funding recovery --- .../to/bitkit/repositories/LightningRepo.kt | 8 +++++++ .../repositories/OnchainSendAttemptStore.kt | 4 ++++ .../wallets/send/SendPendingViewModel.kt | 2 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 8 ++++++- .../bitkit/repositories/LightningRepoTest.kt | 15 +++++++++++++ .../wallets/send/SendPendingViewModelTest.kt | 22 +++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 19 ++++++++++++++++ 7 files changed, 76 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 8aa4777e2a..3d77d813fe 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2033,6 +2033,14 @@ class LightningRepo @Inject constructor( } } + /** Hands an accepted Spark funding recovered from Payment Pending to Spark, which claims it once it matures. */ + fun followRecoveredSparkFunding(attempt: OnchainSendAttempt) { + if (!attempt.isSparkFunding || !attempt.hasPositiveEvidence) return + val txid = attempt.txid ?: return + sparkRepo.onDepositBroadcast(txid, attempt.amountSats) + sparkRepo.waitForMatureClaim(txid) + } + // A change signal only: consumers must reread and validate the original attempt. val onchainSendAttemptUpdates get() = onchainSendAttemptStore.backupStateVersion diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt index b8f9199175..18d69c040a 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt @@ -121,6 +121,10 @@ data class OnchainSendAttempt( val highestCandidateFee: ULong get() = maxOf(candidateMiningFees.values.maxOrNull() ?: 0uL, verifiedWinningFeeSats ?: 0uL) + /** A transfer from the node wallet to its Spark deposit address, which pays no order. */ + val isSparkFunding: Boolean + get() = requestId == null && isTransfer && orderId == null + /** A transfer to spending that pays a Blocktank order, which Bitkit no longer buys. */ val isBlocktankFunding: Boolean get() = requestId == null && isTransfer && orderId != null diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt index 719926fadd..f6e6c71921 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt @@ -99,7 +99,7 @@ class SendPendingViewModel @Inject constructor( private fun observeOriginalCompletion(original: OnchainSendAttempt) { // Shop completion has its own proof resolution route. if (original.requestId != null) return - if (original.isTransfer && (original.orderId == null || original.transferContext == null)) return + if (original.isBlocktankFunding && original.transferContext == null) return viewModelScope.launch { lightningRepo.onchainSendAttemptUpdates.collect { runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.onSuccess { current -> diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 117f8a84e5..d9692c5636 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6657,7 +6657,13 @@ class AppViewModel @Inject constructor( val current = lightningRepo.currentOnchainSendAttempt() ?: return@runSuspendCatching if (current != original || !current.isTransfer || current.requestId != null) return@runSuspendCatching if (!current.hasPositiveEvidence || !current.localFollowupComplete) return@runSuspendCatching - if (current.txid == null || current.transferContext == null) return@runSuspendCatching + if (current.txid == null) return@runSuspendCatching + if (current.isSparkFunding) { + lightningRepo.followRecoveredSparkFunding(current) + hideSheet() + return@runSuspendCatching + } + if (current.transferContext == null) return@runSuspendCatching val orderId = current.orderId ?: return@runSuspendCatching hideSheet() mainScreenEffect(MainScreenEffect.Navigate(Routes.OrderDetail(orderId))) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index c5c7fa2473..a2288e9467 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -196,6 +196,21 @@ class LightningRepoTest : BaseUnitTest() { sut.sync() } + @Test + fun `recovered spark funding hands only an accepted spark deposit to spark`() = test { + val txid = "ab".repeat(32) + val funding = pendingSendAttempt().copy(isTransfer = true, txid = txid) + + sut.followRecoveredSparkFunding(funding) + sut.followRecoveredSparkFunding(funding.copy(evidence = OnchainSendEvidence.Observed, orderId = "order")) + verify(sparkRepo, never()).onDepositBroadcast(any(), any()) + + sut.followRecoveredSparkFunding(funding.copy(evidence = OnchainSendEvidence.Observed)) + + verify(sparkRepo).onDepositBroadcast(txid, 1_000uL) + verify(sparkRepo).waitForMatureClaim(txid) + } + @Test fun `node startup failures do not dispatch invoice payment`() = test { var dispatched = false diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModelTest.kt index 4f9e17f804..51b3281cb8 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModelTest.kt @@ -432,6 +432,28 @@ class SendPendingViewModelTest : BaseUnitTest() { org.mockito.kotlin.verify(activityRepo, org.mockito.kotlin.never()).syncActivities() } + @Test + fun `spark funding pending resolves once its accepted recovery completes`() = test { + val original = pendingOriginal().copy(isTransfer = true) + whenever(lightningRepo.currentOnchainSendAttempt()).thenReturn(original) + sut.initOnchain(original.txid, amount) + advanceUntilIdle() + val winner = "cd".repeat(32) + val complete = original.copy( + txid = winner, + candidateTxids = original.candidateTxids + winner, + evidence = OnchainSendEvidence.Observed, + localFollowupComplete = true, + ) + + whenever(lightningRepo.currentOnchainSendAttempt()).thenReturn(complete) + attemptUpdates.value++ + advanceUntilIdle() + + assertEquals(complete, sut.uiState.value.recoveredTransfer) + assertNull(sut.uiState.value.recoveryAttempt) + } + @Test fun `expired Shop payment can be cancelled once the network never saw it`() = test { val original = pendingOriginal().copy( diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3db0c29d29..2dc4232ff4 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -15237,6 +15237,25 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.successSendUiState.value.paymentHashOrTxId) } + @Test + fun `completed original spark funding closes payment pending and hands the deposit to spark`() = test { + val original = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "original-spark-funding", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 1_000uL, + isMaxAmount = false, feeRateSatsPerVByte = 2uL, isTransfer = true, + channelId = null, tags = emptyList(), evidence = OnchainSendEvidence.Observed, + txid = "ab".repeat(32), localFollowupComplete = true, + ) + sut.showPendingTransfer(original.copy(localFollowupComplete = false)) + whenever(lightningRepo.currentOnchainSendAttempt()).thenReturn(original) + + sut.onRecoveredTransfer(original) + advanceUntilIdle() + + assertNull(sut.currentSheet.value) + verify(lightningRepo).followRecoveredSparkFunding(original) + } + @Test fun `retry fee approval works without USD rate and keeps the Bitcoin fee warning`() = test { val original = OnchainSendAttempt( From 23d9b7ce72bd4eb5a2b1c7cf1a9c22eba546aed2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:25:07 +0100 Subject: [PATCH 018/135] fix: pay channel-only savings swaps from the node --- .../to/bitkit/repositories/LightningRepo.kt | 6 ++++++ .../to/bitkit/viewmodels/TransferViewModel.kt | 6 +++--- .../bitkit/repositories/LightningRepoTest.kt | 19 +++++++++++++++++++ .../viewmodels/TransferViewModelTest.kt | 12 ++++++------ 4 files changed, 34 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 3d77d813fe..04b4fbe26b 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1512,6 +1512,12 @@ class LightningRepo @Inject constructor( return payInvoiceWithLdk(bolt11, sats, paymentHash, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) } + /** Pays [bolt11] from the node's channels only, for a send quoted on them that must never fall back to Spark. */ + suspend fun payInvoiceWithNode(bolt11: String): Result { + val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() + return payInvoiceWithLdk(bolt11, null, paymentHash, null, null) { true } + } + private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val send = listPaymentsOrNull()?.firstOrNull { val kind = it.kind as? PaymentKind.Bolt11 ?: return@firstOrNull false diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 769dcd8d1a..42f52f10a7 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -262,9 +262,9 @@ class TransferViewModel @Inject constructor( outcome.complete(awaitSwapClaim(swap.id)) } - // Pay the hold invoice (amount is encoded). It stays pending until Boltz - // locks funds on-chain and we claim them, which is the expected happy path. - val paymentHash = lightningRepo.payInvoice(bolt11 = swap.invoice).getOrThrow() + // Pay the hold invoice (amount is encoded) from the channels it was quoted on, never Spark. + // It stays pending until Boltz locks funds on-chain and we claim them, the expected happy path. + val paymentHash = lightningRepo.payInvoiceWithNode(swap.invoice).getOrThrow() // payInvoice returns as soon as the HTLC is dispatched, and a hold invoice never // settles until Boltz claims, so nothing else notices a payment that fails to route. diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a2288e9467..881b17ffbb 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1162,6 +1162,25 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).payInvoice(eq("invoice"), eq(1_000uL), eq(deadline), eq(10_000uL), any()) } + @Test + fun `a node-only payment fails instead of falling back to spark`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("spark-hash")) + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenAnswer { throw AppError("Route not found") } + // The unrestricted entry picks Spark when the channels cannot carry the amount. + assertEquals("spark-hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + + val result = sut.payInvoiceWithNode("bolt11") + + assertTrue(result.isFailure) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService).send(eq("bolt11"), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun `an earlier spark failure never settles a retry the node is paying`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 7721d6463b..56f97aa3a9 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -373,7 +373,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `onTransferToSavingsConfirm clears the outcome of an earlier swap`() = test { stubSavingsSwapHappyPath() - whenever(lightningRepo.payInvoice(any(), anyOrNull())).thenReturn(Result.failure(AppError(PAY_ERROR))) + whenever(lightningRepo.payInvoiceWithNode(any())).thenReturn(Result.failure(AppError(PAY_ERROR))) sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() sut.startSavingsSwap() @@ -442,7 +442,7 @@ class TransferViewModelTest : BaseUnitTest() { @Test fun `startSavingsSwap fails when the invoice payment fails`() = test { stubSavingsSwapHappyPath() - whenever(lightningRepo.payInvoice(any(), anyOrNull())).thenReturn(Result.failure(AppError(PAY_ERROR))) + whenever(lightningRepo.payInvoiceWithNode(any())).thenReturn(Result.failure(AppError(PAY_ERROR))) sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) advanceUntilIdle() @@ -467,7 +467,7 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(SavingsSwapResult.Success(TXID), sut.savingsSwapResult.value) verify(boltzService).createReverseSwap(any(), any(), anyOrNull(), anyOrNull()) - verify(lightningRepo).payInvoice(any(), anyOrNull()) + verify(lightningRepo).payInvoiceWithNode(any()) } @Test @@ -480,7 +480,7 @@ class TransferViewModelTest : BaseUnitTest() { sut.startSavingsSwap() runCurrent() - // payInvoice returns as soon as the HTLC is dispatched; the routing failure lands later. + // payInvoiceWithNode returns as soon as the HTLC is dispatched; the routing failure lands later. nodeEvents.emit( Event.PaymentFailed( paymentId = PAYMENT_ID, @@ -511,7 +511,7 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(SavingsSwapResult.Success(TXID), sut.savingsSwapResult.value) verify(boltzService).createReverseSwap(any(), any(), anyOrNull(), anyOrNull()) - verify(lightningRepo).payInvoice(any(), anyOrNull()) + verify(lightningRepo).payInvoiceWithNode(any()) } private suspend fun stubSavingsSwapHappyPath() { @@ -520,7 +520,7 @@ class TransferViewModelTest : BaseUnitTest() { whenever(lightningRepo.newAddress()).thenReturn(Result.success(CLAIM_ADDRESS)) whenever(boltzService.createReverseSwap(any(), any(), anyOrNull(), anyOrNull())) .thenReturn(reverseSwapResponse()) - whenever(lightningRepo.payInvoice(any(), anyOrNull())).thenReturn(Result.success(PAYMENT_ID)) + whenever(lightningRepo.payInvoiceWithNode(any())).thenReturn(Result.success(PAYMENT_ID)) } private fun reverseLimits() = BoltzPairInfo( From 85986cde9acf37404c67519b19e8c313fbd28694 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:42:41 +0100 Subject: [PATCH 019/135] fix: fit spark's funds in transfer steps above the buttons --- .../ui/screens/transfer/SettingUpScreen.kt | 80 ++++++++++++++----- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../screens/transfer/SettingUpScreenTest.kt | 62 ++++++++++++++ 18 files changed, 140 insertions(+), 18 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt index 2cfcd3cbfb..4488c3a47a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt @@ -1,7 +1,11 @@ package to.bitkit.ui.screens.transfer import androidx.compose.foundation.Image +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.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable @@ -21,9 +25,11 @@ import kotlinx.collections.immutable.persistentListOf import to.bitkit.R import to.bitkit.models.formatToModernDisplay import to.bitkit.repositories.SparkClaimOffer +import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim import to.bitkit.ui.appViewModel import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.Caption13Up import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton @@ -44,6 +50,9 @@ private const val MATURE_CONFIRMATIONS = 3 /** About how long [MATURE_CONFIRMATIONS] take. */ private const val MATURE_MINUTES = 30 +/** The arrows' share of the illustration, as on iOS, so the inner circle shows around them. */ +private const val FIGURE_FRACTION = 0.85f + @Composable fun SettingUpScreen( viewModel: SparkFundingViewModel, @@ -61,6 +70,7 @@ fun SettingUpScreen( Content( claim = state.claim, + speed = state.speed, onPayClick = viewModel::onPayRepriced, onWaitClick = viewModel::onWait, onContinueClick = onContinueClick, @@ -68,8 +78,9 @@ fun SettingUpScreen( } @Composable -private fun Content( +internal fun Content( claim: SparkDepositClaim, + speed: SparkClaimSpeed = SparkClaimSpeed.Instant, onPayClick: () -> Unit = {}, onWaitClick: () -> Unit = {}, onContinueClick: () -> Unit = {}, @@ -107,6 +118,14 @@ private fun Content( .fillMaxWidth() .testTag("SettingUpText") ) + VerticalSpacer(8.dp) + Caption13Up( + text = speedText(claim, speed), + color = Colors.White64, + modifier = Modifier + .fillMaxWidth() + .testTag("SettingUpSpeed") + ) } else { Display( text = stringResource(R.string.lightning__transfer_success__title_spending) @@ -122,11 +141,19 @@ private fun Content( } VerticalSpacer(28.dp) if (inProgress) { - TransferAnimationView( - largeCircleRes = R.drawable.ln_sync_large, - smallCircleRes = R.drawable.ln_sync_small, - modifier = Modifier.weight(1f) - ) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .weight(1f) + .fillMaxWidth() + ) { + TransferAnimationView( + largeCircleRes = R.drawable.ln_sync_large, + smallCircleRes = R.drawable.ln_sync_small, + contentWidthFraction = FIGURE_FRACTION, + modifier = Modifier.aspectRatio(1f) + ) + } VerticalSpacer(16.dp) val steps = persistentListOf( stringResource(R.string.lightning__setting_up__step_sent), @@ -151,18 +178,26 @@ private fun Content( } if (claim is SparkDepositClaim.Repriced) { - PrimaryButton( - text = stringResource(R.string.lightning__setting_up__pay) - .replace("{amount}", claim.offer.earlyFeeSats.formatToModernDisplay()), - onClick = onPayClick, - modifier = Modifier.testTag("SettingUpPay") - ) - VerticalSpacer(16.dp) - SecondaryButton( - text = stringResource(R.string.lightning__spark_deposit__wait_button), - onClick = onWaitClick, - modifier = Modifier.testTag("SettingUpWait") - ) + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.fillMaxWidth(), + ) { + SecondaryButton( + text = stringResource(R.string.lightning__spark_deposit__wait_button), + onClick = onWaitClick, + modifier = Modifier + .weight(1f) + .testTag("SettingUpWait") + ) + PrimaryButton( + text = stringResource(R.string.lightning__setting_up__pay) + .replace("{amount}", claim.offer.earlyFeeSats.formatToModernDisplay()), + onClick = onPayClick, + modifier = Modifier + .weight(1f) + .testTag("SettingUpPay") + ) + } } else { val randomOkText = localizedRandom(R.string.common__ok_random) PrimaryButton( @@ -191,6 +226,15 @@ private fun claimText(claim: SparkDepositClaim): String = when (claim) { SparkDepositClaim.NotSeen -> stringResource(R.string.lightning__setting_up__not_seen) } +@Composable +private fun speedText(claim: SparkDepositClaim, speed: SparkClaimSpeed): String { + val isLater = speed == SparkClaimSpeed.Later || claim == SparkDepositClaim.Later + return stringResource(R.string.lightning__setting_up__speed).replace( + "{speed}", + stringResource(if (isLater) R.string.common__later else R.string.fee__instant__title), + ) +} + private fun SparkDepositClaim.stepIndex(): Int = when (this) { SparkDepositClaim.Looking, SparkDepositClaim.Later, SparkDepositClaim.NotSeen -> 1 SparkDepositClaim.Adding, is SparkDepositClaim.Repriced, SparkDepositClaim.Unavailable -> 2 diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 884c9fc9e2..b7ce6f09d7 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -213,6 +213,7 @@ لم يرَ Spark تحويلك بعد. يُضاف بعد 3 تأكيدات؛ يمكنك مغادرة هذه الشاشة. ادفع ₿ {amount} أصبح الفوري يكلّف الآن ₿ {amount}. ادفعه، أو انتظر 3 تأكيدات، نحو 30 دقيقة، برسوم أقل. + السرعة: {speed} جارٍ الإضافة إلى الإنفاق رآه 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 b48ccd2eb1..8e0a6f1c0c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -220,6 +220,7 @@ Spark todavía no vio tu transferencia. Se agrega después de 3 confirmaciones; puedes salir de esta pantalla. Pagar ₿ {amount} Instantáneo ahora cuesta ₿ {amount}. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Velocidad: {speed} Agregando a gastos Visto por Spark Transferencia enviada diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index a6b81f34ef..5ebebc2a3f 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -217,6 +217,7 @@ Spark encara no ha vist la teva transferència. S\'afegeix després de 3 confirmacions; pots sortir d\'aquesta pantalla. Paga ₿ {amount} Instant ara costa ₿ {amount}. Paga-ho o espera 3 confirmacions, uns 30 minuts, amb una comissió més baixa. + Velocitat: {speed} Afegint a despesa Vist per Spark Transferència enviada diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 85a6c4da39..9bd4ec1a3a 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -220,6 +220,7 @@ Spark tvůj převod zatím neviděl. Připíše se po 3 potvrzeních; tuto obrazovku můžeš opustit. Zaplatit ₿ {amount} Okamžitě nyní stojí ₿ {amount}. Zaplať, nebo počkej na 3 potvrzení, asi 30 minut, s nižším poplatkem. + Rychlost: {speed} Přidávání do výdajů Viděno Sparkem Převod odeslán diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 4dd1cbce1f..84fa52b953 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -274,6 +274,7 @@ Spark hat deine Überweisung noch nicht gesehen. Sie wird nach 3 Bestätigungen gutgeschrieben; du kannst diesen Bildschirm verlassen. ₿ {amount} zahlen Sofort kostet jetzt ₿ {amount}. Zahle es oder warte auf 3 Bestätigungen, etwa 30 Minuten, zu einer niedrigeren Gebühr. + Geschwindigkeit: {speed} Wird hinzugefügt Von Spark gesehen Überweisung gesendet diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4e8d0cb156..7c979a4962 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -213,6 +213,7 @@ Το Spark δεν έχει δει ακόμα τη μεταφορά σου. Προστίθεται μετά από 3 επιβεβαιώσεις· μπορείς να φύγεις από αυτή την οθόνη. Πλήρωσε ₿ {amount} Το Άμεσα κοστίζει τώρα ₿ {amount}. Πλήρωσέ το ή περίμενε 3 επιβεβαιώσεις, περίπου 30 λεπτά, με χαμηλότερη χρέωση. + Ταχύτητα: {speed} Προσθήκη στις δαπάνες Το είδε το Spark Η μεταφορά στάλθηκε diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index d56725943d..511457521b 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -219,6 +219,7 @@ Spark aún no ha visto su transferencia. Se añade tras 3 confirmaciones; puede salir de esta pantalla. Pagar ₿ {amount} Instantáneo ahora cuesta ₿ {amount}. Páguelo o espere 3 confirmaciones, unos 30 minutos, con una comisión menor. + Velocidad: {speed} Añadiendo a gastos Visto por Spark Transferencia enviada diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 578005eccd..bf2b3e6017 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -161,6 +161,7 @@ Spark aún no ha visto tu transferencia. Se añade tras 3 confirmaciones; puedes salir de esta pantalla. Pagar ₿ {amount} Instantáneo ahora cuesta ₿ {amount}. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Velocidad: {speed} Añadiendo a gastos Visto por Spark Transferencia enviada diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index cabaea5952..8211bd2813 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -191,6 +191,7 @@ Spark n\'a pas encore vu votre transfert. Il est ajouté après 3 confirmations ; vous pouvez quitter cet écran. Payer ₿ {amount} Instantané coûte maintenant ₿ {amount}. Payez-le, ou attendez 3 confirmations, environ 30 minutes, pour des frais moins élevés. + Vitesse : {speed} Ajout aux dépenses Vu par Spark Transfert envoyé diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 89d808a29e..481015d545 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -218,6 +218,7 @@ Spark non ha ancora visto il tuo trasferimento. Viene aggiunto dopo 3 conferme; puoi lasciare questa schermata. Paga ₿ {amount} Istantanea ora costa ₿ {amount}. Pagala, oppure attendi 3 conferme, circa 30 minuti, con una commissione più bassa. + Velocità: {speed} Aggiunta alle spese Visto da Spark Trasferimento inviato diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 281414582b..f21ea608c4 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -217,6 +217,7 @@ Spark heeft je overboeking nog niet gezien. Hij wordt toegevoegd na 3 bevestigingen; je kunt dit scherm verlaten. Betaal ₿ {amount} Direct kost nu ₿ {amount}. Betaal het, of wacht op 3 bevestigingen, ongeveer 30 minuten, tegen lagere kosten. + Snelheid: {speed} Toevoegen aan besteding Gezien door Spark Overboeking verzonden diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 94a329f18a..62ca4274ca 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -275,6 +275,7 @@ Spark jeszcze nie widzi Twojego przelewu. Zostanie dodany po 3 potwierdzeniach; możesz opuścić ten ekran. Zapłać ₿ {amount} Natychmiast kosztuje teraz ₿ {amount}. Zapłać albo poczekaj na 3 potwierdzenia, około 30 minut, z niższą opłatą. + Prędkość: {speed} Dodawanie do wydatków Widziany przez Spark Przelew wysłany diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 7b748be52c..01e0c50a85 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -221,6 +221,7 @@ A Spark ainda não viu sua transferência. Ela é adicionada após 3 confirmações; você pode sair desta tela. Pagar ₿ {amount} Instantâneo agora custa ₿ {amount}. Pague ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa menor. + Velocidade: {speed} Adicionando aos gastos Vista pela Spark Transferência enviada diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 578c642132..8a223b7386 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -265,6 +265,7 @@ A Spark ainda não viu a sua transferência. É adicionada após 3 confirmações; pode sair deste ecrã. Pagar ₿ {amount} Instantâneo custa agora ₿ {amount}. Pague-o ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa mais baixa. + Velocidade: {speed} A adicionar aos gastos Vista pela Spark Transferência enviada diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index f8335a037d..daeaeec298 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -229,6 +229,7 @@ Spark ещё не увидел ваш перевод. Он будет зачислен после 3 подтверждений; можно покинуть этот экран. Оплатить ₿ {amount} Мгновенно теперь стоит ₿ {amount}. Оплатите или дождитесь 3 подтверждений, около 30 минут, с меньшей комиссией. + Скорость: {speed} Зачисление на расходы Виден Spark Перевод отправлен diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c6d3ba8621..1ea260b5f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -378,6 +378,7 @@ Spark hasn\'t seen your transfer yet. It\'s added after 3 confirmations; you can leave this screen. Pay ₿ {amount} Instant now costs ₿ {amount}. Pay it, or wait for 3 confirmations, about 30 minutes, at a lower fee. + Speed: {speed} Adding To Spending Seen By Spark Transfer Sent diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt new file mode 100644 index 0000000000..272164f663 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt @@ -0,0 +1,62 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.repositories.SparkClaimOffer +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.repositories.SparkDepositClaim +import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertTrue + +@Config(sdk = [34], qualifiers = "w320dp-h568dp") +@RunWith(RobolectricTestRunner::class) +class SettingUpScreenTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `repriced steps and their label sit above the side by side buttons on a small screen`() { + setContent(repriced, SparkClaimSpeed.Instant) + + val label = composeRule.onNodeWithText("Adding To Spending").getUnclippedBoundsInRoot() + val wait = composeRule.onNodeWithTag("SettingUpWait").getUnclippedBoundsInRoot() + val pay = composeRule.onNodeWithTag("SettingUpPay").getUnclippedBoundsInRoot() + + assertTrue(label.bottom <= wait.top) + assertTrue(wait.top == pay.top && wait.right < pay.left) + composeRule.onNodeWithText("SPEED: INSTANT").assertExists() + } + + @Test + fun `later steps and their label sit above the button on a small screen`() { + setContent(SparkDepositClaim.Later, SparkClaimSpeed.Instant) + + val label = composeRule.onNodeWithText("Seen By Spark").getUnclippedBoundsInRoot() + val button = composeRule.onNodeWithTag("TransferSuccess-button").getUnclippedBoundsInRoot() + + assertTrue(label.bottom <= button.top) + composeRule.onNodeWithText("SPEED: LATER").assertExists() + } + + private fun setContent(claim: SparkDepositClaim, speed: SparkClaimSpeed) { + composeRule.setContent { AppThemeSurface { Content(claim = claim, speed = speed) } } + } + + private val repriced = SparkDepositClaim.Repriced( + SparkClaimOffer.Choice( + txid = "txid", + vout = 0u, + earlyFeeSats = 1_850uL, + earlyConfirmations = 0u, + standardFeeSats = 198uL, + standardConfirmations = 3u, + ) + ) +} From d5297dd897fc37379e69713b15ab80483b1cadae Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 13:12:12 +0100 Subject: [PATCH 020/135] fix: open the hardware transfer from funding when spark is ready --- app/src/main/java/to/bitkit/ui/ContentView.kt | 13 +++++ .../ui/screens/transfer/FundingScreen.kt | 4 +- .../test/java/to/bitkit/ui/ContentViewTest.kt | 12 +++++ .../ui/screens/transfer/FundingScreenTest.kt | 51 +++++++++++++++++++ 4 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index ee82fb0e95..08de2e42d1 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -66,6 +66,7 @@ import to.bitkit.appwidget.appWidgetRefreshScheduler import to.bitkit.env.Env import to.bitkit.ext.rawId import to.bitkit.ext.walletId +import to.bitkit.models.HwWalletBalance import to.bitkit.models.NodeLifecycleState import to.bitkit.models.Toast import to.bitkit.repositories.ConnectivityState @@ -1107,6 +1108,7 @@ private fun RootNavHost( } deepLinkableComposable { val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + val balances = LocalBalances.current val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() FundingScreen( canFundWithSpark = sparkState.isReady, @@ -1119,6 +1121,11 @@ private fun RootNavHost( } }, onManual = { navController.navigateTo(Routes.ExternalNav) }, + onHardware = { + fundingHardwareRoute(balances.hardwareWallets, hasSeenSpendingIntro) + ?.let { navController.navigateTo(it) } + ?: appViewModel.showSheet(Sheet.Hardware()) + }, onBackClick = { navController.popBackStack() }, ) } @@ -2303,6 +2310,12 @@ internal fun transferSpendingStartRoute(hasSeenSpendingIntro: Boolean): Routes = fun NavController.navigateToTransferSpendingStart(hasSeenSpendingIntro: Boolean, walletId: String) = navigateTo(transferSpendingStartRoute(hasSeenSpendingIntro, walletId)) +/** Where Funding's hardware row starts Transfer to Spending, from a funded wallet first; null when none is paired. */ +internal fun fundingHardwareRoute(wallets: List, hasSeenSpendingIntro: Boolean): Routes? { + val wallet = wallets.firstOrNull { it.sats > 0uL } ?: wallets.firstOrNull() ?: return null + return transferSpendingStartRoute(hasSeenSpendingIntro, wallet.id) +} + internal fun transferSpendingStartRoute(hasSeenSpendingIntro: Boolean, walletId: String): Routes = when { hasSeenSpendingIntro -> Routes.SpendingAmountHw(walletId) else -> Routes.SpendingIntroHw(walletId) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt index 8af2625d6c..22326e6974 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt @@ -43,6 +43,7 @@ fun FundingScreen( onTransfer: () -> Unit = {}, onFund: () -> Unit = {}, onManual: () -> Unit = {}, + onHardware: () -> Unit = {}, onBackClick: () -> Unit = {}, ) { val context = LocalContext.current @@ -113,7 +114,8 @@ fun FundingScreen( R.string.lightning__funding__button_hw, R.drawable.ic_device_tablet_speaker, 16.25.dp, - "FundHardware" + "FundHardware", + onHardware.takeIf { canFundWithSpark }, ) if (!canFundWithSpark) { FundingOption(R.string.lightning__funding__button2, R.drawable.ic_qr_purple, 13.75.dp, "FundReceive") diff --git a/app/src/test/java/to/bitkit/ui/ContentViewTest.kt b/app/src/test/java/to/bitkit/ui/ContentViewTest.kt index 5adcaec1dd..079b6637d6 100644 --- a/app/src/test/java/to/bitkit/ui/ContentViewTest.kt +++ b/app/src/test/java/to/bitkit/ui/ContentViewTest.kt @@ -17,6 +17,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import to.bitkit.models.HwWalletBalance import to.bitkit.models.NodeLifecycleState import to.bitkit.ui.components.Sheet import to.bitkit.ui.components.navigateIfNotCurrent @@ -284,6 +285,17 @@ class ContentViewTest { assertEquals(Routes.SpendingAmountHw(walletId), transferSpendingStartRoute(true, walletId)) } + @Test + fun `funding hardware row opens the funded wallet transfer or pairing without a wallet`() { + assertNull(fundingHardwareRoute(emptyList(), hasSeenSpendingIntro = true)) + val wallets = listOf(HwWalletBalance("empty", 0uL), HwWalletBalance("funded", 5_000uL)) + + assertEquals(Routes.SpendingAmountHw("funded"), fundingHardwareRoute(wallets, hasSeenSpendingIntro = true)) + assertEquals(Routes.SpendingIntroHw("funded"), fundingHardwareRoute(wallets, hasSeenSpendingIntro = false)) + val unfunded = wallets.take(1) + assertEquals(Routes.SpendingAmountHw("empty"), fundingHardwareRoute(unfunded, hasSeenSpendingIntro = true)) + } + @Test fun `setting up removes spending confirmation from the back stack`() { val navController = transferNavController() diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt new file mode 100644 index 0000000000..ea5989604a --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt @@ -0,0 +1,51 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +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.ui.theme.AppThemeSurface +import kotlin.test.assertEquals +import kotlin.time.Duration.Companion.seconds +import kotlin.time.toJavaDuration + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class FundingScreenTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `hardware row opens the hardware transfer once spark is ready`() { + var clicks = 0 + composeRule.setContent { + AppThemeSurface { FundingScreen(canFundWithSpark = true, onHardware = { clicks++ }) } + } + ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) + + composeRule.onNodeWithTag("FundHardware").performScrollTo().assertIsEnabled().performClick() + + assertEquals(1, clicks) + } + + @Test + fun `hardware row stays disabled while spark is not ready`() { + var clicks = 0 + composeRule.setContent { + AppThemeSurface { FundingScreen(canFundWithSpark = false, onHardware = { clicks++ }) } + } + ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) + + composeRule.onNodeWithTag("FundHardware").performScrollTo().assertIsNotEnabled().performClick() + + assertEquals(0, clicks) + } +} From 136566ad4ed7625baba238a4d93dcd5c758938c8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 13:31:31 +0100 Subject: [PATCH 021/135] fix: hold node sends while spark's history is unreadable --- .../main/java/to/bitkit/data/CacheStore.kt | 12 +++++ .../java/to/bitkit/repositories/SparkRepo.kt | 22 +++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 49 +++++++++++++++++++ 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 1c55b18947..04de389271 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -22,6 +22,9 @@ import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton +/** How many Spark send hashes to keep; an older send's invoice has long expired, so the node cannot pay it again. */ +private const val MAX_SPARK_SEND_HASHES = 100 + private val Context.appCacheDataStore: DataStore by dataStore( fileName = "app_cache.json", serializer = AppCacheSerializer @@ -136,6 +139,13 @@ class CacheStore internal constructor( store.updateData { it.copy(pendingLightningMessages = it.pendingLightningMessages - paymentHash) } } + suspend fun addSparkSendHash(paymentHash: String) { + val hash = paymentHash.lowercase() + store.updateData { + it.copy(sparkSendHashes = (it.sparkSendHashes - hash + hash).takeLast(MAX_SPARK_SEND_HASHES)) + } + } + suspend fun setBackgroundReceive(details: NewTransactionSheetDetails) = store.updateData { it.copy(backgroundReceive = details) } @@ -169,6 +179,8 @@ data class AppCacheData( val quickPayLedger: QuickPayLedger? = null, /** LNURL-pay comments by payment hash, kept until the sent payment's activity stores them. */ val pendingLightningMessages: Map = mapOf(), + /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ + val sparkSendHashes: List = listOf(), ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 000ea263c6..645f71bf7d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -276,6 +276,7 @@ class SparkRepo @Inject constructor( throw PaymentPendingException(paymentHash) } val sent = try { + cacheStore.addSparkSendHash(paymentHash) runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) @@ -683,17 +684,23 @@ class SparkRepo @Inject constructor( /** * Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it * again; a send still inside Spark's send call is pending. Null when Spark's send failed or none is known. + * While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live. */ suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = withContext(bgDispatcher) { sendsInFlight.entries .firstOrNull { it.value.equals(bolt11, ignoreCase = true) || it.key == paymentHash?.lowercase() } ?.let { return@withContext EarlierSend.Pending(it.key) } - if (!sparkService.isConnected) return@withContext null - val send = runSuspendCatching { sparkService.listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .getOrNull() - ?.latestSend { + val payments = if (sparkService.isConnected) { + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrNull() + } else { + null + } + if (payments == null) return@withContext startedSend(paymentHash)?.let { EarlierSend.Pending(it) } + val send = payments + .latestSend { it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } @@ -706,6 +713,11 @@ class SparkRepo @Inject constructor( } } + private suspend fun startedSend(paymentHash: String?): String? { + val hash = paymentHash?.lowercase() ?: return null + return hash.takeIf { it in cacheStore.data.first().sparkSendHashes } + } + private fun List.latestSend(paymentHash: String): Payment? = latestSend { it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0f652000d0..42cb2b8b0d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -44,10 +44,12 @@ import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore @@ -162,6 +164,53 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), earlier) } + @Test + fun `an unreadable history holds the node off an invoice spark started sending`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever(sparkService.isConnected).thenReturn(false) + val sut = createSut() + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "HASH")) + + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenAnswer { throw IllegalStateException("offline") } + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `an unreadable history lets the node pay an invoice spark never sent`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("other")) + whenever(sparkService.isConnected).thenReturn(false) + + assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `a readable history without a live attempt lets the node pay a recorded invoice`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + + assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `a spark send is recorded before it goes out`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + + createSut().payInvoice("lnbc1280n1send", 128uL).getOrThrow() + + inOrder(cacheStore, sparkService) { + verifyBlocking(cacheStore) { addSparkSendHash("hash") } + verifyBlocking(sparkService) { send(any()) } + } + } + @Test fun `records a send's fee once a sync reports it`() = test { whenever(sparkService.isConnected).thenReturn(true) From 1a8dff0feea94faaf60547cdaeb8282e8c1f3dc8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:29:17 +0100 Subject: [PATCH 022/135] fix: back up spark's exit data once per connection --- .../java/to/bitkit/repositories/BackupRepo.kt | 24 +++++++++++----- .../to/bitkit/repositories/BackupRepoTest.kt | 28 +++++++++++++++++++ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index e710084160..b30be8f246 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -23,6 +23,7 @@ import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge +import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @@ -166,6 +167,10 @@ class BackupRepo @Inject constructor( private var isObserving = false private var lastNotificationTime = 0L + /** Spark's current connection was backed up once ready, so a restart of the observers doesn't upload it again. */ + @Volatile + private var hasBackedUpSparkConnection = false + private val _isRestoring = MutableStateFlow(false) val isRestoring: StateFlow = _isRestoring.asStateFlow() @@ -180,7 +185,10 @@ class BackupRepo @Inject constructor( vssBackupClientLdk.reset() } - fun setWiping(isWiping: Boolean) = _isWiping.update { isWiping } + fun setWiping(isWiping: Boolean) { + if (isWiping) hasBackedUpSparkConnection = false + _isWiping.update { isWiping } + } /** * Holds ordinary uploads from the moment a restore is announced, closing the window between the @@ -442,15 +450,17 @@ class BackupRepo @Inject constructor( // payment and sync traffic does not re-upload the whole metadata envelope. dataListenerJobs.add(observeBackupChanges(activityRepo.activityTagsChanged, BackupCategory.METADATA)) - // SPARK_EXIT - back up once Spark is ready and synced, which replays when observing starts after that, - // and again whenever Spark announces its unilateral exit data changed + // SPARK_EXIT - back up once per Spark connection when it is ready and synced, even if observing starts after + // that, and again whenever Spark announces its unilateral exit data changed dataListenerJobs.add( scope.launch { - merge( - sparkRepo.state.map { it.isReady && it.hasSynced }.distinctUntilChanged().filter { it }, - sparkRepo.exitStateChanged, - ).collect { + val isReady = sparkRepo.state.map { it.isReady && it.hasSynced }.distinctUntilChanged() + .onEach { if (!it) hasBackedUpSparkConnection = false } + .filter { it } + merge(isReady, sparkRepo.exitStateChanged.map { false }).collect { isReadyTrigger -> + if (isReadyTrigger && hasBackedUpSparkConnection) return@collect if (shouldSkipBackup()) return@collect + if (isReadyTrigger) hasBackedUpSparkConnection = true markBackupRequired(BackupCategory.SPARK_EXIT) } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 0c7c1bf375..09276b9e50 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -305,6 +305,34 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `spark exit backup does not upload again when observing restarts on foreground`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() + sut.stopObservingBackups() + + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() + + verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `spark exit backup defers, without uploading, until Spark has connected and synced`() = test { whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) From 384bf125b39cbc991609a590e7a9312024f118cb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:36:07 +0100 Subject: [PATCH 023/135] fix: leave the funding flow after a spark funding recovery --- app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 2 ++ .../java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index d9692c5636..86c10e1b35 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6661,6 +6661,8 @@ class AppViewModel @Inject constructor( if (current.isSparkFunding) { lightningRepo.followRecoveredSparkFunding(current) hideSheet() + // Leave the funding flow, whose confirm screen would offer the sent transfer again. + mainScreenEffect(MainScreenEffect.Navigate(Routes.Home, clearStack = true)) return@runSuspendCatching } if (current.transferContext == null) return@runSuspendCatching diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 2dc4232ff4..1a208c67f7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -15249,9 +15249,12 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.showPendingTransfer(original.copy(localFollowupComplete = false)) whenever(lightningRepo.currentOnchainSendAttempt()).thenReturn(original) - sut.onRecoveredTransfer(original) - advanceUntilIdle() + sut.mainScreenEffect.test { + sut.onRecoveredTransfer(original) + advanceUntilIdle() + assertEquals(MainScreenEffect.Navigate(Routes.Home, clearStack = true), expectMostRecentItem()) + } assertNull(sut.currentSheet.value) verify(lightningRepo).followRecoveredSparkFunding(original) } From de16298e3ca5c7653d084611d7e4264dd4674db0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:36:08 +0100 Subject: [PATCH 024/135] test: let the amount change journey keep two inputs at the shown fee --- journeys/transfer/spending-confirm-amount-change.xml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/journeys/transfer/spending-confirm-amount-change.xml b/journeys/transfer/spending-confirm-amount-change.xml index 5343ebb898..26356d3d8b 100644 --- a/journeys/transfer/spending-confirm-amount-change.xml +++ b/journeys/transfer/spending-confirm-amount-change.xml @@ -7,9 +7,10 @@ the next swipe pays them. The higher-total case needs a spend of the wallet's own UTXO outside the app, or a fee rate rise, which the Capabilities table does not list, so unit tests and a manual test cover it. - The amount changes through coin selection: Spending Confirm sizes the network fee for two inputs, - then a larger UTXO confirms before the swipe, so the transfer priced at swipe spends one input and - pays a lower network fee, at once. + A larger UTXO confirms while Spending Confirm is open, so the transfer is priced at swipe against a + changed wallet. Coin selection may keep two inputs (150 000 + 150 000, or 150 000 + 500 000) at the + same fee, or spend the new UTXO alone at a lower fee; either way the fresh price costs no more than the + one shown, so the swipe pays at once. Precondition: a freshly onboarded dev wallet with Spark connected on its regtest, no channel and exactly two confirmed on-chain UTXOs of 150 000 sats each (two ./lsp deposits to the wallet's @@ -28,6 +29,6 @@ Verify the confirm screen still shows the amounts noted before the deposit Swipe the "Swipe To Transfer" handle (testTag "GRAB") fully to the right Verify no "Fees changed" toast appears and the setting up screen (testTag "LightningSettingUp") opens within 90s - Tap "Continue Using Bitkit" (testTag "TransferSuccess-button"), open the newest transfer in the activity list and verify its fee is lower than the "Network Fees" amount noted + Tap "Continue Using Bitkit" (testTag "TransferSuccess-button"), open the newest transfer in the activity list and verify its fee is no higher than the "Network Fees" amount noted From 4e894e46c41c19fbd4786c706e61872fc0d0b8bd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:44:21 +0100 Subject: [PATCH 025/135] fix: release spark send records spark reports failed --- .../main/java/to/bitkit/data/CacheStore.kt | 6 +++ .../java/to/bitkit/repositories/SparkRepo.kt | 5 +++ .../to/bitkit/repositories/SparkRepoTest.kt | 38 +++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 04de389271..9c62249d0e 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -146,6 +146,12 @@ class CacheStore internal constructor( } } + suspend fun removeSparkSendHash(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash !in store.data.first().sparkSendHashes) return + store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes - hash) } + } + suspend fun setBackgroundReceive(details: NewTransactionSheetDetails) = store.updateData { it.copy(backgroundReceive = details) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 645f71bf7d..a08e073d1d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -306,6 +306,7 @@ class SparkRepo @Inject constructor( .onSuccess { _state.update { it.copy(hasSynced = true) } } when (val send = lightningSend(paymentHash)) { SparkLightningSend.NotFound -> { + cacheStore.removeSparkSendHash(paymentHash) val reason = PaymentFailureReason.UNEXPECTED_ERROR _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, reason)) return@launch @@ -313,6 +314,7 @@ class SparkRepo @Inject constructor( // A pending send ends with its own payment event. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@launch is SparkLightningSend.Found -> { + if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } return@launch } @@ -779,6 +781,9 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) + val failedSend = (payment.details as? PaymentDetails.Lightning) + ?.takeIf { payment.paymentType == SparkPaymentType.SEND && payment.status == PaymentStatus.FAILED } + failedSend?.let { cacheStore.removeSparkSendHash(it.htlcDetails.paymentHash) } payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 42cb2b8b0d..b6a59e15e4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -30,7 +30,9 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import org.junit.Before @@ -211,6 +213,42 @@ class SparkRepoTest : BaseUnitTest() { } } + @Test + fun `a send spark failed is not held from the node while spark is disconnected`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever { cacheStore.removeSparkSendHash(any()) }.thenAnswer { call -> + cacheData.update { it.copy(sparkSendHashes = it.sparkSendHashes - call.getArgument(0)) } + } + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + + sparkEvents.emit(SdkEvent.PaymentFailed(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + whenever(sparkService.isConnected).thenReturn(false) + + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `an uncertain send spark never recorded is no longer held from the node`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever { cacheStore.removeSparkSendHash(any()) }.thenAnswer { call -> + cacheData.update { it.copy(sparkSendHashes = it.sparkSendHashes - call.getArgument(0)) } + } + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw IllegalStateException("lost") } + val sut = createSut() + + assertIs(sut.payInvoice("lnbc1280n1send", 128uL).exceptionOrNull()) + advanceTimeBy(15_000) + runCurrent() + whenever(sparkService.isConnected).thenReturn(false) + + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + @Test fun `records a send's fee once a sync reports it`() = test { whenever(sparkService.isConnected).thenReturn(true) From 19e15b2d17c3d3ed8fc7d959ad2cc9c6907ce616 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:01:37 +0100 Subject: [PATCH 026/135] fix: keep the speed fee on one line in spending confirm --- .../screens/transfer/SpendingConfirmScreen.kt | 9 +-- .../screens/transfer/SpendingSpeedRowsTest.kt | 55 +++++++++++++++++++ 2 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SpendingSpeedRowsTest.kt 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 546b4d1bf8..4de87cc6fa 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 @@ -51,7 +51,6 @@ import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.Display import to.bitkit.ui.components.FeeInfo -import to.bitkit.ui.components.FillWidth import to.bitkit.ui.components.HorizontalSpacer import to.bitkit.ui.components.MoneySSB import to.bitkit.ui.components.PrimaryButton @@ -307,7 +306,8 @@ private fun SpeedItem( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(horizontal = 16.dp) - .height(72.dp) + .heightIn(min = 72.dp) + .padding(vertical = 8.dp) ) { Icon( painter = painterResource(icon), @@ -316,12 +316,13 @@ private fun SpeedItem( modifier = Modifier.size(32.dp), ) HorizontalSpacer(16.dp) - Column { + // The text wraps, so the fee keeps its one line at the end of the row. + Column(modifier = Modifier.weight(1f)) { BodyMSB(title, color = MaterialTheme.colorScheme.primary) BodySSB(description, color = MaterialTheme.colorScheme.secondary) } - FillWidth() if (feeSats != null) { + HorizontalSpacer(8.dp) Row { BodySSB("$feePrefix ", color = Colors.White64) MoneySSB(sats = feeSats, showSymbol = true) diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingSpeedRowsTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingSpeedRowsTest.kt new file mode 100644 index 0000000000..683dbd5ce6 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingSpeedRowsTest.kt @@ -0,0 +1,55 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.height +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.annotation.GraphicsMode +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.ui.screens.transfer.SparkFundingContract.Quote +import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [34], qualifiers = "w412dp-h915dp-xxhdpi") +@RunWith(RobolectricTestRunner::class) +class SpendingSpeedRowsTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `the later fee fits inside its row on a narrow screen`() { + val quote = Quote( + address = "bcrt1q", + amountSats = 50_000, + networkFeeSats = 577, + instantFeeSats = 1_350, + laterFeeSats = 99, + spendableSats = 158_234, + ) + composeRule.setContent { + // Inspection mode formats amounts without the currency view model, as previews do. + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { SpendingSpeedRows(quote = quote, speed = SparkClaimSpeed.Later, onSpeedChange = {}) } + } + } + + val row = composeRule.onNodeWithTag("SpendingConfirmLater").getUnclippedBoundsInRoot() + val laterFee = composeRule.onNodeWithText("99", substring = true, useUnmergedTree = true) + .getUnclippedBoundsInRoot() + val instantFee = composeRule.onNodeWithText("350", substring = true, useUnmergedTree = true) + .getUnclippedBoundsInRoot() + + assertTrue(laterFee.right <= row.right, "fee ends at ${laterFee.right}, row at ${row.right}") + assertEquals(instantFee.height.value, laterFee.height.value, 0.5f, "the later fee wraps to a second line") + } +} From 09eac5b03b694362ef4ddc7a4fd7a628a32fbc62 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:33:08 +0100 Subject: [PATCH 027/135] fix: release spark sends that failed while the app was closed --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index a08e073d1d..fbb7b2e219 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -781,9 +781,6 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) - val failedSend = (payment.details as? PaymentDetails.Lightning) - ?.takeIf { payment.paymentType == SparkPaymentType.SEND && payment.status == PaymentStatus.FAILED } - failedSend?.let { cacheStore.removeSparkSendHash(it.htlcDetails.paymentHash) } payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } @@ -793,6 +790,10 @@ class SparkRepo @Inject constructor( return } val id = lightning.htlcDetails.paymentHash + // A failed send no longer holds the node off its invoice, also when it failed while the app was closed. + if (payment.paymentType == SparkPaymentType.SEND && payment.status == PaymentStatus.FAILED) { + cacheStore.removeSparkSendHash(id) + } val existing = (activityRepo.get().getActivity(id).getOrNull() as? Activity.Lightning)?.v1 val activity = LightningActivity.create( id = id, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b6a59e15e4..b45ef8cfcd 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -229,6 +229,23 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a send that failed while the app was closed is released when spark syncs on start`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever { cacheStore.removeSparkSendHash(any()) }.thenAnswer { call -> + cacheData.update { it.copy(sparkSendHashes = it.sparkSendHashes - call.getArgument(0)) } + } + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val sut = createSut() + + sut.start(0).getOrThrow() + whenever(sparkService.isConnected).thenReturn(false) + + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + @Test fun `an uncertain send spark never recorded is no longer held from the node`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) From 9f44c5bec39804b6494785288c934c5e26bc3845 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:35:28 +0100 Subject: [PATCH 028/135] fix: leave spending confirm once a kept spark funding completes --- .../screens/transfer/SparkFundingViewModel.kt | 44 ++++++++++++++----- .../transfer/SparkFundingViewModelTest.kt | 40 +++++++++++++++++ 2 files changed, 74 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 5a662be52c..534270a864 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 @@ -15,6 +15,8 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -79,6 +81,7 @@ class SparkFundingViewModel @Inject constructor( private var maxJob: Job? = null private var quoteJob: Job? = null + private var retainedFundingJob: Job? = null /** The fee rates the shown quote was priced at, so the transfer pays exactly what the screen shows. */ private var quotedFeeRates: FeeRates? = null @@ -297,24 +300,18 @@ class SparkFundingViewModel @Inject constructor( ).getOrThrow() if (outcome !is OnchainSendOutcome.Accepted) { Logger.warn("Spark funding was not accepted: '$outcome'", context = TAG) - if (showRetainedFunding()) return@runSuspendCatching + if (showRetainedFunding(quote)) return@runSuspendCatching error("Spark funding was not accepted: '$outcome'") } withContext(NonCancellable) { runSuspendCatching { lightningRepo.completeAcceptedTransferFollowup(orderId = null, txid = outcome.txid) }.onFailure { Logger.warn("Failed to finish Spark funding locally", it, context = TAG) } - sparkRepo.onDepositBroadcast(outcome.txid, outcome.amountSats ?: quote.amountSats.toULong()) - sparkRepo.followDepositClaim(outcome.txid, state.speed, quote.instantFeeSats.toULong()) } - Logger.info("Funded Spark with '${quote.amountSats}' sats in '${outcome.txid}'", context = TAG) - _uiState.update { - it.copy(txid = outcome.txid, claim = sparkRepo.depositClaims.value[outcome.txid] ?: it.claim) - } - _effects.emit(SideEffect.Sent) + onFundingAccepted(outcome.txid, outcome.amountSats ?: quote.amountSats.toULong(), quote) }.onFailure { Logger.error("Failed to fund Spark", it, context = TAG) - if (it is OnchainSendBlockedError && showRetainedFunding()) return@onFailure + if (it is OnchainSendBlockedError && showRetainedFunding(quote)) return@onFailure toast( title = R.string.lightning__close_error, description = context.getString(R.string.wallet__send_error_create_tx), @@ -323,14 +320,41 @@ class SparkFundingViewModel @Inject constructor( _uiState.update { it.copy(isSending = false) } } + private suspend fun onFundingAccepted(txid: String, amountSats: ULong, quote: Quote) { + val speed = _uiState.value.speed + withContext(NonCancellable) { + sparkRepo.onDepositBroadcast(txid, amountSats) + sparkRepo.followDepositClaim(txid, speed, quote.instantFeeSats.toULong()) + } + Logger.info("Funded Spark with '$amountSats' sats in '$txid'", context = TAG) + _uiState.update { it.copy(txid = txid, claim = sparkRepo.depositClaims.value[txid] ?: it.claim) } + _effects.emit(SideEffect.Sent) + } + // A signed funding that was not accepted is kept; Payment Pending shows it and retries it at a new fee. - private suspend fun showRetainedFunding(): Boolean { + private suspend fun showRetainedFunding(quote: Quote): Boolean { val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() if (attempt == null || !attempt.isTransfer || !attempt.blocksNextSend) return false + watchRetainedFunding(attempt, quote) _effects.emit(SideEffect.FundingPending(attempt)) return true } + // Payment Pending can be dismissed, so the confirm screen leaves for Setting Up once the kept funding completes. + private fun watchRetainedFunding(retained: OnchainSendAttempt, quote: Quote) { + retainedFundingJob?.cancel() + retainedFundingJob = viewModelScope.launch { + val completed = lightningRepo.onchainSendAttemptUpdates + .map { runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() } + .filterNotNull() + .first { + it.attemptId == retained.attemptId && it.address == quote.address && + it.hasPositiveEvidence && it.localFollowupComplete && it.txid != null + } + onFundingAccepted(requireNotNull(completed.txid), completed.amountSats, quote) + } + } + fun onPayRepriced() { val txid = _uiState.value.txid ?: return sparkRepo.payRepricedClaim(txid) 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 713db8c2bf..b659a8af9e 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 @@ -49,6 +49,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { private val currencyRepo = mock() private val hwWalletRepo = mock() private val feeRates = FeeRates(fast = 5u, mid = 3u, slow = 1u) + private val attemptUpdates = MutableStateFlow(0L) private fun createSut() = SparkFundingViewModel(context, walletRepo, lightningRepo, sparkRepo, currencyRepo, hwWalletRepo) @@ -61,6 +62,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { whenever(context.getString(R.string.lightning__spending_amount__error_balance__title)).thenReturn("Short") whenever(walletRepo.balanceState).thenReturn(MutableStateFlow(BalanceState(maxSendOnchainSats = 100_000u))) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) + whenever(lightningRepo.onchainSendAttemptUpdates).thenReturn(attemptUpdates) whenever(currencyRepo.currencyState).thenReturn(MutableStateFlow(CurrencyState())) whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(emptyMap())) whenever { sparkRepo.depositAddress() }.thenReturn(Result.success("bcrt1qspark")) @@ -226,6 +228,44 @@ class SparkFundingViewModelTest : BaseUnitTest() { verify(sparkRepo, never()).onDepositBroadcast(any(), any()) } + @Test + fun `a retained funding that completes later leaves the confirm screen for setting up`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) + val retained = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "attempt", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(retained) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + val effects = mutableListOf() + backgroundScope.launch { sut.effects.collect { effects += it } } + sut.onConfirm() + advanceUntilIdle() + + val confirmed = retained.copy(evidence = OnchainSendEvidence.Observed, localFollowupComplete = true) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(confirmed) + attemptUpdates.value++ + advanceUntilIdle() + + assertEquals(SideEffect.Sent, effects.last()) + assertEquals("txid", sut.uiState.value.txid) + verify(sparkRepo).onDepositBroadcast("txid", 50_000uL) + verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Instant, 1_350uL) + } + @Test fun `hardware transfer prices from the device and hands signing a transfer request`() = test { whenever { hwWalletRepo.maxSpendableFunding("trezor", "bcrt1qspark", 5uL) }.thenReturn(Result.success(80_000uL)) From 8dee16786f0bbbf157d59273caed5daf7b44475e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:32:24 +0100 Subject: [PATCH 029/135] fix: keep a spark send held while its retry is live --- .../java/to/bitkit/repositories/SparkRepo.kt | 22 ++++++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 19 ++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index fbb7b2e219..2436468dc4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -749,9 +749,19 @@ class SparkRepo @Inject constructor( } private suspend fun syncActivities() { - sparkService.listPayments().forEach { recordActivity(it) } + val payments = sparkService.listPayments() + payments.forEach { recordActivity(it) } + // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a + // retry of it is still live. + payments.mapNotNull { it.failedSendHash() }.distinct() + .filter { payments.latestSend(it)?.status == PaymentStatus.FAILED } + .forEach { cacheStore.removeSparkSendHash(it) } } + private fun Payment.failedSendHash(): String? = (details as? PaymentDetails.Lightning) + ?.takeIf { paymentType == SparkPaymentType.SEND && status == PaymentStatus.FAILED } + ?.htlcDetails?.paymentHash + private suspend fun onSdkEvent(event: SdkEvent) { runSuspendCatching { when (event) { @@ -781,6 +791,12 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) + payment.failedSendHash()?.let { hash -> + val latest = lightningSend(hash) + val isReleased = latest == SparkLightningSend.NotFound || + (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED + if (isReleased) cacheStore.removeSparkSendHash(hash) + } payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } @@ -790,10 +806,6 @@ class SparkRepo @Inject constructor( return } val id = lightning.htlcDetails.paymentHash - // A failed send no longer holds the node off its invoice, also when it failed while the app was closed. - if (payment.paymentType == SparkPaymentType.SEND && payment.status == PaymentStatus.FAILED) { - cacheStore.removeSparkSendHash(id) - } val existing = (activityRepo.get().getActivity(id).getOrNull() as? Activity.Lightning)?.v1 val activity = LightningActivity.create( id = id, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b45ef8cfcd..14a3d0bd17 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -246,6 +246,25 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a failed send does not release a hash its retry still holds pending`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever { cacheStore.removeSparkSendHash(any()) }.thenAnswer { call -> + cacheData.update { it.copy(sparkSendHashes = it.sparkSendHashes - call.getArgument(0)) } + } + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(id = "first", status = PaymentStatus.FAILED) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed, retry)) + val sut = createSut() + + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + whenever(sparkService.isConnected).thenReturn(false) + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + @Test fun `an uncertain send spark never recorded is no longer held from the node`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) From fa02b812457253ac1e092c02e1ed306fd176a072 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:35:56 +0100 Subject: [PATCH 030/135] fix: keep the funding screen's claim speed on a recovered funding --- .../java/to/bitkit/repositories/LightningRepo.kt | 3 ++- .../to/bitkit/repositories/LightningRepoTest.kt | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 04b4fbe26b..4105a5c34f 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2044,7 +2044,8 @@ class LightningRepo @Inject constructor( if (!attempt.isSparkFunding || !attempt.hasPositiveEvidence) return val txid = attempt.txid ?: return sparkRepo.onDepositBroadcast(txid, attempt.amountSats) - sparkRepo.waitForMatureClaim(txid) + // The funding screen may already follow the claim at the speed the user chose. + if (sparkRepo.depositClaims.value[txid] == null) sparkRepo.waitForMatureClaim(txid) } // A change signal only: consumers must reread and validate the original attempt. diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 881b17ffbb..1f4667c032 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -200,6 +200,7 @@ class LightningRepoTest : BaseUnitTest() { fun `recovered spark funding hands only an accepted spark deposit to spark`() = test { val txid = "ab".repeat(32) val funding = pendingSendAttempt().copy(isTransfer = true, txid = txid) + whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(emptyMap())) sut.followRecoveredSparkFunding(funding) sut.followRecoveredSparkFunding(funding.copy(evidence = OnchainSendEvidence.Observed, orderId = "order")) @@ -211,6 +212,18 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).waitForMatureClaim(txid) } + @Test + fun `a recovered spark funding keeps the claim the funding screen chose`() = test { + val txid = "ab".repeat(32) + val funding = pendingSendAttempt().copy(isTransfer = true, txid = txid, evidence = OnchainSendEvidence.Observed) + whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(mapOf(txid to SparkDepositClaim.Looking))) + + sut.followRecoveredSparkFunding(funding) + + verify(sparkRepo).onDepositBroadcast(txid, 1_000uL) + verify(sparkRepo, never()).waitForMatureClaim(any()) + } + @Test fun `node startup failures do not dispatch invoice payment`() = test { var dispatched = false From 439d163f93d5a5e9ed37f5406a7f3502b341bf8b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:42:24 +0100 Subject: [PATCH 031/135] fix: read spark's sends in quickpay's payment lookup --- app/src/main/java/to/bitkit/di/RepoModule.kt | 37 +++++++++++- .../java/to/bitkit/repositories/SparkRepo.kt | 20 +++++++ .../to/bitkit/di/QuickPayPaymentLookupTest.kt | 60 +++++++++++++++++++ 3 files changed, 115 insertions(+), 2 deletions(-) create mode 100644 app/src/test/java/to/bitkit/di/QuickPayPaymentLookupTest.kt diff --git a/app/src/main/java/to/bitkit/di/RepoModule.kt b/app/src/main/java/to/bitkit/di/RepoModule.kt index f08456fec0..fe4c64cd40 100644 --- a/app/src/main/java/to/bitkit/di/RepoModule.kt +++ b/app/src/main/java/to/bitkit/di/RepoModule.kt @@ -12,7 +12,9 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.QuickPayInvoiceParser import to.bitkit.repositories.QuickPayPaymentLookup import to.bitkit.repositories.QuickPayReconcileRow +import to.bitkit.repositories.SparkRepo import javax.inject.Named +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus @Module @InstallIn(SingletonComponent::class) @@ -33,8 +35,39 @@ abstract class RepoModule { runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() } + /** + * Payments of both rails, one row per invoice for a payment either rail made, so an older failed channel + * attempt never settles one a Spark retry still holds or paid. Null while either rail can't list them. + */ @Provides - fun provideQuickPayPaymentLookup(lightningRepo: LightningRepo): QuickPayPaymentLookup = - QuickPayPaymentLookup { lightningRepo.listPaymentsOrNull()?.map { QuickPayReconcileRow(it) } } + fun provideQuickPayPaymentLookup(lightningRepo: LightningRepo, sparkRepo: SparkRepo): QuickPayPaymentLookup = + QuickPayPaymentLookup { + val node = lightningRepo.listPaymentsOrNull()?.map { QuickPayReconcileRow(it) } + ?: return@QuickPayPaymentLookup null + val spark = sparkRepo.lightningSendStatuses() ?: return@QuickPayPaymentLookup null + val sparkRows = spark.map { (hash, status) -> + QuickPayReconcileRow( + paymentId = hash, + invoicePaymentHash = hash, + isOutboundBolt11 = true, + status = when (status) { + SparkPaymentStatus.COMPLETED -> QuickPayReconcileRow.Status.SUCCEEDED + SparkPaymentStatus.PENDING -> QuickPayReconcileRow.Status.PENDING + SparkPaymentStatus.FAILED -> QuickPayReconcileRow.Status.FAILED + }, + ) + } + val (sends, others) = (node + sparkRows).partition { it.isOutboundBolt11 } + others + sends.groupBy { it.invoicePaymentHash }.values.map { rows -> + rows.maxBy { SETTLING_STATUSES.indexOf(it.status) } + } + } + + /** The order in which an outcome settles a payment both rails attempted, the last one winning. */ + private val SETTLING_STATUSES = listOf( + QuickPayReconcileRow.Status.FAILED, + QuickPayReconcileRow.Status.PENDING, + QuickPayReconcileRow.Status.SUCCEEDED, + ) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2436468dc4..7f0f330b4b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -667,6 +667,26 @@ class SparkRepo @Inject constructor( fun canListPayments(): Boolean = !sparkService.isSupported || (sparkService.isConnected && _state.value.hasSynced) + /** + * The status that settles each of Spark's Lightning sends, by payment hash; empty where Spark is unsupported and + * null while it can't list its payments, so a send it may hold is never read as one it never made. + */ + suspend fun lightningSendStatuses(): Map? = withContext(bgDispatcher) { + if (!sparkService.isSupported) return@withContext emptyMap() + if (!canListPayments()) return@withContext null + val payments = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrElse { return@withContext null } + payments + .mapNotNull { payment -> + (payment.details as? PaymentDetails.Lightning) + ?.takeIf { payment.paymentType == SparkPaymentType.SEND } + ?.htlcDetails?.paymentHash + } + .distinct() + .associateWith { hash -> requireNotNull(payments.latestSend(hash)).status } + } + /** * Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. * [SparkLightningSend.Unavailable] while Spark is supported but cannot list its payments, so a send it may hold diff --git a/app/src/test/java/to/bitkit/di/QuickPayPaymentLookupTest.kt b/app/src/test/java/to/bitkit/di/QuickPayPaymentLookupTest.kt new file mode 100644 index 0000000000..bddf4a6969 --- /dev/null +++ b/app/src/test/java/to/bitkit/di/QuickPayPaymentLookupTest.kt @@ -0,0 +1,60 @@ +package to.bitkit.di + +import org.junit.Test +import org.lightningdevkit.ldknode.PaymentDetails +import org.lightningdevkit.ldknode.PaymentDirection +import org.lightningdevkit.ldknode.PaymentKind +import org.lightningdevkit.ldknode.PaymentStatus +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.QuickPayReconcileRow +import to.bitkit.repositories.SparkRepo +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals +import kotlin.test.assertNull +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus + +class QuickPayPaymentLookupTest : BaseUnitTest() { + private val lightningRepo = mock() + private val sparkRepo = mock() + private val lookup = RepoModule.provideQuickPayPaymentLookup(lightningRepo, sparkRepo) + + @Test + fun `a spark retry still pending outranks an older failed channel attempt`() = test { + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(nodeSend(PaymentStatus.FAILED))) + whenever(sparkRepo.lightningSendStatuses()).thenReturn(mapOf("hash" to SparkPaymentStatus.PENDING)) + + val row = lookup.rows()?.single { it.invoicePaymentHash == "hash" } + + assertEquals(QuickPayReconcileRow.Status.PENDING, row?.status) + } + + @Test + fun `a spark send that paid settles the payment the channel failed`() = test { + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(nodeSend(PaymentStatus.FAILED))) + whenever(sparkRepo.lightningSendStatuses()).thenReturn(mapOf("hash" to SparkPaymentStatus.COMPLETED)) + + val row = lookup.rows()?.single { it.invoicePaymentHash == "hash" } + + assertEquals(QuickPayReconcileRow.Status.SUCCEEDED, row?.status) + } + + @Test + fun `the lookup is unavailable while spark cannot list its payments`() = test { + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(listOf(nodeSend(PaymentStatus.FAILED))) + whenever(sparkRepo.lightningSendStatuses()).thenReturn(null) + + assertNull(lookup.rows()) + } + + private fun nodeSend(status: PaymentStatus) = PaymentDetails( + id = "hash", + kind = PaymentKind.Bolt11(hash = "hash", preimage = null, secret = null, description = null, bolt11 = "bolt11"), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = status, + latestUpdateTimestamp = 0uL, + ) +} From fd854d3e4f3ecdb62edef0cdb5810b3b3958026d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:48:37 +0100 Subject: [PATCH 032/135] fix: keep a payment's note when spark replays its activity --- .../java/to/bitkit/repositories/SparkRepo.kt | 3 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7f0f330b4b..f8d2642e54 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -842,7 +842,8 @@ class SparkRepo @Inject constructor( invoice = lightning.invoice, timestamp = payment.timestamp, fee = payment.fees.toLong().toULong(), - message = lightning.description.orEmpty(), + // A note stored on the activity, such as an LNURL comment, outlives the invoice's description. + message = existing?.message?.takeIf { it.isNotEmpty() } ?: lightning.description.orEmpty(), preimage = lightning.htlcDetails.preimage, contact = existing?.contact ?: receivedContact(payment, id), seenAt = existing?.seenAt, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 14a3d0bd17..89fdf69989 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -24,7 +24,9 @@ import breez_sdk_spark.SendPaymentMethod import breez_sdk_spark.SparkHtlcDetails import breez_sdk_spark.SparkHtlcStatus import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaymentState import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async @@ -285,6 +287,30 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `replaying a send keeps the payment note stored on its activity`() = test { + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.SUCCEEDED, message = "for coffee")))) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + whenever(sparkService.isConnected).thenReturn(true) + + createSut().start(0).getOrThrow() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("for coffee", (activity.firstValue as Activity.Lightning).v1.message) + } + + private fun storedSend(status: PaymentState, message: String = "") = LightningActivity.create( + id = "hash", + txType = ActivityPaymentType.SENT, + status = status, + value = 128uL, + invoice = "lnbc1280n1send", + timestamp = 1uL, + message = message, + ) + @Test fun `records a send's fee once a sync reports it`() = test { whenever(sparkService.isConnected).thenReturn(true) From a88a943a15d5b26a808b34d5c44e04ef267d1e15 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:51:15 +0100 Subject: [PATCH 033/135] fix: never downgrade a paid activity on a spark replay --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 2 ++ .../java/to/bitkit/repositories/SparkRepoTest.kt | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f8d2642e54..400dead27b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -827,6 +827,8 @@ class SparkRepo @Inject constructor( } val id = lightning.htlcDetails.paymentHash val existing = (activityRepo.get().getActivity(id).getOrNull() as? Activity.Lightning)?.v1 + // Another attempt of the same invoice, on either rail, already paid it. + if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return val activity = LightningActivity.create( id = id, txType = when (payment.paymentType) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 89fdf69989..03d3d57576 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -301,6 +301,19 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("for coffee", (activity.firstValue as Activity.Lightning).v1.message) } + @Test + fun `replaying a failed spark attempt never downgrades a payment that succeeded`() = test { + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.SUCCEEDED)))) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + whenever(sparkService.isConnected).thenReturn(true) + + createSut().start(0).getOrThrow() + + verify(activityRepo, never()).upsertActivity(any()) + } + private fun storedSend(status: PaymentState, message: String = "") = LightningActivity.create( id = "hash", txType = ActivityPaymentType.SENT, From aa61e5b83b20c8c84b18d4836376e1bf9eeff1c6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:56:36 +0100 Subject: [PATCH 034/135] fix: let the open funding screen own a kept spark funding --- .../to/bitkit/repositories/LightningRepo.kt | 10 ++++++++ .../screens/transfer/SparkFundingViewModel.kt | 3 ++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 ++++ .../transfer/SparkFundingViewModelTest.kt | 5 ++++ .../viewmodels/AppViewModelSendFlowTest.kt | 23 +++++++++++++++++++ 5 files changed, 45 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 4105a5c34f..b684309637 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2039,6 +2039,16 @@ class LightningRepo @Inject constructor( } } + private val fundingsFollowedOnScreen = ConcurrentHashMap.newKeySet() + + /** The funding screen settles the kept Spark funding [attemptId] itself while it stays open. */ + fun followFundingOnScreen(attemptId: String, isFollowed: Boolean) { + if (isFollowed) fundingsFollowedOnScreen.add(attemptId) else fundingsFollowedOnScreen.remove(attemptId) + } + + /** Whether the funding screen settles the kept Spark funding [attemptId], so its recovery leaves it alone. */ + fun isFundingFollowedOnScreen(attemptId: String): Boolean = attemptId in fundingsFollowedOnScreen + /** Hands an accepted Spark funding recovered from Payment Pending to Spark, which claims it once it matures. */ fun followRecoveredSparkFunding(attempt: OnchainSendAttempt) { if (!attempt.isSparkFunding || !attempt.hasPositiveEvidence) return 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 534270a864..134d447507 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 @@ -343,6 +343,7 @@ class SparkFundingViewModel @Inject constructor( // Payment Pending can be dismissed, so the confirm screen leaves for Setting Up once the kept funding completes. private fun watchRetainedFunding(retained: OnchainSendAttempt, quote: Quote) { retainedFundingJob?.cancel() + lightningRepo.followFundingOnScreen(retained.attemptId, isFollowed = true) retainedFundingJob = viewModelScope.launch { val completed = lightningRepo.onchainSendAttemptUpdates .map { runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() } @@ -352,7 +353,7 @@ class SparkFundingViewModel @Inject constructor( it.hasPositiveEvidence && it.localFollowupComplete && it.txid != null } onFundingAccepted(requireNotNull(completed.txid), completed.amountSats, quote) - } + }.apply { invokeOnCompletion { lightningRepo.followFundingOnScreen(retained.attemptId, isFollowed = false) } } } fun onPayRepriced() { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 86c10e1b35..496409d329 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6658,6 +6658,11 @@ class AppViewModel @Inject constructor( if (current != original || !current.isTransfer || current.requestId != null) return@runSuspendCatching if (!current.hasPositiveEvidence || !current.localFollowupComplete) return@runSuspendCatching if (current.txid == null) return@runSuspendCatching + if (current.isSparkFunding && lightningRepo.isFundingFollowedOnScreen(current.attemptId)) { + // The open funding screen settles it at the speed the user chose and moves on to Setting Up. + hideSheet() + return@runSuspendCatching + } if (current.isSparkFunding) { lightningRepo.followRecoveredSparkFunding(current) hideSheet() 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 b659a8af9e..1f0860c002 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 @@ -13,6 +13,7 @@ import org.lightningdevkit.ldknode.BalanceDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify @@ -264,6 +265,10 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals("txid", sut.uiState.value.txid) verify(sparkRepo).onDepositBroadcast("txid", 50_000uL) verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Instant, 1_350uL) + inOrder(lightningRepo) { + verify(lightningRepo).followFundingOnScreen("attempt", true) + verify(lightningRepo).followFundingOnScreen("attempt", false) + } } @Test diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 1a208c67f7..827c5fb255 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -15259,6 +15259,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo).followRecoveredSparkFunding(original) } + @Test + fun `a recovered spark funding the funding screen settles only closes payment pending`() = test { + val original = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "original-spark-funding", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 1_000uL, + isMaxAmount = false, feeRateSatsPerVByte = 2uL, isTransfer = true, + channelId = null, tags = emptyList(), evidence = OnchainSendEvidence.Observed, + txid = "ab".repeat(32), localFollowupComplete = true, + ) + sut.showPendingTransfer(original.copy(localFollowupComplete = false)) + whenever(lightningRepo.currentOnchainSendAttempt()).thenReturn(original) + whenever(lightningRepo.isFundingFollowedOnScreen("original-spark-funding")).thenReturn(true) + + sut.mainScreenEffect.test { + sut.onRecoveredTransfer(original) + advanceUntilIdle() + + expectNoEvents() + } + assertNull(sut.currentSheet.value) + verify(lightningRepo, never()).followRecoveredSparkFunding(any()) + } + @Test fun `retry fee approval works without USD rate and keeps the Bitcoin fee warning`() = test { val original = OnchainSendAttempt( From aaafd920281abbea729a156478cd93688ca094e4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:59:02 +0100 Subject: [PATCH 035/135] fix: show the later speed when spark adds a transfer at 3 confirmations --- .../bitkit/ui/screens/transfer/SettingUpScreen.kt | 4 +++- .../ui/screens/transfer/SettingUpScreenTest.kt | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt index 4488c3a47a..9fbe7512af 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt @@ -228,7 +228,9 @@ private fun claimText(claim: SparkDepositClaim): String = when (claim) { @Composable private fun speedText(claim: SparkDepositClaim, speed: SparkClaimSpeed): String { - val isLater = speed == SparkClaimSpeed.Later || claim == SparkDepositClaim.Later + // Unavailable and not seen add the transfer after 3 confirmations, whatever speed the user chose. + val isLater = speed == SparkClaimSpeed.Later || claim == SparkDepositClaim.Later || + claim == SparkDepositClaim.Unavailable || claim == SparkDepositClaim.NotSeen return stringResource(R.string.lightning__setting_up__speed).replace( "{speed}", stringResource(if (isLater) R.string.common__later else R.string.fee__instant__title), diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt index 272164f663..083ab13329 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt @@ -45,6 +45,20 @@ class SettingUpScreenTest { composeRule.onNodeWithText("SPEED: LATER").assertExists() } + @Test + fun `a transfer added after 3 confirmations shows the later speed`() { + setContent(SparkDepositClaim.Unavailable, SparkClaimSpeed.Instant) + + composeRule.onNodeWithText("SPEED: LATER").assertExists() + } + + @Test + fun `a transfer spark has not seen yet shows the later speed`() { + setContent(SparkDepositClaim.NotSeen, SparkClaimSpeed.Instant) + + composeRule.onNodeWithText("SPEED: LATER").assertExists() + } + private fun setContent(claim: SparkDepositClaim, speed: SparkClaimSpeed) { composeRule.setContent { AppThemeSurface { Content(claim = claim, speed = speed) } } } From 767f0eb0e4d7494ffc1a7a8d49ce424eb8fc1d4f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:04:29 +0100 Subject: [PATCH 036/135] fix: refuse a sub-sat withdrawal spark can't invoice exactly --- .../to/bitkit/repositories/LightningRepo.kt | 10 +++++++- .../bitkit/repositories/LightningRepoTest.kt | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index b684309637..d615ffbb63 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1359,9 +1359,13 @@ class LightningRepo @Inject constructor( expirySeconds: UInt = Defaults.bolt11ExpirySec, ): Result = executeWhenNodeRunning("createInvoiceMsats") { requireWalletRestoreComplete() - // Spark invoices hold whole sats, so a sub-sat part rounds up rather than dropping the amount. + // An LNURL withdrawal is paid at exactly this amount, which a whole-sat Spark invoice can't hold unless it + // has no sub-sat part; the channels take such an amount when they can, else it is refused before the callback. val amountSats = (amountMsats.safe() + (MSATS_PER_SAT - 1uL).safe()) / MSATS_PER_SAT if (shouldReceiveWithSpark(amountSats)) { + if (amountMsats % MSATS_PER_SAT != 0uL) { + return@executeWhenNodeRunning Result.failure(SubSatAmountUnsupportedError(amountMsats)) + } val invoiceSats = amountSats.takeIf { it > 0uL } return@executeWhenNodeRunning sparkRepo.createInvoice(invoiceSats, description, expirySeconds) } @@ -3083,3 +3087,7 @@ sealed interface EarlierSend { data class Paid(override val paymentHash: String) : EarlierSend } + +/** Spark invoices hold whole sats, so an exact msat amount the channels can't receive has nowhere to go. */ +class SubSatAmountUnsupportedError(amountMsats: ULong) : + AppError("Spark can only receive whole sats, not '$amountMsats' msat, and the channels can't receive it") diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 1f4667c032..bd8edd8d4f 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -224,6 +224,29 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo, never()).waitForMatureClaim(any()) } + @Test + fun `a sub-sat withdrawal amount never gets a spark invoice for a different amount`() = test { + startNodeForTesting() + whenever(sparkRepo.canReceive()).thenReturn(true) + + for (amountMsats in listOf(222_538uL, 999uL)) { + assertIs(sut.createInvoiceMsats(amountMsats, "withdraw").exceptionOrNull()) + } + + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + @Test + fun `a whole-sat withdrawal amount is received on spark at its exact amount`() = test { + startNodeForTesting() + whenever(sparkRepo.canReceive()).thenReturn(true) + whenever(sparkRepo.createInvoice(anyOrNull(), any(), any())).thenReturn(Result.success("spark-invoice")) + + assertEquals("spark-invoice", sut.createInvoiceMsats(222_000uL, "withdraw").getOrThrow()) + + verify(sparkRepo).createInvoice(eq(222uL), eq("withdraw"), any()) + } + @Test fun `node startup failures do not dispatch invoice payment`() = test { var dispatched = false From a180df6dfae58e11350038978afac6685881535a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:33:52 +0100 Subject: [PATCH 037/135] fix: reconcile quickpay again once spark syncs --- .../to/bitkit/repositories/QuickPayRepo.kt | 3 ++ .../bitkit/repositories/QuickPayRepoTest.kt | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 13fd893b07..0e0e6c61fb 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch @@ -82,6 +83,8 @@ class QuickPayRepo @Inject constructor( if (running) reconcileAgainstLdk() } } + // The lookup waits for Spark's history, so a first Spark sync after the node's runs the reconcile again. + scope.launch { lightningRepo.isSparkSynced.filter { it }.collect { reconcileAgainstLdk() } } } fun attach(session: QuickPaySession): Flow { diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 13d6899a51..5a49472076 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -35,7 +35,9 @@ import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.di.json import to.bitkit.models.ConvertedAmount +import to.bitkit.models.NodeLifecycleState import to.bitkit.models.QuickPayLedger +import to.bitkit.models.QuickPayLedgerRecord import to.bitkit.models.QuickPayRecordPhase import to.bitkit.models.USD import to.bitkit.test.BaseUnitTest @@ -112,6 +114,7 @@ class QuickPayRepoTest : BaseUnitTest() { SettingsData(isQuickPayEnabled = true, quickPayAmount = 5, quickPayDailyLimitMultiplier = 5), ) private val lightningState = MutableStateFlow(LightningState()) + private val sparkSynced = MutableStateFlow(false) private var paymentRows: List? = null private lateinit var sut: QuickPayRepo @@ -121,6 +124,7 @@ class QuickPayRepoTest : BaseUnitTest() { paymentRows = null whenever(settingsStore.data).thenReturn(settingsData) whenever(lightningRepo.lightningState).thenReturn(lightningState) + whenever(lightningRepo.isSparkSynced).thenReturn(sparkSynced) whenever { lightningRepo.listPaymentsOrNull() }.thenReturn(null) whenever(currencyRepo.convertFiatToSats(5.0, USD)).thenAnswer { 1000uL } whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())).thenAnswer { invocation -> @@ -471,6 +475,41 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(QuickPayRecordPhase.SUBMITTING, ledger.records.last().phase) } + @Test + fun `a payment the node failed is released once spark syncs after the node`() = test { + cacheStore.update { + it.copy( + quickPayLedger = QuickPayLedger( + version = 1, + dayKey = "2026-08-15", + spentCents = 250L, + records = listOf( + QuickPayLedgerRecord( + id = "rec", + amountCents = 250L, + dayKey = "2026-08-15", + invoicePaymentHash = "inv", + paymentId = "pid", + phase = QuickPayRecordPhase.SUBMITTED, + ), + ), + ), + ) + } + sut = repo() + lightningState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + runCurrent() + lightningState.value = lightningState.value.copy(lastSuccessfulSyncAt = 1L) + runCurrent() + assertEquals(250L, spentCents()) + + paymentRows = listOf(failedRow("inv")) + sparkSynced.value = true + runCurrent() + + assertEquals(0L, spentCents()) + } + @Test fun `unsupported ledger version does not wipe unrelated cache`() = test { cacheStore.update { From 984a21b632571cdc9b42ab220d70deb0de6f5984 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:41:03 +0100 Subject: [PATCH 038/135] fix: keep a kept spark funding owned until the funding screen closes --- .../screens/transfer/SparkFundingViewModel.kt | 13 ++++- .../transfer/SparkFundingViewModelTest.kt | 50 +++++++++++++++++-- 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 134d447507..ec49cd75ff 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 @@ -83,6 +83,9 @@ class SparkFundingViewModel @Inject constructor( private var quoteJob: Job? = null private var retainedFundingJob: Job? = null + /** The kept funding this screen settles, held until the screen closes so its recovery never takes over. */ + private var ownedFundingAttemptId: String? = null + /** The fee rates the shown quote was priced at, so the transfer pays exactly what the screen shows. */ private var quotedFeeRates: FeeRates? = null @@ -343,6 +346,9 @@ class SparkFundingViewModel @Inject constructor( // Payment Pending can be dismissed, so the confirm screen leaves for Setting Up once the kept funding completes. private fun watchRetainedFunding(retained: OnchainSendAttempt, quote: Quote) { retainedFundingJob?.cancel() + ownedFundingAttemptId?.takeIf { it != retained.attemptId } + ?.let { lightningRepo.followFundingOnScreen(it, isFollowed = false) } + ownedFundingAttemptId = retained.attemptId lightningRepo.followFundingOnScreen(retained.attemptId, isFollowed = true) retainedFundingJob = viewModelScope.launch { val completed = lightningRepo.onchainSendAttemptUpdates @@ -353,7 +359,12 @@ class SparkFundingViewModel @Inject constructor( it.hasPositiveEvidence && it.localFollowupComplete && it.txid != null } onFundingAccepted(requireNotNull(completed.txid), completed.amountSats, quote) - }.apply { invokeOnCompletion { lightningRepo.followFundingOnScreen(retained.attemptId, isFollowed = false) } } + } + } + + override fun onCleared() { + ownedFundingAttemptId?.let { lightningRepo.followFundingOnScreen(it, isFollowed = false) } + super.onCleared() } fun onPayRepriced() { 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 1f0860c002..c56261594e 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 @@ -1,6 +1,10 @@ package to.bitkit.ui.screens.transfer import android.content.Context +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory import com.synonym.bitkitcore.FeeRates import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow @@ -13,7 +17,6 @@ import org.lightningdevkit.ldknode.BalanceDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq -import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify @@ -265,10 +268,47 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals("txid", sut.uiState.value.txid) verify(sparkRepo).onDepositBroadcast("txid", 50_000uL) verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Instant, 1_350uL) - inOrder(lightningRepo) { - verify(lightningRepo).followFundingOnScreen("attempt", true) - verify(lightningRepo).followFundingOnScreen("attempt", false) - } + verify(lightningRepo).followFundingOnScreen("attempt", true) + verify(lightningRepo, never()).followFundingOnScreen("attempt", false) + } + + @Test + fun `the funding screen owns a kept funding until it closes`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) + val retained = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "attempt", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(retained) + val store = ViewModelStore() + val sut = ViewModelProvider.create( + store, + viewModelFactory { initializer { createSut() } }, + )[SparkFundingViewModel::class] + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + sut.onConfirm() + advanceUntilIdle() + whenever { lightningRepo.currentOnchainSendAttempt() } + .thenReturn(retained.copy(evidence = OnchainSendEvidence.Observed, localFollowupComplete = true)) + attemptUpdates.value++ + advanceUntilIdle() + verify(lightningRepo, never()).followFundingOnScreen("attempt", false) + + store.clear() + + verify(lightningRepo).followFundingOnScreen("attempt", false) } @Test From 7b7bdc01052f1d43a6b42f63fd76b67d0286587a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:41:04 +0100 Subject: [PATCH 039/135] fix: hold a spark retry that starts during the activity sync --- .../java/to/bitkit/repositories/SparkRepo.kt | 8 +++++- .../to/bitkit/repositories/SparkRepoTest.kt | 26 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 400dead27b..f7420d21f1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -773,8 +773,14 @@ class SparkRepo @Inject constructor( payments.forEach { recordActivity(it) } // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a // retry of it is still live. - payments.mapNotNull { it.failedSendHash() }.distinct() + val failed = payments.mapNotNull { it.failedSendHash() }.distinct() .filter { payments.latestSend(it)?.status == PaymentStatus.FAILED } + if (failed.isEmpty()) return + // A retry can start while the list is recorded, so the release reads Spark's sends again first. + val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return + failed + .filter { !sendsInFlight.containsKey(it.lowercase()) } + .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } .forEach { cacheStore.removeSparkSendHash(it) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 03d3d57576..1bdc32639f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -267,6 +267,32 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a retry spark is still sending keeps its hash held through the activity sync`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever { cacheStore.removeSparkSendHash(any()) }.thenAnswer { call -> + cacheData.update { it.copy(sparkSendHashes = it.sparkSendHashes - call.getArgument(0)) } + } + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sending = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { + sending.await() + sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) + } + val sut = createSut() + backgroundScope.launch { sut.payInvoice("lnbc1280n1send", 128uL) } + runCurrent() + + sut.start(0).getOrThrow() + + assertTrue("hash" in cacheData.value.sparkSendHashes) + sending.complete(Unit) + } + @Test fun `an uncertain send spark never recorded is no longer held from the node`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) From 665641e241badb505c1d439a112284cc629a8655 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:17:53 +0100 Subject: [PATCH 040/135] fix: drop the empty super call in spark funding --- .../java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt | 1 - 1 file changed, 1 deletion(-) 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 ec49cd75ff..af4d5df413 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 @@ -364,7 +364,6 @@ class SparkFundingViewModel @Inject constructor( override fun onCleared() { ownedFundingAttemptId?.let { lightningRepo.followFundingOnScreen(it, isFollowed = false) } - super.onCleared() } fun onPayRepriced() { From f811bcaab6c9bbfa0b381cb79be231aa917cd7c0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:44:03 +0100 Subject: [PATCH 041/135] fix: keep a pending spark retry over the channel's older failure --- .../java/to/bitkit/services/CoreService.kt | 6 ++++++ .../ActivityServiceLightningMessageTest.kt | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index 0aba45fd82..c1659c419d 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -886,6 +886,12 @@ class ActivityService( ) { return } + // A newer pending attempt, such as a Spark retry, stays until it settles; an older failure can't end it. + if (existingActivity is Activity.Lightning && existingActivity.v1.status == PaymentState.PENDING && + state == PaymentState.FAILED && (existingActivity.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp + ) { + return + } if (existingActivity is Activity.Lightning) { val statusChanging = existingActivity.v1.status != state val needsPrivateContactAttribution = existingActivity.v1.contact == null && diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt index a03424ee6c..4d169f862d 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt @@ -108,6 +108,27 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { assertEquals(PaymentState.SUCCEEDED, stored.status) } + @Test + fun `payment sync keeps a newer pending spark retry over the channel's earlier failure`() = coreTest { + val retry = sent(status = PaymentState.PENDING, message = "").copy(timestamp = 300uL, updatedAt = 300uL) + row = Activity.Lightning(retry) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + + sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) + + assertEquals(PaymentState.PENDING, (row as Activity.Lightning).v1.status) + } + + @Test + fun `payment sync still fails the node's own earlier pending attempt`() = coreTest { + row = Activity.Lightning(sent(status = PaymentState.PENDING, message = "")) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + + sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) + + assertEquals(PaymentState.FAILED, (row as Activity.Lightning).v1.status) + } + private fun coreTest(block: suspend () -> Unit) = test { ServiceQueue.CORE.background { mockStatic(Class.forName(BITKIT_CORE_FFI_CLASS)).use { native -> From ecf9e533d1657fd9c55474b1f5d3d6c3c214680f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:44:04 +0100 Subject: [PATCH 042/135] fix: hold node retries until spark's history has synced --- .../java/to/bitkit/repositories/SparkRepo.kt | 3 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 18 ++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f7420d21f1..02a88b7f4c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -713,7 +713,8 @@ class SparkRepo @Inject constructor( sendsInFlight.entries .firstOrNull { it.value.equals(bolt11, ignoreCase = true) || it.key == paymentHash?.lowercase() } ?.let { return@withContext EarlierSend.Pending(it.key) } - val payments = if (sparkService.isConnected) { + // Before Spark's first sync its local list can be empty although a restored send is live. + val payments = if (sparkService.isSupported && canListPayments()) { runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 1bdc32639f..487abd4e47 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -163,7 +163,10 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 2).copy(status = PaymentStatus.PENDING))) - val earlier = createSut().earlierLightningSend("lnbc1280n1send", null) + val sut = createSut() + sut.start(0).getOrThrow() + + val earlier = sut.earlierLightningSend("lnbc1280n1send", null) assertEquals(EarlierSend.Pending("hash"), earlier) } @@ -181,6 +184,15 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `an empty history spark has not synced yet holds the node off an invoice spark started sending`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + + assertEquals(EarlierSend.Pending("hash"), createSut().earlierLightningSend("lnbc1280n1send", "hash")) + } + @Test fun `an unreadable history lets the node pay an invoice spark never sent`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("other")) @@ -195,8 +207,10 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val sut = createSut() + sut.start(0).getOrThrow() - assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash")) + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } @Test From d31e9f00b08f1f1e6856802d250f8cc45273a637 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:25:31 +0100 Subject: [PATCH 043/135] fix: post raw transactions as text/plain through the spark regtest proxy --- scripts/spark-regtest-esplora.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/spark-regtest-esplora.py b/scripts/spark-regtest-esplora.py index d5a3863116..a8f03853ee 100755 --- a/scripts/spark-regtest-esplora.py +++ b/scripts/spark-regtest-esplora.py @@ -64,8 +64,10 @@ def forward(self): return self.reply(200, json.dumps(block_status(parts[1])).encode(), "application/json") body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) if self.command == "POST" else None request = urllib.request.Request(f"{UPSTREAM}{self.path}", data=body, method=self.command) - if self.headers.get("Content-Type"): - request.add_header("Content-Type", self.headers["Content-Type"]) + # Without one, urllib sends form-urlencoded, which Lightspark's POST /tx refuses with a bare code -1: a raw + # transaction is text/plain, which LDK's Esplora client does not name. + if body is not None: + request.add_header("Content-Type", self.headers.get("Content-Type") or "text/plain") try: with urllib.request.urlopen(request, timeout=30) as response: self.reply(response.status, response.read(), response.headers.get("Content-Type")) From 3f6c517483c366e3dabd7148254380f42ab275bf Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 20:29:10 +0100 Subject: [PATCH 044/135] fix: keep a spark retry pending on spark's record, not write times --- .../main/java/to/bitkit/services/CoreService.kt | 5 +++-- .../ActivityServiceLightningMessageTest.kt | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index c1659c419d..6ac4f10eef 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -886,9 +886,10 @@ class ActivityService( ) { return } - // A newer pending attempt, such as a Spark retry, stays until it settles; an older failure can't end it. + // A Spark retry of the invoice stays pending until Spark settles it; the channel's failure can't end it. + // Spark records the hash before it sends and drops it only once it reports the send failed or unknown. if (existingActivity is Activity.Lightning && existingActivity.v1.status == PaymentState.PENDING && - state == PaymentState.FAILED && (existingActivity.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp + state == PaymentState.FAILED && payment.id.lowercase() in cacheStore.data.first().sparkSendHashes ) { return } diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt index 4d169f862d..fe74a10b6e 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt @@ -109,16 +109,26 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { } @Test - fun `payment sync keeps a newer pending spark retry over the channel's earlier failure`() = coreTest { + fun `payment sync keeps a pending spark retry over the channel's earlier failure`() = coreTest { val retry = sent(status = PaymentState.PENDING, message = "").copy(timestamp = 300uL, updatedAt = 300uL) row = Activity.Lightning(retry) - whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkSendHashes = listOf(HASH)))) sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) assertEquals(PaymentState.PENDING, (row as Activity.Lightning).v1.status) } + @Test + fun `payment sync fails a node send whose row was written after the node failed it`() = coreTest { + row = Activity.Lightning(sent(status = PaymentState.PENDING, message = "").copy(updatedAt = 300uL)) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + + sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) + + assertEquals(PaymentState.FAILED, (row as Activity.Lightning).v1.status) + } + @Test fun `payment sync still fails the node's own earlier pending attempt`() = coreTest { row = Activity.Lightning(sent(status = PaymentState.PENDING, message = "")) From 192b71e3268c0e7a92cbbbe50c36a5337c308507 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 21:37:48 +0100 Subject: [PATCH 045/135] fix: back up spark exit data that changed while backups were stopped --- .../java/to/bitkit/repositories/BackupRepo.kt | 22 ++++++++++--- .../java/to/bitkit/repositories/SparkRepo.kt | 13 +++++--- .../to/bitkit/repositories/BackupRepoTest.kt | 33 ++++++++++++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 6 +--- 4 files changed, 58 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 62e2dfb3b9..12bf241939 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -22,7 +22,6 @@ import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive @@ -175,6 +174,10 @@ class BackupRepo @Inject constructor( @Volatile private var hasBackedUpSparkConnection = false + /** The last Spark exit-state generation marked for backup; it outlives the observers, so a gap is caught up. */ + @Volatile + private var markedSparkExitGeneration = 0L + private val uploadedActivityDigest = AtomicReference(null) private val activityDigestEpoch = AtomicLong(0) @@ -465,10 +468,19 @@ class BackupRepo @Inject constructor( val isReady = sparkRepo.state.map { it.isReady && it.hasSynced }.distinctUntilChanged() .onEach { if (!it) hasBackedUpSparkConnection = false } .filter { it } - merge(isReady, sparkRepo.exitStateChanged.map { false }).collect { isReadyTrigger -> - if (isReadyTrigger && hasBackedUpSparkConnection) return@collect - if (shouldSkipBackup()) return@collect - if (isReadyTrigger) hasBackedUpSparkConnection = true + isReady.collect { + if (hasBackedUpSparkConnection || shouldSkipBackup()) return@collect + hasBackedUpSparkConnection = true + markBackupRequired(BackupCategory.SPARK_EXIT) + } + } + ) + // The generation replays on each start, so exit data that changed while nothing observed is backed up then. + dataListenerJobs.add( + scope.launch { + sparkRepo.exitStateGeneration.collect { generation -> + if (generation <= markedSparkExitGeneration || shouldSkipBackup()) return@collect + markedSparkExitGeneration = generation markBackupRequired(BackupCategory.SPARK_EXIT) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 02a88b7f4c..c7bc65a99c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -148,10 +148,13 @@ class SparkRepo @Inject constructor( private val _nodeEvents = MutableSharedFlow(extraBufferCapacity = 64) val nodeEvents: SharedFlow = _nodeEvents.asSharedFlow() - private val _exitStateChanged = MutableSharedFlow(extraBufferCapacity = 1) + private val _exitStateGeneration = MutableStateFlow(0L) - /** Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. */ - val exitStateChanged: SharedFlow = _exitStateChanged.asSharedFlow() + /** + * Counts Spark's connections and changes to its unilateral exit data, so the exit data backup is redone whenever it + * moved past the one last backed up, also when it moved while nothing observed it. + */ + val exitStateGeneration: StateFlow = _exitStateGeneration.asStateFlow() suspend fun start(walletIndex: Int): Result = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext Result.success(Unit) @@ -165,7 +168,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.syncWallet() } .onSuccess { _state.update { it.copy(hasSynced = true) } } .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } - if (connected) _exitStateChanged.emit(Unit) + if (connected) _exitStateGeneration.update { it + 1 } refresh() if (!hasSyncedActivities) syncActivities().also { hasSyncedActivities = true } }.onFailure { @@ -804,7 +807,7 @@ class SparkRepo @Inject constructor( context = TAG, ) is SdkEvent.NewDeposits -> refresh() - is SdkEvent.UnilateralExitStateChanged -> _exitStateChanged.emit(Unit) + is SdkEvent.UnilateralExitStateChanged -> _exitStateGeneration.update { it + 1 } is SdkEvent.ClaimedDeposits -> refresh() else -> Unit } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 7e7b8afb91..bc4827cd39 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -142,6 +142,7 @@ class BackupRepoTest : BaseUnitTest() { private val keychain = mock() private val onchainSendAttemptStore = mock() private val sparkRepo = mock() + private val exitStateGeneration = MutableStateFlow(0L) private val vssStoreIdProvider = mock() private val preActivityMetadataRepo = mock() private val lightningService = mock() @@ -226,7 +227,7 @@ class BackupRepoTest : BaseUnitTest() { whenever { sparkRepo.restoreExitBackup(any(), any()) }.thenReturn(Result.success(Unit)) whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenReturn(Result.success(Unit)) whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(true) - whenever(sparkRepo.exitStateChanged).thenReturn(MutableSharedFlow()) + whenever(sparkRepo.exitStateGeneration).thenReturn(exitStateGeneration) whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) sut = createSut() @@ -333,6 +334,36 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `spark exit data that changed while observing was stopped uploads when observing restarts`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + exitStateGeneration.value = 1L + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() + sut.stopObservingBackups() + + exitStateGeneration.value = 2L + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `spark exit backup defers, without uploading, until Spark has connected and synced`() = test { whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 487abd4e47..07219566f4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -145,15 +145,11 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.connect(0)).thenReturn(true, false) whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) val sut = createSut() - val exitSignals = mutableListOf() - backgroundScope.launch { sut.exitStateChanged.collect { exitSignals += it } } - runCurrent() - sut.start(0).getOrThrow() sut.start(0).getOrThrow() runCurrent() - assertEquals(1, exitSignals.size, "exit data backup signals after two starts") + assertEquals(1L, sut.exitStateGeneration.value, "exit data backup signals after two starts") verify(activityRepo, times(1)).upsertActivity(any()) } From c5d5b46c535d9410586b851076eeb0fee5cdc27f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 21:51:45 +0100 Subject: [PATCH 046/135] fix: hold on-chain spark funding off a chain spark doesn't watch --- app/src/main/java/to/bitkit/env/Env.kt | 10 ++++++++++ app/src/main/java/to/bitkit/ui/ContentView.kt | 7 ++++--- .../to/bitkit/ui/screens/transfer/FundingScreen.kt | 5 +++-- .../test/java/to/bitkit/env/SparkChainServiceTest.kt | 9 +++++++++ .../bitkit/ui/screens/transfer/FundingScreenTest.kt | 11 +++++++++++ 5 files changed, 37 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 8f035eb59d..261caadb91 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -130,6 +130,16 @@ internal object Env { } /** Esplora REST that Spark reads the chain from; null keeps the SDK's default, on staging and regtest. */ + /** + * Whether the node's chain is the one Spark watches, so an on-chain funding of Spark from Savings or a hardware + * wallet reaches it. On regtest Spark runs on Lightspark's own chain, which the node joins only through the + * Spark regtest Esplora proxy. + */ + fun sparkSharesNodeChain(network: Network, regtestEsploraUrl: String?): Boolean = + network != Network.REGTEST || regtestEsploraUrl != null + + val sparkSharesNodeChain: Boolean get() = sparkSharesNodeChain(network, regtestEsploraUrl) + fun sparkChainServiceUrl(network: Network): String? = when (network) { Network.BITCOIN -> bitkitEsploraUrl else -> null diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 8de08c3356..420f7c0b24 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -1112,6 +1112,7 @@ private fun RootNavHost( val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() FundingScreen( canFundWithSpark = sparkState.isReady, + canFundOnChain = Env.sparkSharesNodeChain, onTransfer = { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) }, onFund = { scope.launch { @@ -1358,7 +1359,7 @@ private fun NavGraphBuilder.home( }, onEmptyActivityRowClick = { appViewModel.showSheet(Sheet.Receive()) }, onTransferToSpendingClick = { - if (sparkState.isReady) { + if (sparkState.isReady && Env.sparkSharesNodeChain) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -1394,7 +1395,7 @@ private fun NavGraphBuilder.home( } }, onTransferFromSavingsClick = { - if (sparkState.isReady) { + if (sparkState.isReady && Env.sparkSharesNodeChain) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -1415,7 +1416,7 @@ private fun NavGraphBuilder.home( ) }, onTransferToSpendingClick = { walletId -> - if (sparkState.isReady) { + if (sparkState.isReady && Env.sparkSharesNodeChain) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro, walletId) } else { appViewModel.showSheet(Sheet.TransferUnavailable) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt index 22326e6974..dc1bb3f367 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/FundingScreen.kt @@ -40,6 +40,7 @@ import to.bitkit.ui.utils.withAccent @Composable fun FundingScreen( canFundWithSpark: Boolean = false, + canFundOnChain: Boolean = true, onTransfer: () -> Unit = {}, onFund: () -> Unit = {}, onManual: () -> Unit = {}, @@ -85,7 +86,7 @@ fun FundingScreen( R.drawable.ic_transfer, 20.dp, "FundTransfer", - { if (hasSavings) onTransfer() else showNoFundsAlert = true }, + { if (hasSavings) onTransfer() else showNoFundsAlert = true }.takeIf { canFundOnChain }, ) FundingOption( R.string.lightning__funding__button2, @@ -115,7 +116,7 @@ fun FundingScreen( R.drawable.ic_device_tablet_speaker, 16.25.dp, "FundHardware", - onHardware.takeIf { canFundWithSpark }, + onHardware.takeIf { canFundWithSpark && canFundOnChain }, ) if (!canFundWithSpark) { FundingOption(R.string.lightning__funding__button2, R.drawable.ic_qr_purple, 13.75.dp, "FundReceive") diff --git a/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt b/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt index 597e6127b6..86eb15a492 100644 --- a/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt +++ b/app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt @@ -3,7 +3,9 @@ package to.bitkit.env import org.junit.Test import org.lightningdevkit.ldknode.Network import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue class SparkChainServiceTest { @Test @@ -17,4 +19,11 @@ class SparkChainServiceTest { assertNull(Env.sparkChainServiceUrl(Network.TESTNET)) assertNull(Env.sparkChainServiceUrl(Network.SIGNET)) } + + @Test + fun `on-chain spark funding needs the spark regtest chain on regtest`() { + assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, regtestEsploraUrl = null)) + assertTrue(Env.sparkSharesNodeChain(Network.REGTEST, regtestEsploraUrl = "http://10.0.2.2:3999")) + assertTrue(Env.sparkSharesNodeChain(Network.BITCOIN, regtestEsploraUrl = null)) + } } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt index ea5989604a..dafc6da5fa 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/FundingScreenTest.kt @@ -48,4 +48,15 @@ class FundingScreenTest { assertEquals(0, clicks) } + + @Test + fun `on-chain funding rows stay disabled when spark watches another chain`() { + composeRule.setContent { + AppThemeSurface { FundingScreen(canFundWithSpark = true, canFundOnChain = false) } + } + + composeRule.onNodeWithTag("FundTransfer").performScrollTo().assertIsNotEnabled() + composeRule.onNodeWithTag("FundHardware").performScrollTo().assertIsNotEnabled() + composeRule.onNodeWithTag("FundReceive").performScrollTo().assertIsEnabled() + } } From 9164635ad77e6a59d87e4d34525504e3d4d29f25 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 23:37:20 +0100 Subject: [PATCH 047/135] test: cover private invoice rotation for spark receipts --- .../bitkit/repositories/LightningRepoTest.kt | 15 ++++++++++++ .../repositories/PrivatePaykitRepoTest.kt | 23 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 6f24237ec7..7c66236073 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -248,6 +248,21 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).createInvoice(eq(222uL), eq("withdraw"), any()) } + @Test + fun `a payment spark received reaches the node event stream`() = test { + startNodeForTesting() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + val received = Event.PaymentReceived("hash", "hash", 1_000_000uL, emptyList()) + + @Suppress("UNCHECKED_CAST") + (sparkRepo.nodeEvents as MutableSharedFlow).emit(received) + runCurrent() + + assertTrue(received in events) + } + @Test fun `node startup failures do not dispatch invoice payment`() = test { var dispatched = false diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index f36c50c6a2..6b6466b742 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -3219,6 +3219,29 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.closeAndClear() } + @Test + fun `received payment reconciliation rotates a private invoice paid through Spark`() = test { + preparePrivateLightningContact() + val refreshedInvoice = "lnbcrt1refreshed" + whenever(lightningRepo.createInvoice(null, "", PRIVATE_BOLT11_EXPIRY_SECONDS, true)) + .thenReturn(Result.success(refreshedInvoice)) + whenever(coreService.decode(refreshedInvoice)) + .thenReturn(Scanner.Lightning(lightningInvoice(refreshedInvoice, byteArrayOf(8, 8, 8)))) + whenever(sparkRepo.receivedLightningPaymentHashes()).thenReturn(setOf("090909")) + clearInvocations(paykitSdkService) + + sut.reconcileReceivedPayments().getOrThrow() + runCurrent() + + val publication = argumentCaptor>() + verify(paykitSdkService).syncPrivatePaymentListsWithReservations(publication.capture(), eq(false)) + assertEquals( + PublicPaykitRepo.serializePayload(refreshedInvoice), + publication.firstValue.single().reservations.single().payload, + ) + sut.closeAndClear() + } + @Test fun `forced private Lightning refresh includes contacts loaded later`() = test { preparePrivateLightningContact() From d9d0e216ea4da3d9c135c0ad06eec0273f6f4b87 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 23:37:20 +0100 Subject: [PATCH 048/135] test: name the unit test the amount change journey relies on --- journeys/transfer/spending-confirm-amount-change.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/journeys/transfer/spending-confirm-amount-change.xml b/journeys/transfer/spending-confirm-amount-change.xml index 26356d3d8b..111c59a2c9 100644 --- a/journeys/transfer/spending-confirm-amount-change.xml +++ b/journeys/transfer/spending-confirm-amount-change.xml @@ -5,7 +5,8 @@ or less pays on that swipe, at the new amount. A price whose total is higher, or that leaves less for the spending balance, pays nothing: the screen shows the new amounts and a "Fees changed" toast, and the next swipe pays them. The higher-total case needs a spend of the wallet's own UTXO outside the app, - or a fee rate rise, which the Capabilities table does not list, so unit tests and a manual test cover it. + or a fee rate rise, which the Capabilities table does not list, so the unit test `swipe asks again when the + network fee rose since shown` in SparkFundingViewModelTest.kt covers it. A larger UTXO confirms while Spending Confirm is open, so the transfer is priced at swipe against a changed wallet. Coin selection may keep two inputs (150 000 + 150 000, or 150 000 + 500 000) at the From f6bd0e0a8685ba0fe5352124028429c90fb45000 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 23:50:33 +0100 Subject: [PATCH 049/135] test: pin which rails a unified invoice offers --- .../bitkit/repositories/LightningRepoTest.kt | 8 ++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 7c66236073..113ae59468 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1937,6 +1937,14 @@ class LightningRepoTest : BaseUnitTest() { assertTrue(sut.canSend(1000uL)) } + @Test + fun `canSend counts spark when no channel can pay`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + assertTrue(sut.canSend(1_000uL)) + } + @Test fun `canSend should return false when channels have insufficient capacity`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index bd3a14ff0b..3db1d8409d 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -10218,6 +10218,26 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(sut.sendUiState.value.isUnified) } + @Test + fun `unified scan offers only savings when spending cannot pay`() = test { + val bolt11 = "lnbcrt1spendingempty" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.00001&lightning=$bolt11" + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 1_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + whenever(lightningRepo.awaitNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.canSend(any())).thenReturn(false) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + sut.setIsAuthenticated(true) + + sut.onScanResult(uri) + advanceUntilIdle() + + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + assertNull(sut.sendUiState.value.decodedInvoice) + assertFalse(sut.sendUiState.value.isUnified) + assertFalse(sut.sendUiState.value.canSwitchFundingSource) + } + @Test fun `manual input of own lightning invoice shows self payment toast`() = test { val bolt11 = "lnbcrt1ownmanual" From 327ad44ae8563b29724d0fe68e57e0a314f73536 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 00:04:49 +0100 Subject: [PATCH 050/135] fix: refresh the receive invoice once a restore ends --- .../java/to/bitkit/repositories/BackupRepo.kt | 6 +++++ .../java/to/bitkit/repositories/WalletRepo.kt | 9 ++++++++ .../bitkit/repositories/LightningRepoTest.kt | 2 +- .../to/bitkit/repositories/WalletRepoTest.kt | 23 +++++++++++++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 12bf241939..004da6bbac 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop @@ -189,6 +190,11 @@ class BackupRepo @Inject constructor( private val restorePendingUntil = MutableStateFlow(0L) + /** Whether a restore is announced and its backup not applied yet, as [isRestoreInProgress], as it changes. */ + val restoreInProgress: Flow = combine(_isRestoring, restorePendingUntil) { isRestoring, pendingUntil -> + isRestoring || currentTimeMillis() < pendingUntil + }.distinctUntilChanged() + fun reset() { stopObservingBackups() clearUploadedActivityDigest() diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index 85b52a7425..db5445e6e5 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -16,6 +16,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update @@ -119,6 +121,13 @@ class WalletRepo @Inject constructor( _balanceState.update { state -> state.copy(hardwareWallets = wallets.map { it.toBalance() }) } } } + repoScope.launch { + // Node start and Spark-ready skip their refresh during a restore, so it runs once the restore ends. + backupRepo.restoreInProgress.drop(1).filter { !it }.collect { + val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() + if (walletExists() && (isNodeRunning || sparkRepo.state.value.isReady)) refreshBip21() + } + } repoScope.launch { sparkRepo.state.map { it.isReady }.distinctUntilChanged().collect { isReady -> // An address revealed before the restore reads the backup leaves an unused index behind it. diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 113ae59468..35adce42d6 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -313,7 +313,7 @@ class LightningRepoTest : BaseUnitTest() { hwWalletRepo = hardware, connectionRecovery = connectionRecoveryFixture(settingsStore), sparkRepo = sparkRepo, - backupRepo = mock(), + backupRepo = mock { on { restoreInProgress } doReturn MutableStateFlow(false) }, ) } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index aeb0a50c56..b95b2f870b 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -138,6 +138,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(bolt11 = "", onchainAddress = ADDRESS))) whenever { cacheStore.update(any()) }.thenReturn(Unit) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) + whenever(backupRepo.restoreInProgress).thenReturn(MutableStateFlow(false)) whenever(hwWalletRepo.wallets).thenReturn(MutableStateFlow(persistentListOf())) whenever(lightningRepo.nodeEventUpdates).thenReturn(MutableSharedFlow()) whenever(lightningRepo.listSpendableOutputs()).thenReturn(Result.success(emptyList())) @@ -238,6 +239,28 @@ class WalletRepoTest : BaseUnitTest() { verify(privatePaykitAddressReservationRepo).nextReusableReceiveAddress() } + @Test + fun `a restore that completes after the node and spark started refreshes the receive invoice once`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + val restoring = MutableStateFlow(true) + whenever(backupRepo.restoreInProgress).thenReturn(restoring) + whenever(backupRepo.isRestoreInProgress()).thenAnswer { restoring.value } + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + whenever(lightningRepo.createInvoice(anyOrNull(), any(), any(), any())).thenReturn(Result.success(INVOICE)) + val spark = sparkRepoWith(MutableStateFlow(SparkState(isReady = true))) + whenever(spark.canReceive()).thenReturn(true) + sut = createSut(spark = spark) + testScheduler.runCurrent() + verify(lightningRepo, never()).createInvoice(anyOrNull(), any(), any(), any()) + + restoring.value = false + testScheduler.runCurrent() + + verify(lightningRepo, times(1)).createInvoice(anyOrNull(), any(), any(), any()) + assertEquals(INVOICE, sut.walletState.value.bolt11) + } + private fun sparkRepoWith(state: MutableStateFlow): SparkRepo = mock { on { this.state } doReturn state on { nodeEvents } doReturn MutableSharedFlow() From 6baceed96d0541cd0eb25a7aecd4b00a71dadf0a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 03:29:05 +0100 Subject: [PATCH 051/135] fix: spark transfer, send and claim edge cases - Transfer to Savings starts from a fresh pick and refuses to commit an empty selection. - A Spark send is refused while the node can't list an invoice it sent; Paykit reads an unlistable node or Spark as unknown. - Insufficient funds inside the Spark send is a refusal. - Wait after a claim-time reprice clears the early-claim fee cap; the latest backup time skips SPARK_EXIT. - Transfer journeys name the ESPLORA_URL build Savings to Spending needs on regtest. --- .../main/java/to/bitkit/data/CacheStore.kt | 15 +++++ .../java/to/bitkit/repositories/BackupRepo.kt | 13 +++- .../to/bitkit/repositories/LightningRepo.kt | 17 +++++- .../bitkit/repositories/PrivatePaykitRepo.kt | 15 +++-- .../java/to/bitkit/repositories/SparkRepo.kt | 47 +++++++++++---- .../java/to/bitkit/services/SparkService.kt | 5 ++ app/src/main/java/to/bitkit/ui/ContentView.kt | 5 +- .../screens/transfer/SavingsConfirmScreen.kt | 6 +- .../to/bitkit/viewmodels/TransferViewModel.kt | 3 + .../to/bitkit/repositories/BackupRepoTest.kt | 6 ++ .../bitkit/repositories/LightningRepoTest.kt | 37 ++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 60 +++++++++++++++++++ .../viewmodels/TransferViewModelTest.kt | 9 +++ journeys/amount-limits/README.md | 3 +- .../transfer-spending-over-max.xml | 2 +- .../transfer-spending-preset-delete.xml | 2 +- .../passphrase-transfer-to-spending.xml | 2 +- .../transfer-to-spending-node-warmup.xml | 2 +- .../hardware-wallet/transfer-to-spending.xml | 2 +- .../transfer/spark-transfer-to-spending.xml | 2 +- .../spending-confirm-amount-change.xml | 2 +- .../transfer/transfer-unavailable-sheet.xml | 3 +- 22 files changed, 228 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 9c62249d0e..303010b9f8 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -152,6 +152,19 @@ class CacheStore internal constructor( store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes - hash) } } + suspend fun addLdkSendHash(paymentHash: String) { + val hash = paymentHash.lowercase() + store.updateData { + it.copy(ldkSendHashes = (it.ldkSendHashes - hash + hash).takeLast(MAX_SPARK_SEND_HASHES)) + } + } + + suspend fun removeLdkSendHash(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash !in store.data.first().ldkSendHashes) return + store.updateData { it.copy(ldkSendHashes = it.ldkSendHashes - hash) } + } + suspend fun setBackgroundReceive(details: NewTransactionSheetDetails) = store.updateData { it.copy(backgroundReceive = details) } @@ -187,6 +200,8 @@ data class AppCacheData( val pendingLightningMessages: Map = mapOf(), /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ val sparkSendHashes: List = listOf(), + /** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */ + val ldkSendHashes: List = listOf(), ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 004da6bbac..6bac538a35 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1335,8 +1335,7 @@ class BackupRepo @Inject constructor( withTimeout(VSS_TIMESTAMP_TIMEOUT) { vssBackupClient.setup().getOrThrow() coroutineScope { - BackupCategory.entries - .filter { it != BackupCategory.LIGHTNING_CONNECTIONS && it != BackupCategory.USDT_RECOVERY } + LATEST_BACKUP_TIME_CATEGORIES .map { category -> async { getRemoteBackupTimestamp(category) } } .mapNotNull { it.await() } .filter { it > 0uL } @@ -1462,6 +1461,16 @@ class BackupRepo @Inject constructor( companion object { private const val TAG = "BackupRepo" + /** + * The categories whose remote timestamp tells when the wallet was last backed up. The Spark exit data is left + * out: reading its timestamp downloads data that can reach several MB. + */ + internal val LATEST_BACKUP_TIME_CATEGORIES = BackupCategory.entries.filter { + it != BackupCategory.LIGHTNING_CONNECTIONS && + it != BackupCategory.USDT_RECOVERY && + it != BackupCategory.SPARK_EXIT + } + private const val MINUTE_IN_MS = 60_000 private const val BACKUP_DEBOUNCE = 5000L // 5 seconds diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index dba62aa4bf..3679b19d4f 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1522,12 +1522,21 @@ class LightningRepo @Inject constructor( return payInvoiceWithLdk(bolt11, null, paymentHash, null, null) { true } } + /** + * The node's pending or paid send of [bolt11]. While the node can't list its payments (stopped or not started yet), + * a send it started for the invoice counts as pending, since it may be live. + */ private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { - val send = listPaymentsOrNull()?.firstOrNull { + val key = ldkSendKey(bolt11, paymentHash) + val payments = listPaymentsOrNull() + ?: return key.takeIf { it in cacheStore.data.first().ldkSendHashes }?.let { EarlierSend.Pending(it) } + val send = payments.firstOrNull { val kind = it.kind as? PaymentKind.Bolt11 ?: return@firstOrNull false it.direction == PaymentDirection.OUTBOUND && (kind.bolt11.equals(bolt11, ignoreCase = true) || kind.hash.equals(paymentHash, ignoreCase = true)) - } ?: return null + } + if (send == null || send.status == PaymentStatus.FAILED) cacheStore.removeLdkSendHash(key) + if (send == null) return null val hash = (send.kind as PaymentKind.Bolt11).hash return when (send.status) { PaymentStatus.PENDING -> EarlierSend.Pending(hash) @@ -1555,11 +1564,15 @@ class LightningRepo @Inject constructor( sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() + cacheStore.addLdkSendHash(ldkSendKey(bolt11, paymentHash)) runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } .onSuccess { recordSendRail(it, LightningRail.Ldk) } .also { syncState() } } + /** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */ + private fun ldkSendKey(bolt11: String, paymentHash: String?): String = (paymentHash ?: bolt11).lowercase() + private fun recordSendRail(paymentHash: String, rail: LightningRail) { sendRails[paymentHash.lowercase()] = rail } diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index 451ec44ef4..50ae2dba44 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -2308,6 +2308,9 @@ class PrivatePaykitRepo @Inject constructor( context = TAG, ) false + } else if (attemptedHashes == null) { + // Unknown while the node or Spark can't list its payments: the invoice may be paid already. + false } else if (paymentHash in attemptedHashes) { staleLightningHashes += paymentHash Logger.warn( @@ -2463,18 +2466,22 @@ class PrivatePaykitRepo @Inject constructor( (coreService.decode(bolt11) as? Scanner.Lightning)?.invoice?.paymentHash?.toHex() }.getOrNull() - private suspend fun attemptedOutboundBolt11PaymentHashes(): Set = - lightningRepo.getPayments().getOrElse { + /** Null while the node or Spark can't list its payments, so a payment either may have made isn't read as none. */ + private suspend fun attemptedOutboundBolt11PaymentHashes(): Set? { + val payments = lightningRepo.getPayments().getOrElse { if (it is CancellationException) throw it - emptyList() + return null } + val sparkHashes = sparkRepo.attemptedLightningPaymentHashes() ?: return null + return payments .filter { it.direction == PaymentDirection.OUTBOUND && it.status != PaymentStatus.FAILED && it.kind is PaymentKind.Bolt11 } .map { it.id.lowercase() } - .toSet() + sparkRepo.attemptedLightningPaymentHashes() + .toSet() + sparkHashes + } private suspend fun isReceivedInvoiceSettled(paymentHash: String): Boolean = paymentHash in receivedSettledPaymentHashes() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c7bc65a99c..3a7c027b90 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -137,6 +137,9 @@ class SparkRepo @Inject constructor( /** Watchers of the claims of deposits this app sent, by txid; they outlive the screens that start them. */ private val claimJobs = ConcurrentHashMap() + /** Vouts of the deposits an early claim was attempted for, so Wait can clear the fee cap it left on them. */ + private val earlyClaimVouts = ConcurrentHashMap() + private val _depositClaims = MutableStateFlow>(emptyMap()) /** Where the claim of each deposit sent from the transfer flow stands, by txid. */ @@ -186,6 +189,7 @@ class SparkRepo @Inject constructor( suspend fun wipe(walletIndex: Int): Result = withContext(bgDispatcher) { claimJobs.values.forEach { it.cancel() } claimJobs.clear() + earlyClaimVouts.clear() preparedWithdrawal = null withdrawalTxids.clear() broadcastDeposits.clear() @@ -286,6 +290,12 @@ class SparkRepo @Inject constructor( } val payment = sent.getOrElse { if (it.isInvoiceExpired()) throw SparkError.InvoiceExpired(it) + // Spark selects the leaves to spend before anything goes to the operators, so a short balance left + // nothing, for instance when an earlier send spent it after the balance was read. + if (it is SdkException.InsufficientFunds) { + cacheStore.removeSparkSendHash(paymentHash) + throw SparkError.SendRefused("Spark balance can't cover the payment", it) + } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) settleUncertainSend(paymentHash) throw PaymentPendingException(paymentHash) @@ -364,10 +374,20 @@ class SparkRepo @Inject constructor( followDepositClaim(txid, SparkClaimSpeed.Instant, repriced.offer.earlyFeeSats) } - /** Leaves the deposit in [txid] to the claim at 3 confirmations. */ + /** + * Leaves the deposit in [txid] to the claim at 3 confirmations, clearing the fee cap an early claim attempt left on + * it, so Spark doesn't still claim it early. + */ fun waitForMatureClaim(txid: String) { claimJobs.remove(txid)?.cancel() setDepositClaim(txid, SparkDepositClaim.Later) + val vout = earlyClaimVouts.remove(txid) ?: return + scope.launch { + runSuspendCatching { sparkService.releaseDepositClaimFee(txid, vout) } + .onFailure { + Logger.warn("Failed to clear the early claim cap of Spark deposit '$txid'", it, context = TAG) + } + } } private suspend fun claimInstantly(txid: String, ceilingSats: ULong) { @@ -420,6 +440,7 @@ class SparkRepo @Inject constructor( /** Accepts the early claim of [offer] at its quoted fee. */ suspend fun claimEarly(offer: SparkClaimOffer.Choice): Result = withContext(bgDispatcher) { + earlyClaimVouts[offer.txid] = offer.vout runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats) } .map { SparkEarlyClaim.from(it) } .recover { if (it is SdkException.DepositClaimInProgress) SparkEarlyClaim.Claimed else throw it } @@ -757,19 +778,25 @@ class SparkRepo @Inject constructor( /** Payment hashes of the Lightning payments Spark received. */ suspend fun receivedLightningPaymentHashes(): Set = lightningPaymentHashes { it.paymentType == SparkPaymentType.RECEIVE && it.status == PaymentStatus.COMPLETED } + .orEmpty() - /** Payment hashes of the Lightning payments Spark sent or is sending. */ - suspend fun attemptedLightningPaymentHashes(): Set = - lightningPaymentHashes { it.paymentType == SparkPaymentType.SEND && it.status != PaymentStatus.FAILED } + /** + * Payment hashes of the Lightning payments Spark sent or is sending, or null while Spark runs here but can't list + * them, so a send it may have made isn't read as never tried. + */ + suspend fun attemptedLightningPaymentHashes(): Set? { + if (!sparkService.isSupported) return emptySet() + return lightningPaymentHashes { it.paymentType == SparkPaymentType.SEND && it.status != PaymentStatus.FAILED } + } - private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set = withContext(bgDispatcher) { - if (!sparkService.isConnected) return@withContext emptySet() + private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set? = withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext null runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .getOrDefault(emptyList()) - .filter(filter) - .mapNotNull { (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash?.lowercase() } - .toSet() + .getOrNull() + ?.filter(filter) + ?.mapNotNull { (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash?.lowercase() } + ?.toSet() } private suspend fun syncActivities() { diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 413710108b..22ab976ab4 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -265,6 +265,11 @@ class SparkService @Inject constructor( ClaimDepositRequest(txid, vout, MaxFee(MaxOnchainFee.Fixed(maxFeeSats), proportionalPpm = null)), ).outcome + /** Clears the fee ceiling an early claim left on a deposit, back to the configured one that never claims early. */ + suspend fun releaseDepositClaimFee(txid: String, vout: UInt) { + requireSdk().claimDeposit(ClaimDepositRequest(txid, vout, maxFee = null)) + } + suspend fun listPayments(): List = requireSdk().listPayments(ListPaymentsRequest()).payments /** Exports what a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. */ diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 420f7c0b24..9aee983b5f 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -1079,7 +1079,10 @@ private fun RootNavHost( SavingsAvailabilityScreen( onBackClick = { navController.popBackStack() }, onCancelClick = { navController.navigateToHome() }, - onContinueClick = { navController.navigateTo(Routes.SavingsConfirm) }, + onContinueClick = { + transferViewModel.beginSavingsTransfer() + navController.navigateTo(Routes.SavingsConfirm) + }, ) } deepLinkableComposable { diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index fedb717780..99abc486d8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -125,6 +125,7 @@ fun SavingsConfirmScreen( // Spark's part moves only at the fee shown, so nothing is confirmed before it is priced. isSparkFeePricing = withdrawsSpark && isSparkFeePricing, isSparkUnpriced = withdrawsSpark && sparkFeeSats == null, + isNothingSelected = channels.isEmpty() && !withdrawsSpark, isSparkTooSmall = withdrawsSpark && isSparkTooSmall, isSwapEnabled = swapState.isSwapEnabled, quote = swapState.quote, @@ -167,6 +168,7 @@ private fun SavingsConfirmContent( sparkFeeSats: ULong?, isSparkFeePricing: Boolean, isSparkUnpriced: Boolean, + isNothingSelected: Boolean = false, isSparkTooSmall: Boolean, isSwapEnabled: Boolean, quote: SavingsSwapQuote?, @@ -344,7 +346,7 @@ private fun SavingsConfirmContent( SwipeToConfirm( text = stringResource(R.string.lightning__transfer__swipe), loading = isLoading || isPricingSwap || isSparkFeePricing, - enabled = !isSparkUnpriced, + enabled = !isSparkUnpriced && !isNothingSelected, color = Colors.Brand, onConfirm = { scope.launch { @@ -359,7 +361,7 @@ private fun SavingsConfirmContent( // Fallback: drain a whole channel on-chain by closing it instead of swapping. TertiaryButton( text = stringResource(R.string.lightning__savings_confirm__close_instead), - enabled = !isSparkUnpriced, + enabled = !isSparkUnpriced && !isNothingSelected, onClick = onCloseConfirm, ) } diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 42f52f10a7..06919fcaec 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -307,6 +307,9 @@ class TransferViewModel @Inject constructor( return SavingsSwapResult.Failure(event.reason.toUserMessage(context)) } + /** Opens Transfer to Savings with nothing left from an earlier visit that ended before the swipe. */ + fun beginSavingsTransfer() = setSavingsSelection(SavingsSelection()) + fun setSavingsSelection(selection: SavingsSelection) { _savingsSelection.update { selection } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index bc4827cd39..60a4f2d62b 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -233,6 +233,12 @@ class BackupRepoTest : BaseUnitTest() { sut = createSut() } + @Test + fun `the latest backup time skips the spark exit data`() { + assertFalse(BackupCategory.SPARK_EXIT in BackupRepo.LATEST_BACKUP_TIME_CATEGORIES) + assertTrue(BackupCategory.WALLET in BackupRepo.LATEST_BACKUP_TIME_CATEGORIES) + } + @Test fun `restore marker storage reads leave Main responsive`() = test { val entered = CompletableDeferred() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 35adce42d6..4f2a1e04db 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1317,6 +1317,43 @@ class LightningRepoTest : BaseUnitTest() { assertIs(retry.exceptionOrNull()) } + @Test + fun `an invoice the node sent is not sent through spark while the node can't list it`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + val retry = sut.payInvoice("bolt11", 1_000uL) + + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + assertIs(retry.exceptionOrNull()) + } + + @Test + fun `spark still pays while the node can't list when the node never tried the invoice`() = test { + startNodeForTesting() + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + } + + @Test + fun `a node send is recorded before it leaves`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send("bolt11", 1_000uL)).thenReturn("hash") + + sut.payInvoice("bolt11", 1_000uL).getOrThrow() + + verifyBlocking(cacheStore) { addLdkSendHash("bolt11") } + } + @Test fun `an invoice spark is still paying is not sent again through the node`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 07219566f4..48a838cbc9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -523,6 +523,52 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(450uL, claim.offer.earlyFeeSats) } + @Test + fun `wait after a claim time reprice clears the early claim cap`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + ClaimDepositOutcome.Deferred( + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ) + ) + val sut = createSut() + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + sut.waitForMatureClaim("txid") + advanceUntilIdle() + + assertEquals(SparkDepositClaim.Later, sut.depositClaims.value["txid"]) + verify(sparkService).releaseDepositClaimFee("txid", 0u) + } + + @Test + fun `wait before any claim attempt leaves the deposit alone`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 900uL)) + val sut = createSut() + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + sut.waitForMatureClaim("txid") + advanceUntilIdle() + + verify(sparkService, never()).releaseDepositClaimFee(any(), any()) + } + + @Test + fun `attempted sends are unknown while spark can't list them`() = test { + whenever(sparkService.isConnected).thenReturn(false) + val sut = createSut() + + assertNull(sut.attemptedLightningPaymentHashes()) + + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenAnswer { throw SdkException.Generic("offline") } + assertNull(sut.attemptedLightningPaymentHashes()) + } + @Test fun `instant is unavailable when Spark offers only the standard claim`() = test { listDeposit() @@ -734,6 +780,20 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } + @Test + fun `insufficient funds inside the spark send is a refusal, not pending`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } + val sut = createSut() + + val error = sut.payInvoice("lnbc1", 100uL).exceptionOrNull() + + assertIs(error) + verifyBlocking(cacheStore) { removeSparkSendHash("hash") } + } + @Test fun `a spark send over the fee limit is refused before it leaves`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 56f97aa3a9..962bf3c16e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -113,6 +113,15 @@ class TransferViewModelTest : BaseUnitTest() { assertTrue(sparkOnly.withdrawsSpark(SPARK_SATS)) } + @Test + fun `entering transfer to savings drops a pick left from an abandoned visit`() { + sut.setSavingsSelection(SavingsSelection(channelIds = persistentSetOf("closed-since"), includesSpark = false)) + + sut.beginSavingsTransfer() + + assertEquals(SavingsSelection(), sut.savingsSelection.value) + } + @Test fun `transfer to savings with only spark withdraws spark and closes no channel`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) diff --git a/journeys/amount-limits/README.md b/journeys/amount-limits/README.md index 93cc15c033..bc921f4177 100644 --- a/journeys/amount-limits/README.md +++ b/journeys/amount-limits/README.md @@ -21,7 +21,8 @@ External node). `./lsp POST /regtest/chain/deposit '{"address":"","amountSat":100000}'` then `./lsp POST /regtest/chain/mine '{"count":3}'` and wait for the balance to sync. 2. **Transfer→Spending needs Spark connected** so the most Savings can send to the Spark deposit - address can be priced. The number pad is disabled until that max loads — **wait for it** before + address can be priced. On regtest it also needs a build with `ESPLORA_URL` on Spark's regtest chain + (`scripts/spark-regtest-esplora.py`); without it the Transfer Unavailable sheet opens. The number pad is disabled until that max loads — **wait for it** before typing. 3. **External-node flow needs a reachable LN peer.** The staging LSP node works as the peer: id `028a8910b0048630d4eb17af25668cdd7ea6f2d8ae20956e7a06e2ae46ebcb69fc`, diff --git a/journeys/amount-limits/transfer-spending-over-max.xml b/journeys/amount-limits/transfer-spending-over-max.xml index 9e1a555c31..931e1cc86c 100644 --- a/journeys/amount-limits/transfer-spending-over-max.xml +++ b/journeys/amount-limits/transfer-spending-over-max.xml @@ -5,7 +5,7 @@ digits while at the cap. Precondition: onboarded dev wallet with a POSITIVE on-chain Savings balance and Spark connected on - its regtest, so the most Savings can send to the Spark deposit address can be priced. The pad is + its regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), so the most Savings can send to the Spark deposit address can be priced. The pad is disabled until that maximum loads — wait for it. The maximum is the Savings balance less the network fee, so it is lower than the Savings balance. Start on the wallet home screen. diff --git a/journeys/amount-limits/transfer-spending-preset-delete.xml b/journeys/amount-limits/transfer-spending-preset-delete.xml index 03e299c823..7cfb9791f5 100644 --- a/journeys/amount-limits/transfer-spending-preset-delete.xml +++ b/journeys/amount-limits/transfer-spending-preset-delete.xml @@ -7,7 +7,7 @@ Precondition: onboarded dev wallet with the display unit set to modern Bitcoin (sats), primary display Bitcoin, a POSITIVE on-chain Savings balance of at least 250 000 sats, and Spark connected - on its regtest. Start on the wallet home screen. No funds move: the journey never taps Continue. + on its regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet). Start on the wallet home screen. No funds move: the journey never taps Continue. Why 250 000: the number pad rejects any sats input above its max (AmountInputViewModel.handleNumberPadInput, the guard comparing the new amount to maxAmount), diff --git a/journeys/hardware-wallet/passphrase-transfer-to-spending.xml b/journeys/hardware-wallet/passphrase-transfer-to-spending.xml index 091f42d0e4..3a012dc3e7 100644 --- a/journeys/hardware-wallet/passphrase-transfer-to-spending.xml +++ b/journeys/hardware-wallet/passphrase-transfer-to-spending.xml @@ -3,7 +3,7 @@ Drives Transfer To Spending from a passphrase (hidden) wallet. While the Trezor session that holds the passphrase is still open the transfer signs straight away; after the session is dropped Bitkit asks for the passphrase again, and a wrong one is refused instead of signing - from whichever wallet the device happens to have open. Requires Spark connected on its regtest, the emulator started with + from whichever wallet the device happens to have open. Requires Spark connected on its regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), the emulator started with passphrase protection enabled, the hidden wallet from passphrase-pairing.xml paired, and its native-segwit account holding spendable regtest funds. diff --git a/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml b/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml index db2076b6b5..77d86cf25d 100644 --- a/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml +++ b/journeys/hardware-wallet/transfer-to-spending-node-warmup.xml @@ -3,7 +3,7 @@ Verifies that starting a hardware-wallet transfer while the Lightning node is still warming up does not fail or strand the CTA in loading. The flow should show the normal loading/progress UI, continue once the node reaches the needed state, and land on the - sign screen. Requires Spark connected on its regtest and a paired and funded hardware wallet. + sign screen. Requires Spark connected on its regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), and a paired and funded hardware wallet. diff --git a/journeys/hardware-wallet/transfer-to-spending.xml b/journeys/hardware-wallet/transfer-to-spending.xml index c24949172e..867791fe5a 100644 --- a/journeys/hardware-wallet/transfer-to-spending.xml +++ b/journeys/hardware-wallet/transfer-to-spending.xml @@ -3,7 +3,7 @@ Drives the watch-only Transfer To Spending flow for a paired Trezor into Spark: Amount -> Sign With Your Device -> Transaction Signed -> setting-up progress, then verifies the new transfer is represented once in the hardware wallet's Core activity scope. Requires Spark connected on its - regtest and a paired Bridge emulator whose native-segwit account holds spendable regtest funds and + regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), and a paired Bridge emulator whose native-segwit account holds spendable regtest funds and at least one older hardware receive row with a distinct amount. diff --git a/journeys/transfer/spark-transfer-to-spending.xml b/journeys/transfer/spark-transfer-to-spending.xml index a5c2a9f0c3..5ede3e3336 100644 --- a/journeys/transfer/spark-transfer-to-spending.xml +++ b/journeys/transfer/spark-transfer-to-spending.xml @@ -10,7 +10,7 @@ sees, so this journey stops before the swipe; the states after it are covered by SettingUpScreen previews and SparkRepoTest. - Precondition: dev build with Spark connected on its regtest (no key needed), a freshly onboarded wallet (so + Precondition: dev build with Spark connected on its regtest (no key needed), built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), a freshly onboarded wallet (so neither intro has been seen) with a positive on-chain Savings balance and no channels, and the Spending suggestion card on Home. Start on the wallet home screen. diff --git a/journeys/transfer/spending-confirm-amount-change.xml b/journeys/transfer/spending-confirm-amount-change.xml index 111c59a2c9..2b570a189c 100644 --- a/journeys/transfer/spending-confirm-amount-change.xml +++ b/journeys/transfer/spending-confirm-amount-change.xml @@ -13,7 +13,7 @@ same fee, or spend the new UTXO alone at a lower fee; either way the fresh price costs no more than the one shown, so the swipe pays at once. - Precondition: a freshly onboarded dev wallet with Spark connected on its regtest, no channel and + Precondition: a freshly onboarded dev wallet with Spark connected on its regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), no channel and exactly two confirmed on-chain UTXOs of 150 000 sats each (two ./lsp deposits to the wallet's savings address, each followed by a mine). Start on the wallet home screen. diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index 1f5a9722b5..a4fc33336c 100644 --- a/journeys/transfer/transfer-unavailable-sheet.xml +++ b/journeys/transfer/transfer-unavailable-sheet.xml @@ -9,7 +9,8 @@ path shows the same sheet content. Precondition: dev build, onboarded wallet with a positive on-chain Savings balance, no channels and Spark - not running (a build without a Breez API key, or Spark's regtest unreachable); with Spark ready, see + not running (a build without a Breez API key, or Spark's regtest unreachable), or a regtest build without + `ESPLORA_URL`, whose deposits Spark can't see; with Spark ready on its chain, see spark-transfer-to-spending.xml. Start on the wallet home screen. From 8afe67cd1b5b7cf94d339cff17800ec439cffd18 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 04:36:14 +0100 Subject: [PATCH 052/135] fix: earlier node sends and early-claim cap clearing - The node's first payment listing keeps its pending and paid sends by hash, so node sends made before hashes were kept hold Spark too; until that first listing an unlistable node refuses Spark sends. - Wait retries clearing the early-claim fee cap while another claim of the deposit holds it. --- .../main/java/to/bitkit/data/CacheStore.kt | 18 +++++++ .../to/bitkit/repositories/LightningRepo.kt | 28 ++++++++-- .../java/to/bitkit/repositories/SparkRepo.kt | 13 +++-- .../bitkit/repositories/LightningRepoTest.kt | 53 ++++++++++++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 23 ++++++++ 5 files changed, 127 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 303010b9f8..f1847aace8 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -159,6 +159,19 @@ class CacheStore internal constructor( } } + /** Keeps [paymentHashes], the node's pending and paid sends, once, ahead of the hashes kept since. */ + suspend fun seedLdkSendHashes(paymentHashes: List) { + if (store.data.first().ldkSendHashesSeeded) return + store.updateData { data -> + if (data.ldkSendHashesSeeded) return@updateData data + val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.ldkSendHashes.toSet() + data.copy( + ldkSendHashes = (seeded + data.ldkSendHashes).takeLast(MAX_SPARK_SEND_HASHES), + ldkSendHashesSeeded = true, + ) + } + } + suspend fun removeLdkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().ldkSendHashes) return @@ -202,6 +215,11 @@ data class AppCacheData( val sparkSendHashes: List = listOf(), /** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */ val ldkSendHashes: List = listOf(), + /** + * Set once the node's own list has filled [ldkSendHashes], as node sends made before hashes were kept carry none + * there. Until then an unlistable node holds every Spark send. + */ + val ldkSendHashesSeeded: Boolean = false, ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 3679b19d4f..3b65d33116 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -430,6 +430,7 @@ class LightningRepo @Inject constructor( lightningService.start(timeout, ::onEvent) _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } + listPaymentsOrNull()?.let { seedLdkSendHashes(it) } // Initial state sync syncState() @@ -1498,7 +1499,9 @@ class LightningRepo @Inject constructor( val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() if (shouldPayWithSpark(bolt11, sats)) { runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } - earlierNodeSend(bolt11, paymentHash)?.let { return it.toResult() } + runSuspendCatching { earlierNodeSend(bolt11, paymentHash) } + .getOrElse { return Result.failure(it) } + ?.let { return it.toResult() } val authorizeSend: suspend () -> Boolean = { onBeforeSend().also { if (it) requireWalletRestoreComplete() } } @@ -1524,12 +1527,22 @@ class LightningRepo @Inject constructor( /** * The node's pending or paid send of [bolt11]. While the node can't list its payments (stopped or not started yet), - * a send it started for the invoice counts as pending, since it may be live. + * a send it started for the invoice counts as pending, since it may be live. Before the node first listed its + * payments, the sends it made earlier are unknown, so the node not started yet is thrown. */ private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) val payments = listPaymentsOrNull() - ?: return key.takeIf { it in cacheStore.data.first().ldkSendHashes }?.let { EarlierSend.Pending(it) } + if (payments == null) { + val cache = cacheStore.data.first() + if (key in cache.ldkSendHashes) return EarlierSend.Pending(key) + if (!cache.ldkSendHashesSeeded) { + Logger.warn("Refused a Spark send until the node lists its earlier payments once", context = TAG) + throw ServiceError.NodeNotStarted() + } + return null + } + seedLdkSendHashes(payments) val send = payments.firstOrNull { val kind = it.kind as? PaymentKind.Bolt11 ?: return@firstOrNull false it.direction == PaymentDirection.OUTBOUND && @@ -1570,6 +1583,15 @@ class LightningRepo @Inject constructor( .also { syncState() } } + /** Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too. */ + private suspend fun seedLdkSendHashes(payments: List) { + cacheStore.seedLdkSendHashes( + payments + .filter { it.direction == PaymentDirection.OUTBOUND && it.status != PaymentStatus.FAILED } + .mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash } + ) + } + /** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */ private fun ldkSendKey(bolt11: String, paymentHash: String?): String = (paymentHash ?: bolt11).lowercase() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 3a7c027b90..b2c6c5d599 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -382,11 +382,16 @@ class SparkRepo @Inject constructor( claimJobs.remove(txid)?.cancel() setDepositClaim(txid, SparkDepositClaim.Later) val vout = earlyClaimVouts.remove(txid) ?: return + // Tried again while another claim of the deposit, such as Spark's own sync, leaves the cap in place. scope.launch { - runSuspendCatching { sparkService.releaseDepositClaimFee(txid, vout) } - .onFailure { - Logger.warn("Failed to clear the early claim cap of Spark deposit '$txid'", it, context = TAG) - } + repeat(CLAIM_POLL_ATTEMPTS) { attempt -> + runSuspendCatching { sparkService.releaseDepositClaimFee(txid, vout) } + .onSuccess { return@launch } + .onFailure { + Logger.warn("Failed to clear the early claim cap of Spark deposit '$txid'", it, context = TAG) + } + if (attempt < CLAIM_POLL_ATTEMPTS - 1) delay(CLAIM_POLL_INTERVAL) + } } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 4f2a1e04db..a7d79aff8d 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -162,7 +162,7 @@ class LightningRepoTest : BaseUnitTest() { .thenReturn(Unit) whenever(lightningService.start(anyOrNull(), any())).thenReturn(Unit) whenever { electrumProbeService.probe(any(), any()) }.thenReturn(Result.success(Unit)) - whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) whenever(connectivityRepo.isOnline).thenReturn(MutableStateFlow(ConnectivityState.CONNECTED)) whenever(settingsStore.data).thenReturn(flowOf(SettingsData())) whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(true) @@ -1343,6 +1343,57 @@ class LightningRepoTest : BaseUnitTest() { assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) } + @Test + fun `spark waits for the node's first listing when its earlier sends were never kept`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + val result = sut.payInvoice("bolt11", 1_000uL) + + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + assertTrue(result.isFailure, "Spark paid while the node's earlier sends were unknown") + } + + @Test + fun `the node's first listing keeps the sends it made before sends were kept`() = test { + startNodeForTesting() + val earlier = { status: PaymentStatus, hash: String -> + PaymentDetails( + id = hash, + kind = PaymentKind.Bolt11( + hash = hash, + preimage = null, + secret = null, + description = null, + bolt11 = hash, + ), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = status, + latestUpdateTimestamp = 0uL, + ) + } + whenever(lightningService.listPayments()).thenReturn( + listOf( + earlier(PaymentStatus.PENDING, "PENDING"), + earlier(PaymentStatus.SUCCEEDED, "paid"), + earlier(PaymentStatus.FAILED, "failed"), + ) + ) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + sut.payInvoice("bolt11", 1_000uL) + + verifyBlocking(cacheStore) { seedLdkSendHashes(listOf("PENDING", "paid")) } + } + @Test fun `a node send is recorded before it leaves`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 48a838cbc9..a79d9524e7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -543,6 +543,29 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService).releaseDepositClaimFee("txid", 0u) } + @Test + fun `wait clears the early claim cap again when another claim held the deposit`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + ClaimDepositOutcome.Deferred( + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ) + ) + // The first call meets Spark's own sync claiming the deposit, which leaves the cap in place. + whenever { sparkService.releaseDepositClaimFee("txid", 0u) } + .thenAnswer { throw SdkException.DepositClaimInProgress("txid", 0u, "") } + .thenReturn(Unit) + val sut = createSut() + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + sut.waitForMatureClaim("txid") + advanceUntilIdle() + + verify(sparkService, times(2)).releaseDepositClaimFee("txid", 0u) + } + @Test fun `wait before any claim attempt leaves the deposit alone`() = test { listDeposit() From 8590ce0fecd15be025cec5716b7537dcd522221b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 04:55:02 +0100 Subject: [PATCH 053/135] fix: recheck spark before the savings swipe commits - The Transfer to Savings swipe commits only while Spark's withdrawal is still priced at the fee and balance shown when the swipe began. - When Spark's balance changed or is being priced again in the 300 ms before the commit, the swipe resets instead of opening progress. --- .../screens/transfer/SavingsConfirmScreen.kt | 17 ++++-- .../to/bitkit/viewmodels/TransferViewModel.kt | 26 ++++++++ .../viewmodels/TransferViewModelTest.kt | 59 +++++++++++++++++++ 3 files changed, 97 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 99abc486d8..6ccf1e6237 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -25,6 +25,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -139,9 +140,9 @@ fun SavingsConfirmScreen( onAmountClick = { currency.switchUnit() }, onAdvancedClick = onAdvancedClick, onSelectAllClick = { transfer.setSavingsSelection(SavingsSelection()) }, - onSwipeConfirm = { - transfer.onTransferToSavingsConfirm(channels, withdrawsSpark) - onConfirm() + onSwipeConfirm = { shownSparkSats, shownFeeSats -> + transfer.confirmSavingsSwipe(channels, withdrawsSpark, shownSparkSats, shownFeeSats) + .also { if (it) onConfirm() } }, onCloseConfirm = { transfer.onTransferToSavingsConfirm(channels, withdrawsSpark, SavingsTransferMode.CLOSE) @@ -182,7 +183,7 @@ private fun SavingsConfirmContent( onAmountClick: () -> Unit = {}, onAdvancedClick: () -> Unit = {}, onSelectAllClick: () -> Unit = {}, - onSwipeConfirm: () -> Unit = {}, + onSwipeConfirm: (shownSparkSats: ULong, shownFeeSats: ULong?) -> Boolean = { _, _ -> true }, onCloseConfirm: () -> Unit = {}, ) { val scope = rememberCoroutineScope() @@ -343,16 +344,22 @@ private fun SavingsConfirmContent( // The swipe always commits the transfer: it swaps when a quote is ready and otherwise // falls back to the pre-swap behaviour of closing the channel, so it is never inert. var isLoading by remember { mutableStateOf(false) } + // Read at swipe time, as the swipe's gesture keeps the lambda from the composition it started in. + val shownSpark by rememberUpdatedState(sparkAmount to sparkFeeSats) + val commitSwipe by rememberUpdatedState(onSwipeConfirm) SwipeToConfirm( text = stringResource(R.string.lightning__transfer__swipe), loading = isLoading || isPricingSwap || isSparkFeePricing, enabled = !isSparkUnpriced && !isNothingSelected, + confirmed = isLoading, color = Colors.Brand, onConfirm = { + val (shownSparkSats, shownFeeSats) = shownSpark scope.launch { isLoading = true delay(300) - onSwipeConfirm() + // Spark changed since the swipe began: reset the swipe so the new fee is approved first. + if (!commitSwipe(shownSparkSats, shownFeeSats)) isLoading = false } } ) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 06919fcaec..b5e30952cf 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -352,6 +352,32 @@ class TransferViewModel @Inject constructor( ?.also { sparkAddress = it } } + /** + * The swipe: commits the transfer only while Spark's withdrawal is still priced at the fee shown when the swipe + * began, for the balance shown then. Returns false without committing when Spark's balance changed or is being + * priced again since, so the swipe resets instead of opening progress. + */ + fun confirmSavingsSwipe( + channels: List, + withdrawSpark: Boolean, + shownSparkSats: ULong, + shownFeeSats: ULong?, + ): Boolean { + if (withdrawSpark && !isSparkPricedAt(shownSparkSats, shownFeeSats)) { + Logger.info("Refused the savings swipe as Spark changed since it was shown", context = TAG) + return false + } + onTransferToSavingsConfirm(channels, withdrawSpark) + return true + } + + private fun isSparkPricedAt(balanceSats: ULong, feeSats: ULong?): Boolean = + feeSats != null && + sparkFeeJob?.isActive != true && + _sparkWithdrawFeeSats.value == feeSats && + sparkFeeBalanceSats == balanceSats && + sparkRepo.state.value.balanceSats == balanceSats + /** * Commit the transfer and pick how it runs. A swap needs a priced quote, so without one * (swaps unsupported on this network, Boltz unreachable, or an amount below the swap diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 962bf3c16e..a832683b1d 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -136,6 +136,63 @@ class TransferViewModelTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } + @Test + fun `the swipe resets when spark's balance is priced again before it commits`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + // A receive lands between the swipe and its commit, so the confirm screen prices the new balance. + whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) }.thenReturn(Result.success(NEW_SPARK_FEE)) + sparkState.value = SparkState(balanceSats = NEW_SPARK_SATS) + sut.loadSparkWithdrawFee(NEW_SPARK_SATS) + + val committed = sut.confirmSavingsSwipe( + channels = emptyList(), + withdrawSpark = true, + shownSparkSats = SPARK_SATS, + shownFeeSats = SPARK_FEE, + ) + + assertFalse(committed) + sut.closeSelectedChannels() + verify(sparkRepo, never()).withdrawAll(any(), any()) + } + + @Test + fun `the swipe resets when spark's balance changes before the screen prices it again`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) }.thenReturn(Result.success(NEW_SPARK_FEE)) + sparkState.value = SparkState(balanceSats = NEW_SPARK_SATS) + + val committed = sut.confirmSavingsSwipe( + channels = emptyList(), + withdrawSpark = true, + shownSparkSats = SPARK_SATS, + shownFeeSats = SPARK_FEE, + ) + + assertFalse(committed) + sut.closeSelectedChannels() + verify(sparkRepo, never()).withdrawAll(any(), any()) + } + + @Test + fun `the swipe commits spark's withdrawal at the fee shown`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + + val committed = sut.confirmSavingsSwipe( + channels = emptyList(), + withdrawSpark = true, + shownSparkSats = SPARK_SATS, + shownFeeSats = SPARK_FEE, + ) + + assertTrue(committed) + sut.closeSelectedChannels() + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) + } + @Test fun `transfer to savings with only channels leaves spark untouched`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) @@ -553,7 +610,9 @@ class TransferViewModelTest : BaseUnitTest() { val CHANNEL_A = createChannelDetails().copy(channelId = "channel_a") val CHANNEL_B = createChannelDetails().copy(channelId = "channel_b") const val SPARK_SATS = 40_000uL + const val NEW_SPARK_SATS = 52_000uL const val SPARK_FEE = 1_470uL + const val NEW_SPARK_FEE = 1_620uL const val CHANNEL_SENDABLE = 60_000uL const val TXID = "tx-abc" const val SPENDABLE_LN = 150_000uL From 99b81bcc421e0d89779eb11ca277baa8cb2555f6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 05:14:21 +0100 Subject: [PATCH 054/135] fix: keep pending send hashes past the cap - Recording a node or Spark send no longer trims the kept hashes, so later sends can't evict one still pending. - A payment listing trims past the cap only hashes it shows as paid, so a pending send behind many paid ones keeps holding the other rail while its own can't list. --- .../main/java/to/bitkit/data/CacheStore.kt | 31 +++++++++++++--- .../to/bitkit/repositories/LightningRepo.kt | 22 +++++++----- .../java/to/bitkit/repositories/SparkRepo.kt | 12 ++++--- .../java/to/bitkit/data/CacheStoreTest.kt | 36 +++++++++++++++++++ .../bitkit/repositories/LightningRepoTest.kt | 36 +++++++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 21 +++++++++++ 6 files changed, 141 insertions(+), 17 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index f1847aace8..8c100d2167 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -22,8 +22,11 @@ import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton -/** How many Spark send hashes to keep; an older send's invoice has long expired, so the node cannot pay it again. */ -private const val MAX_SPARK_SEND_HASHES = 100 +/** + * How many paid send hashes to keep per rail; an older paid send's invoice has long expired, so the other rail + * cannot pay it again. Sends that may still be pending are always kept, past this cap too. + */ +internal const val MAX_SPARK_SEND_HASHES = 100 private val Context.appCacheDataStore: DataStore by dataStore( fileName = "app_cache.json", @@ -142,7 +145,7 @@ class CacheStore internal constructor( suspend fun addSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() store.updateData { - it.copy(sparkSendHashes = (it.sparkSendHashes - hash + hash).takeLast(MAX_SPARK_SEND_HASHES)) + it.copy(sparkSendHashes = it.sparkSendHashes - hash + hash) } } @@ -155,7 +158,7 @@ class CacheStore internal constructor( suspend fun addLdkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() store.updateData { - it.copy(ldkSendHashes = (it.ldkSendHashes - hash + hash).takeLast(MAX_SPARK_SEND_HASHES)) + it.copy(ldkSendHashes = it.ldkSendHashes - hash + hash) } } @@ -166,12 +169,30 @@ class CacheStore internal constructor( if (data.ldkSendHashesSeeded) return@updateData data val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.ldkSendHashes.toSet() data.copy( - ldkSendHashes = (seeded + data.ldkSendHashes).takeLast(MAX_SPARK_SEND_HASHES), + ldkSendHashes = seeded + data.ldkSendHashes, ldkSendHashesSeeded = true, ) } } + /** Past the cap, drops the oldest of the node's sends [paid] lists as paid; a send that may be pending stays. */ + suspend fun trimLdkSendHashes(paid: Set) { + if (store.data.first().ldkSendHashes.size <= MAX_SPARK_SEND_HASHES) return + store.updateData { it.copy(ldkSendHashes = it.ldkSendHashes.withoutOldestPaid(paid)) } + } + + /** Past the cap, drops the oldest of Spark's sends [paid] lists as paid; a send that may be pending stays. */ + suspend fun trimSparkSendHashes(paid: Set) { + if (store.data.first().sparkSendHashes.size <= MAX_SPARK_SEND_HASHES) return + store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes.withoutOldestPaid(paid)) } + } + + private fun List.withoutOldestPaid(paid: Set): List { + val lowercasePaid = paid.mapTo(mutableSetOf()) { it.lowercase() } + var excess = size - MAX_SPARK_SEND_HASHES + return filterNot { hash -> (excess > 0 && hash in lowercasePaid).also { if (it) excess-- } } + } + suspend fun removeLdkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().ldkSendHashes) return diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 3b65d33116..afdb88d6ec 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -430,7 +430,7 @@ class LightningRepo @Inject constructor( lightningService.start(timeout, ::onEvent) _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } - listPaymentsOrNull()?.let { seedLdkSendHashes(it) } + listPaymentsOrNull()?.let { keepLdkSendHashes(it) } // Initial state sync syncState() @@ -1542,7 +1542,7 @@ class LightningRepo @Inject constructor( } return null } - seedLdkSendHashes(payments) + keepLdkSendHashes(payments) val send = payments.firstOrNull { val kind = it.kind as? PaymentKind.Bolt11 ?: return@firstOrNull false it.direction == PaymentDirection.OUTBOUND && @@ -1583,12 +1583,18 @@ class LightningRepo @Inject constructor( .also { syncState() } } - /** Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too. */ - private suspend fun seedLdkSendHashes(payments: List) { - cacheStore.seedLdkSendHashes( - payments - .filter { it.direction == PaymentDirection.OUTBOUND && it.status != PaymentStatus.FAILED } - .mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash } + /** + * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, then trims + * only paid ones past the cap, so a send that may still be pending always holds Spark. + */ + private suspend fun keepLdkSendHashes(payments: List) { + val sends = payments + .filter { it.direction == PaymentDirection.OUTBOUND && it.status != PaymentStatus.FAILED } + .sortedBy { it.latestUpdateTimestamp } + cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }) + cacheStore.trimLdkSendHashes( + sends.filter { it.status == PaymentStatus.SUCCEEDED } + .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } ) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b2c6c5d599..ef54297a78 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -807,9 +807,13 @@ class SparkRepo @Inject constructor( private suspend fun syncActivities() { val payments = sparkService.listPayments() payments.forEach { recordActivity(it) } + val sendHashes = { status: PaymentStatus -> + payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } + } + cacheStore.trimSparkSendHashes(sendHashes(PaymentStatus.COMPLETED) - sendHashes(PaymentStatus.PENDING)) // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a // retry of it is still live. - val failed = payments.mapNotNull { it.failedSendHash() }.distinct() + val failed = payments.mapNotNull { it.sendHash(PaymentStatus.FAILED) }.distinct() .filter { payments.latestSend(it)?.status == PaymentStatus.FAILED } if (failed.isEmpty()) return // A retry can start while the list is recorded, so the release reads Spark's sends again first. @@ -820,8 +824,8 @@ class SparkRepo @Inject constructor( .forEach { cacheStore.removeSparkSendHash(it) } } - private fun Payment.failedSendHash(): String? = (details as? PaymentDetails.Lightning) - ?.takeIf { paymentType == SparkPaymentType.SEND && status == PaymentStatus.FAILED } + private fun Payment.sendHash(status: PaymentStatus): String? = (details as? PaymentDetails.Lightning) + ?.takeIf { paymentType == SparkPaymentType.SEND && this.status == status } ?.htlcDetails?.paymentHash private suspend fun onSdkEvent(event: SdkEvent) { @@ -853,7 +857,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) - payment.failedSendHash()?.let { hash -> + payment.sendHash(PaymentStatus.FAILED)?.let { hash -> val latest = lightningSend(hash) val isReleased = latest == SparkLightningSend.NotFound || (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 915f35d3bf..899cbe3061 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -91,4 +91,40 @@ class CacheStoreTest : BaseUnitTest() { sut.data.first().deletedActivities, ) } + + @Test + fun `a pending node send behind the cap of paid ones stays kept`() = test { + val paid = settledHashes() + sut.seedLdkSendHashes(listOf("pending") + paid) + + sut.trimLdkSendHashes(paid.toSet()) + + val kept = sut.data.first().ldkSendHashes + assertTrue("pending" in kept) + assertEquals(MAX_SPARK_SEND_HASHES, kept.size) + assertFalse(paid.first() in kept, "The oldest paid send was kept over the cap") + } + + @Test + fun `a node send still pending behind the cap of later sends stays kept`() = test { + sut.addLdkSendHash("pending") + settledHashes().forEach { sut.addLdkSendHash(it) } + + assertTrue("pending" in sut.data.first().ldkSendHashes) + } + + @Test + fun `a spark send still pending behind the cap of later sends stays kept`() = test { + sut.addSparkSendHash("pending") + val paid = settledHashes() + paid.forEach { sut.addSparkSendHash(it) } + + sut.trimSparkSendHashes(paid.toSet()) + + val kept = sut.data.first().sparkSendHashes + assertTrue("pending" in kept) + assertEquals(MAX_SPARK_SEND_HASHES, kept.size) + } + + private fun settledHashes() = (1..MAX_SPARK_SEND_HASHES).map { "paid$it" } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a7d79aff8d..e3d088655a 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1394,6 +1394,42 @@ class LightningRepoTest : BaseUnitTest() { verifyBlocking(cacheStore) { seedLdkSendHashes(listOf("PENDING", "paid")) } } + @Test + fun `a node listing trims only its paid sends past the cap`() = test { + startNodeForTesting() + val earlier = { status: PaymentStatus, hash: String -> + PaymentDetails( + id = hash, + kind = PaymentKind.Bolt11( + hash = hash, + preimage = null, + secret = null, + description = null, + bolt11 = hash, + ), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = status, + latestUpdateTimestamp = 0uL, + ) + } + whenever(lightningService.listPayments()).thenReturn( + listOf( + earlier(PaymentStatus.PENDING, "pending"), + earlier(PaymentStatus.SUCCEEDED, "PAID"), + earlier(PaymentStatus.FAILED, "failed"), + ) + ) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + sut.payInvoice("bolt11", 1_000uL) + + verifyBlocking(cacheStore) { trimLdkSendHashes(setOf("paid")) } + } + @Test fun `a node send is recorded before it leaves`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a79d9524e7..58cf8654b3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -258,6 +258,22 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `spark's paid sends are trimmed past the cap when spark syncs on start`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenReturn( + listOf( + sentPayment(fees = 0), + sentPayment(fees = 0).copy(id = "pending", status = PaymentStatus.PENDING).withHash("PENDING"), + ) + ) + val sut = createSut() + + sut.start(0).getOrThrow() + + verifyBlocking(cacheStore) { trimSparkSendHashes(setOf("hash")) } + } + @Test fun `a failed send does not release a hash its retry still holds pending`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) @@ -1076,6 +1092,11 @@ class SparkRepoTest : BaseUnitTest() { details = PaymentDetails.Deposit(txId = "txid", vout = 0u), ) + private fun Payment.withHash(hash: String): Payment { + val lightning = details as PaymentDetails.Lightning + return copy(details = lightning.copy(htlcDetails = lightning.htlcDetails.copy(paymentHash = hash))) + } + private fun sentPayment(fees: Int) = Payment( id = "send", paymentType = PaymentType.SEND, From a8364408f820329a0832bd8ec42b635a66dc84a8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 06:02:44 +0100 Subject: [PATCH 055/135] fix: bound stored send hashes - A payment listing past the cap now trims the oldest sends it shows as paid or failed, so failed sends no longer pile up; a send that may still be pending stays. - Spark's trim keeps a send in flight, so a trim from a listing read before it can't drop it. - An invoice that expires inside the Spark send no longer holds the node, as nothing left the wallet. --- .../main/java/to/bitkit/data/CacheStore.kt | 27 ++++++++++-------- .../to/bitkit/repositories/LightningRepo.kt | 9 +++--- .../java/to/bitkit/repositories/SparkRepo.kt | 12 ++++++-- .../java/to/bitkit/data/CacheStoreTest.kt | 28 +++++++++++++++++++ .../bitkit/repositories/LightningRepoTest.kt | 4 +-- .../to/bitkit/repositories/SparkRepoTest.kt | 19 +++++++++++-- 6 files changed, 77 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 8c100d2167..07498492fc 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -23,8 +23,9 @@ import javax.inject.Inject import javax.inject.Singleton /** - * How many paid send hashes to keep per rail; an older paid send's invoice has long expired, so the other rail - * cannot pay it again. Sends that may still be pending are always kept, past this cap too. + * How many send hashes to keep per rail before a listing drops the oldest it shows as paid or failed; an older paid + * send's invoice has long expired, so the other rail cannot pay it again. Sends that may still be pending, and ones + * no listing has shown yet, are always kept, past this cap too. */ internal const val MAX_SPARK_SEND_HASHES = 100 @@ -175,22 +176,26 @@ class CacheStore internal constructor( } } - /** Past the cap, drops the oldest of the node's sends [paid] lists as paid; a send that may be pending stays. */ - suspend fun trimLdkSendHashes(paid: Set) { + /** + * Past the cap, drops the oldest of the node's sends a listing showed as paid or failed ([settled]); a send that + * may be pending stays. A retry moves its hash to the newest end, so a trim from an older listing drops others + * first. + */ + suspend fun trimLdkSendHashes(settled: Set) { if (store.data.first().ldkSendHashes.size <= MAX_SPARK_SEND_HASHES) return - store.updateData { it.copy(ldkSendHashes = it.ldkSendHashes.withoutOldestPaid(paid)) } + store.updateData { it.copy(ldkSendHashes = it.ldkSendHashes.withoutOldestSettled(settled)) } } - /** Past the cap, drops the oldest of Spark's sends [paid] lists as paid; a send that may be pending stays. */ - suspend fun trimSparkSendHashes(paid: Set) { + /** Past the cap, drops the oldest of Spark's sends a listing showed as paid or failed ([settled]). */ + suspend fun trimSparkSendHashes(settled: Set) { if (store.data.first().sparkSendHashes.size <= MAX_SPARK_SEND_HASHES) return - store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes.withoutOldestPaid(paid)) } + store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes.withoutOldestSettled(settled)) } } - private fun List.withoutOldestPaid(paid: Set): List { - val lowercasePaid = paid.mapTo(mutableSetOf()) { it.lowercase() } + private fun List.withoutOldestSettled(settled: Set): List { + val lowercaseSettled = settled.mapTo(mutableSetOf()) { it.lowercase() } var excess = size - MAX_SPARK_SEND_HASHES - return filterNot { hash -> (excess > 0 && hash in lowercasePaid).also { if (it) excess-- } } + return filterNot { hash -> (excess > 0 && hash in lowercaseSettled).also { if (it) excess-- } } } suspend fun removeLdkSendHash(paymentHash: String) { diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index afdb88d6ec..1e362ade10 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1585,15 +1585,14 @@ class LightningRepo @Inject constructor( /** * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, then trims - * only paid ones past the cap, so a send that may still be pending always holds Spark. + * only paid and failed ones past the cap, so a send that may still be pending always holds Spark. */ private suspend fun keepLdkSendHashes(payments: List) { - val sends = payments - .filter { it.direction == PaymentDirection.OUTBOUND && it.status != PaymentStatus.FAILED } - .sortedBy { it.latestUpdateTimestamp } + val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND } + val sends = outbound.filter { it.status != PaymentStatus.FAILED }.sortedBy { it.latestUpdateTimestamp } cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }) cacheStore.trimLdkSendHashes( - sends.filter { it.status == PaymentStatus.SUCCEEDED } + outbound.filter { it.status != PaymentStatus.PENDING } .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } ) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ef54297a78..24fc056458 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -289,7 +289,11 @@ class SparkRepo @Inject constructor( sendsInFlight.remove(paymentHash.lowercase()) } val payment = sent.getOrElse { - if (it.isInvoiceExpired()) throw SparkError.InvoiceExpired(it) + // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. + if (it.isInvoiceExpired()) { + cacheStore.removeSparkSendHash(paymentHash) + throw SparkError.InvoiceExpired(it) + } // Spark selects the leaves to spend before anything goes to the operators, so a short balance left // nothing, for instance when an earlier send spent it after the balance was read. if (it is SdkException.InsufficientFunds) { @@ -810,7 +814,11 @@ class SparkRepo @Inject constructor( val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } - cacheStore.trimSparkSendHashes(sendHashes(PaymentStatus.COMPLETED) - sendHashes(PaymentStatus.PENDING)) + // A send in flight may be missing from this list, or show only its earlier failed attempt, so it stays. + cacheStore.trimSparkSendHashes( + sendHashes(PaymentStatus.COMPLETED) + sendHashes(PaymentStatus.FAILED) - sendHashes(PaymentStatus.PENDING) - + sendsInFlight.keys + ) // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a // retry of it is still live. val failed = payments.mapNotNull { it.sendHash(PaymentStatus.FAILED) }.distinct() diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 899cbe3061..693677b421 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -126,5 +126,33 @@ class CacheStoreTest : BaseUnitTest() { assertEquals(MAX_SPARK_SEND_HASHES, kept.size) } + @Test + fun `node sends listed as failed are trimmed past the cap, a pending one stays`() = test { + sut.addLdkSendHash("pending") + val failed = settledHashes() + failed.forEach { sut.addLdkSendHash(it) } + + sut.trimLdkSendHashes(failed.toSet()) + + val kept = sut.data.first().ldkSendHashes + assertTrue("pending" in kept) + assertEquals(MAX_SPARK_SEND_HASHES, kept.size) + assertFalse(failed.first() in kept, "The oldest failed send was kept over the cap") + } + + @Test + fun `a retried node send survives a trim from a listing that still shows it failed`() = test { + sut.addLdkSendHash("retried") + val failed = settledHashes() + failed.forEach { sut.addLdkSendHash(it) } + sut.addLdkSendHash("retried") + + sut.trimLdkSendHashes(failed.toSet() + "retried") + + val kept = sut.data.first().ldkSendHashes + assertEquals("retried", kept.last()) + assertEquals(MAX_SPARK_SEND_HASHES, kept.size) + } + private fun settledHashes() = (1..MAX_SPARK_SEND_HASHES).map { "paid$it" } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index e3d088655a..21413117ef 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1395,7 +1395,7 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `a node listing trims only its paid sends past the cap`() = test { + fun `a node listing trims only its paid and failed sends past the cap`() = test { startNodeForTesting() val earlier = { status: PaymentStatus, hash: String -> PaymentDetails( @@ -1427,7 +1427,7 @@ class LightningRepoTest : BaseUnitTest() { sut.payInvoice("bolt11", 1_000uL) - verifyBlocking(cacheStore) { trimLdkSendHashes(setOf("paid")) } + verifyBlocking(cacheStore) { trimLdkSendHashes(setOf("paid", "failed")) } } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 58cf8654b3..fa880bf7f0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -259,19 +259,21 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `spark's paid sends are trimmed past the cap when spark syncs on start`() = test { + fun `spark's paid and failed sends are trimmed past the cap when spark syncs on start`() = test { whenever(sparkService.isConnected).thenReturn(true) whenever { sparkService.listPayments() }.thenReturn( listOf( sentPayment(fees = 0), + sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED).withHash("FAILED"), sentPayment(fees = 0).copy(id = "pending", status = PaymentStatus.PENDING).withHash("PENDING"), + sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED).withHash("PENDING"), ) ) val sut = createSut() sut.start(0).getOrThrow() - verifyBlocking(cacheStore) { trimSparkSendHashes(setOf("hash")) } + verifyBlocking(cacheStore) { trimSparkSendHashes(setOf("hash", "failed")) } } @Test @@ -819,6 +821,19 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } + @Test + fun `an invoice that expired inside the spark send no longer holds the node`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.InvalidInput("Invoice has expired") } + val sut = createSut() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verifyBlocking(cacheStore) { removeSparkSendHash("hash") } + } + @Test fun `insufficient funds inside the spark send is a refusal, not pending`() = test { whenever(sparkService.isConnected).thenReturn(true) From 93497008ebff56db945ed807774b7367191c077e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 10:53:23 +0100 Subject: [PATCH 056/135] fix: refuse a spark funding that changed after approval Before broadcast, a max Spark funding now checks the prepared send-all against the approved quote: the amount reaching Spark must match and the mining fee must not exceed it. A send-all re-reads the balance after the swipe, so new UTXOs could raise the amount sent or the fee with no new confirmation. On a mismatch nothing is broadcast; the screen prices the transfer again and asks for another swipe. A fixed amount stays pinned as before. --- .../to/bitkit/repositories/LightningRepo.kt | 9 ++++ .../repositories/OnchainSendAttemptStore.kt | 3 ++ .../screens/transfer/SparkFundingViewModel.kt | 34 ++++++++---- .../bitkit/repositories/LightningRepoTest.kt | 53 +++++++++++++++++++ .../transfer/SparkFundingViewModelTest.kt | 6 +++ .../viewmodels/AppViewModelSendFlowTest.kt | 17 +++++- 6 files changed, 111 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 1e362ade10..8d29681246 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1714,6 +1714,7 @@ class LightningRepo @Inject constructor( payerIdentity: String? = null, paymentDeadlineAt: Instant? = null, contactPublicKey: String? = null, + approvedMiningFeeSats: ULong? = null, ): Result = executeWhenNodeRunning("sendOnChain") { requireWalletRestoreComplete() require(address.isNotEmpty()) { "Send address cannot be empty" } @@ -1793,6 +1794,14 @@ class LightningRepo @Inject constructor( }.toSet() ) } + if (approvedMiningFeeSats != null) { + val miningFee = prepared.receipt.miningFeeSats + if (prepared.receipt.amountSats != sats || miningFee == null || + miningFee > approvedMiningFeeSats + ) { + throw OnchainSendChangedError() + } + } onchainSendAttemptStore.retainPreparedReceipt( attempt.attemptId, attempt.walletIndex, diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt index 18d69c040a..8a05368c13 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt @@ -190,6 +190,9 @@ class OnchainSendAttemptUnreadableError(cause: Throwable) : AppError("Failed to class OnchainSendNotDispatchedError(cause: Throwable) : AppError("On-chain send did not reach the backend", cause) +/** A send refused before broadcast because it would send another amount, or pay more mining fee, than approved. */ +class OnchainSendChangedError : AppError("On-chain send changed after it was approved") + class OnchainSendPendingError(cause: Throwable, val txid: String? = null) : AppError("On-chain send outcome is unknown; do not send again", cause) 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 af4d5df413..0b66e8d680 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 @@ -36,6 +36,7 @@ import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.OnchainSendBlockedError +import to.bitkit.repositories.OnchainSendChangedError import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim @@ -241,16 +242,10 @@ class SparkFundingViewModel @Inject constructor( _uiState.update { it.copy(isSending = false) } return@launch } - val totalRise = quote.totalSats - shownQuote.totalSats - val spendingDrop = shownQuote.toSpendingSats(shown.speed) - quote.toSpendingSats(shown.speed) - if (totalRise > 0 || spendingDrop > 0) { + val increase = quote.increaseOver(shownQuote, shown.speed) + if (increase > 0) { Logger.info("Asking for another swipe, fees rose since shown", context = TAG) - toast( - title = R.string.lightning__spending_confirm__fees_changed_title, - description = context.getString(R.string.lightning__spending_confirm__fees_changed_network) - .replace("{amount}", formatPrimaryAmount(maxOf(totalRise, spendingDrop))), - type = Toast.ToastType.INFO, - ) + toastFeesChanged(increase) _uiState.update { it.copy(isSending = false) } return@launch } @@ -300,6 +295,8 @@ class SparkFundingViewModel @Inject constructor( feeRates = quotedFeeRates, isTransfer = true, isMaxAmount = state.isMax, + // A send-all spends every coin, so its fee is bound; a fixed amount's coin selection can vary. + approvedMiningFeeSats = quote.networkFeeSats.toULong().takeIf { state.isMax }, ).getOrThrow() if (outcome !is OnchainSendOutcome.Accepted) { Logger.warn("Spark funding was not accepted: '$outcome'", context = TAG) @@ -313,6 +310,14 @@ class SparkFundingViewModel @Inject constructor( } onFundingAccepted(outcome.txid, outcome.amountSats ?: quote.amountSats.toULong(), quote) }.onFailure { + if (it.cause is OnchainSendChangedError) { + Logger.info("Asking for another swipe, the funding changed since approved", context = TAG) + quote().onSuccess { repriced -> + showQuote(repriced) + toastFeesChanged(repriced.increaseOver(quote, state.speed)) + }.onFailure { toastQuoteError() } + return@onFailure + } Logger.error("Failed to fund Spark", it, context = TAG) if (it is OnchainSendBlockedError && showRetainedFunding(quote)) return@onFailure toast( @@ -434,6 +439,13 @@ class SparkFundingViewModel @Inject constructor( private suspend fun spendableSats(): ULong = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats + private fun toastFeesChanged(increaseSats: Long) = toast( + title = R.string.lightning__spending_confirm__fees_changed_title, + description = context.getString(R.string.lightning__spending_confirm__fees_changed_network) + .replace("{amount}", formatPrimaryAmount(increaseSats)), + type = Toast.ToastType.INFO, + ) + private fun toastQuoteError() = toast( title = R.string.lightning__spending_confirm__quote_error_title, description = context.getString(R.string.lightning__spending_confirm__quote_error_text), @@ -491,6 +503,10 @@ interface SparkFundingContract { ) { val totalSats: Long get() = amountSats + networkFeeSats + /** How much more this asks than [approved]: the larger rise in the total or fall in what reaches spending. */ + fun increaseOver(approved: Quote, speed: SparkClaimSpeed): Long = + maxOf(totalSats - approved.totalSats, approved.toSpendingSats(speed) - toSpendingSats(speed)) + /** Whether Savings can pay the amount and its network fee. */ val isCovered: Boolean get() = totalSats <= spendableSats diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 21413117ef..fe6c85ab3c 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2751,6 +2751,59 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(OnchainSendOutcome.Accepted(txid, 900uL), result) } + @Test + fun `a send that grew after approval is refused before broadcast`() = test { + val txid = "ab".repeat(32) + // The approved quote: 99_000 reaches the address for a 500 sat mining fee. + val cases = listOf>( + Triple(99_000uL, 500uL, true), + Triple(99_000uL, 400uL, true), + Triple(99_500uL, 500uL, false), + Triple(98_500uL, 500uL, false), + Triple(99_000uL, 501uL, false), + Triple(99_000uL, null, false), + ) + for ((amount, fee, valid) in cases) { + val original = pendingSendAttempt().copy(amountSats = 99_000uL, isMaxAmount = true, isTransfer = true) + val repo = prepareGuardedSend(original) + var broadcasts = 0 + val prepared = PreparedOnchainSend( + OnchainPreparedReceipt( + txid = txid, + inputs = listOf(OnchainSendInput("11".repeat(32), 0u)), + address = "address", + amountSats = amount, + miningFeeSats = fee, + ), + ) { beforeDispatch -> + beforeDispatch() + broadcasts++ + OnchainSendOutcome.Accepted(txid) + } + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(prepared) + whenever(onchainSendAttemptStore.recordOutcome(any(), any(), any())) + .thenReturn(original.copy(amountSats = amount, evidence = OnchainSendEvidence.Accepted, txid = txid)) + + val result = repo.sendOnChain( + "address", + 99_000uL, + isTransfer = true, + isMaxAmount = true, + approvedMiningFeeSats = 500uL, + ) + + if (valid) { + assertTrue(result.isSuccess, "The approved send must still go out: $amount, $fee") + assertEquals(1, broadcasts) + } else { + val error = assertIs(result.exceptionOrNull(), "Sent $amount for $fee") + assertIs(error.cause) + assertEquals(0, broadcasts) + } + } + } + private fun preparedOutcome(outcome: OnchainSendOutcome) = PreparedOnchainSend( OnchainPreparedReceipt(outcome.txid, listOf(OnchainSendInput("11".repeat(32), 0u)), "address", 1_000uL), ) { 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 c56261594e..3774fb8615 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 @@ -148,6 +148,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -174,6 +175,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Accepted("txid", 50_000uL))) whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(mapOf("txid" to SparkDepositClaim.Later))) @@ -193,6 +195,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { anyOrNull(), eq(false), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) verify(sparkRepo).onDepositBroadcast("txid", 50_000uL) verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Later, 1_350uL) @@ -208,6 +211,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -240,6 +244,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -280,6 +285,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3db1d8409d..0c701c4928 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -7723,7 +7723,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).sendOnChain( any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), any(), any(), any(), any(), anyOrNull(), - anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), ) verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) } @@ -11828,6 +11828,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ), ).doSuspendableAnswer { entered.complete(Unit) @@ -11950,6 +11951,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) verify( paykitPaymentProofRepo @@ -12115,6 +12117,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -12165,6 +12168,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) verify(paykitPaymentProofRepo, never()).markOnchainPaymentStarted( any(), @@ -13119,6 +13123,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -13264,6 +13269,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -13356,6 +13362,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -14612,6 +14619,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -14658,6 +14666,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -14724,6 +14733,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -14852,6 +14862,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -15063,6 +15074,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -16861,6 +16873,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payerIdentity = anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) }.doSuspendableAnswer { invocation -> kotlin.check(invocation.getArgument(0) == address) @@ -18298,7 +18311,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).sendOnChain( any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), any(), any(), any(), any(), anyOrNull(), - anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), ) verify(paykitPaymentRequestRepo, never()).accept(any()) verify(paykitPaymentProofRepo, never()).prepare(any(), any(), any(), any(), anyOrNull(), anyOrNull()) From 14eac0a2617413214d7009f96615926b8f40e0b3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 10:53:24 +0100 Subject: [PATCH 057/135] fix: retry spark activity that failed to save A Spark payment whose activity failed to save is kept and written again at the next refresh, and a start whose activity sync failed to save one leaves the sync to the next start. Before, the failure was dropped and receives or sends with a known fee stayed missing or pending until the app restarted. An activity the user deleted is not written again. --- .../to/bitkit/repositories/ActivityRepo.kt | 5 +- .../java/to/bitkit/repositories/SparkRepo.kt | 38 ++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 47 +++++++++++++++++++ 3 files changed, 78 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt b/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt index f6359b7a5e..b4424b5abf 100644 --- a/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt @@ -857,7 +857,7 @@ class ActivityRepo @Inject constructor( val id = activity.rawId() if (cacheStore.data.first().isActivityDeleted(id, activity.walletId())) { Logger.debug("Activity $id was deleted, skipping", context = TAG) - return@withContext Result.failure(AppError("Activity $id was deleted")) + return@withContext Result.failure(ActivityDeletedError(id)) } coreService.activity.upsert(activity) notifyActivitiesChanged() @@ -1263,3 +1263,6 @@ private data class RbfPublications( val generation: Long = 0, val replacements: Map = emptyMap(), ) + +/** The user deleted the activity, so writing it again is skipped. */ +class ActivityDeletedError(id: String) : AppError("Activity $id was deleted") diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 24fc056458..ca777c6c35 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -119,6 +119,9 @@ class SparkRepo @Inject constructor( /** Sends recorded before Spark knew their fee; its completion event reports 0 until a later sync. */ private val sendsRecordedWithoutFee = ConcurrentHashMap.newKeySet() + /** Payments whose activity failed to save, written again at the next refresh. */ + private val unsavedPayments = ConcurrentHashMap.newKeySet() + private val isCollectingEvents = AtomicBoolean(false) private val refreshMutex = Mutex() @@ -173,7 +176,7 @@ class SparkRepo @Inject constructor( .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } if (connected) _exitStateGeneration.update { it + 1 } refresh() - if (!hasSyncedActivities) syncActivities().also { hasSyncedActivities = true } + if (!hasSyncedActivities) hasSyncedActivities = syncActivities() }.onFailure { Logger.error("Failed to start Spark wallet", it, context = TAG) } @@ -194,6 +197,7 @@ class SparkRepo @Inject constructor( withdrawalTxids.clear() broadcastDeposits.clear() sendsRecordedWithoutFee.clear() + unsavedPayments.clear() sendsInFlight.clear() hasSyncedActivities = false hasMergedRemoteExitState = false @@ -631,7 +635,9 @@ class SparkRepo @Inject constructor( ).withBroadcastDeposits() } markClaimedDeposits(claimed) - payments.filter { it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0 }.forEach { recordActivity(it) } + payments + .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } + .forEach { recordActivity(it) } markTransfers(payments) } @@ -808,9 +814,10 @@ class SparkRepo @Inject constructor( ?.toSet() } - private suspend fun syncActivities() { + /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ + private suspend fun syncActivities(): Boolean { val payments = sparkService.listPayments() - payments.forEach { recordActivity(it) } + val isSaved = payments.map { recordActivity(it) }.all { it } val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } @@ -823,13 +830,14 @@ class SparkRepo @Inject constructor( // retry of it is still live. val failed = payments.mapNotNull { it.sendHash(PaymentStatus.FAILED) }.distinct() .filter { payments.latestSend(it)?.status == PaymentStatus.FAILED } - if (failed.isEmpty()) return + if (failed.isEmpty()) return isSaved // A retry can start while the list is recorded, so the release reads Spark's sends again first. - val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return + val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return isSaved failed .filter { !sendsInFlight.containsKey(it.lowercase()) } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } .forEach { cacheStore.removeSparkSendHash(it) } + return isSaved } private fun Payment.sendHash(status: PaymentStatus): String? = (details as? PaymentDetails.Lightning) @@ -874,15 +882,16 @@ class SparkRepo @Inject constructor( payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } - private suspend fun recordActivity(payment: Payment) { - val lightning = payment.details as? PaymentDetails.Lightning ?: return + /** Returns whether the payment's activity is saved; a failed write is kept in [unsavedPayments]. */ + private suspend fun recordActivity(payment: Payment): Boolean { + val lightning = payment.details as? PaymentDetails.Lightning ?: return true if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { - return + return true } val id = lightning.htlcDetails.paymentHash val existing = (activityRepo.get().getActivity(id).getOrNull() as? Activity.Lightning)?.v1 // Another attempt of the same invoice, on either rail, already paid it. - if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return + if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true val activity = LightningActivity.create( id = id, txType = when (payment.paymentType) { @@ -904,12 +913,19 @@ class SparkRepo @Inject constructor( contact = existing?.contact ?: receivedContact(payment, id), seenAt = existing?.seenAt, ) - activityRepo.get().upsertActivity(Activity.Lightning(activity)) + val saved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) + .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + if (!saved) { + unsavedPayments.add(payment.id) + return false + } + unsavedPayments.remove(payment.id) if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { sendsRecordedWithoutFee.remove(payment.id) } + return true } private suspend fun receivedContact(payment: Payment, paymentHash: String): String? { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fa880bf7f0..4dce7d114b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -393,6 +393,53 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf(0uL, 2uL), activities.allValues.map { (it as Activity.Lightning).v1.fee }) } + @Test + fun `a start whose activity write failed syncs the activities again`() = test { + whenever(sparkService.isConnected).thenReturn(false, true) + whenever(sparkService.connect(0)).thenReturn(true, false) + whenever { sparkService.listPayments() }.thenReturn(listOf(receivedPayment())) + var saved = 0 + whenever { activityRepo.upsertActivity(any()) } + .thenReturn(Result.failure(IllegalStateException("write failed"))) + .thenAnswer { Result.success(Unit).also { saved++ } } + val sut = createSut() + + sut.start(0) + sut.start(0) + + assertTrue(saved > 0, "The receive whose write failed was never saved") + } + + @Test + fun `a receive that failed to save is written again at the next sync`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + whenever { activityRepo.upsertActivity(any()) } + .thenReturn(Result.failure(IllegalStateException("write failed")), Result.success(Unit)) + + sparkEvents.emit(SdkEvent.PaymentSucceeded(receivedPayment())) + whenever { sparkService.listPayments() }.thenReturn(listOf(receivedPayment())) + sparkEvents.emit(SdkEvent.Synced) + sparkEvents.emit(SdkEvent.Synced) + + verify(activityRepo, times(2)).upsertActivity(any()) + } + + @Test + fun `an activity the user deleted is not written again`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(ActivityDeletedError("hash"))) + + sparkEvents.emit(SdkEvent.PaymentSucceeded(receivedPayment())) + whenever { sparkService.listPayments() }.thenReturn(listOf(receivedPayment())) + sparkEvents.emit(SdkEvent.Synced) + + verify(activityRepo, times(1)).upsertActivity(any()) + } + @Test fun `marks a withdrawal's arrival as a transfer by the txid its send returned`() = test { val arrival = OnchainActivity.create( From fc4d936a34644716c289310bced7f9e90635e73d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:09:44 +0100 Subject: [PATCH 058/135] fix: keep spark activity details when its read fails When reading a Spark payment's stored activity fails, the write is skipped and the payment is kept for the next refresh. Before, a failed read counted as no activity, so the rewrite dropped the stored note, contact and seen time. --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 +++- .../to/bitkit/repositories/SparkRepoTest.kt | 34 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ca777c6c35..479480a9ad 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -889,7 +889,12 @@ class SparkRepo @Inject constructor( return true } val id = lightning.htlcDetails.paymentHash - val existing = (activityRepo.get().getActivity(id).getOrNull() as? Activity.Lightning)?.v1 + // A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh. + val stored = activityRepo.get().getActivity(id).getOrElse { + unsavedPayments.add(payment.id) + return false + } + val existing = (stored as? Activity.Lightning)?.v1 // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true val activity = LightningActivity.create( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 4dce7d114b..8e7d83bf99 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -426,6 +426,40 @@ class SparkRepoTest : BaseUnitTest() { verify(activityRepo, times(2)).upsertActivity(any()) } + @Test + fun `a failed activity read keeps its stored note contact and seen time and retries at the next sync`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + val stored = LightningActivity.create( + id = "hash", + txType = ActivityPaymentType.SENT, + status = PaymentState.PENDING, + value = 128uL, + invoice = "lnbc1280n1send", + timestamp = 1uL, + message = "note", + contact = "contact", + seenAt = 5uL, + ) + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn( + Result.failure(IllegalStateException("read failed")), + Result.success(Activity.Lightning(stored)), + ) + + sparkEvents.emit(SdkEvent.PaymentSucceeded(sentPayment(fees = 2))) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + sparkEvents.emit(SdkEvent.Synced) + + val activities = argumentCaptor() + verify(activityRepo, times(1)).upsertActivity(activities.capture()) + val written = (activities.firstValue as Activity.Lightning).v1 + assertEquals("note", written.message) + assertEquals("contact", written.contact) + assertEquals(5uL, written.seenAt) + } + @Test fun `an activity the user deleted is not written again`() = test { whenever(sparkService.isConnected).thenReturn(true) From 309b1868ccc143995cc283e160c3e20203879de3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:31:02 +0100 Subject: [PATCH 059/135] fix: keep paid send guards until their invoices expire --- .../main/java/to/bitkit/data/CacheStore.kt | 79 ++++++++++++++----- .../to/bitkit/repositories/LightningRepo.kt | 16 +++- .../java/to/bitkit/repositories/SparkRepo.kt | 9 ++- .../java/to/bitkit/data/CacheStoreTest.kt | 51 +++++++++++- .../bitkit/repositories/LightningRepoTest.kt | 2 +- .../to/bitkit/repositories/SparkRepoTest.kt | 25 +++++- 6 files changed, 146 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 07498492fc..f593a69419 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -21,11 +21,12 @@ import to.bitkit.models.WalletScope import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton +import kotlin.time.Clock /** - * How many send hashes to keep per rail before a listing drops the oldest it shows as paid or failed; an older paid - * send's invoice has long expired, so the other rail cannot pay it again. Sends that may still be pending, and ones - * no listing has shown yet, are always kept, past this cap too. + * How many send hashes to keep per rail before a listing drops the oldest it shows as failed, or as paid once the + * paid send's invoice has expired, so the other rail cannot pay it again. A paid send with no known expiry is dropped + * like a failed one. Pending sends, unexpired paid ones and ones no listing has shown yet are kept past this cap. */ internal const val MAX_SPARK_SEND_HASHES = 100 @@ -37,6 +38,7 @@ private val Context.appCacheDataStore: DataStore by dataStore( @Singleton class CacheStore internal constructor( private val store: DataStore, + private val clock: Clock = Clock.System, ) { @Inject constructor(@ApplicationContext context: Context) : this(context.appCacheDataStore) @@ -143,26 +145,39 @@ class CacheStore internal constructor( store.updateData { it.copy(pendingLightningMessages = it.pendingLightningMessages - paymentHash) } } - suspend fun addSparkSendHash(paymentHash: String) { + /** Keeps [paymentHash] with its invoice's expiry in epoch seconds, [expiresAt], when known. */ + suspend fun addSparkSendHash(paymentHash: String, expiresAt: Long? = null) { val hash = paymentHash.lowercase() store.updateData { - it.copy(sparkSendHashes = it.sparkSendHashes - hash + hash) + it.copy( + sparkSendHashes = it.sparkSendHashes - hash + hash, + sparkSendExpiries = it.sparkSendExpiries.with(hash, expiresAt), + ) } } suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return - store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes - hash) } + store.updateData { + it.copy(sparkSendHashes = it.sparkSendHashes - hash, sparkSendExpiries = it.sparkSendExpiries - hash) + } } - suspend fun addLdkSendHash(paymentHash: String) { + /** Keeps [paymentHash] with its invoice's expiry in epoch seconds, [expiresAt], when known. */ + suspend fun addLdkSendHash(paymentHash: String, expiresAt: Long? = null) { val hash = paymentHash.lowercase() store.updateData { - it.copy(ldkSendHashes = it.ldkSendHashes - hash + hash) + it.copy( + ldkSendHashes = it.ldkSendHashes - hash + hash, + ldkSendExpiries = it.ldkSendExpiries.with(hash, expiresAt), + ) } } + private fun Map.with(hash: String, expiresAt: Long?) = + if (expiresAt == null) this else this + (hash to expiresAt) + /** Keeps [paymentHashes], the node's pending and paid sends, once, ahead of the hashes kept since. */ suspend fun seedLdkSendHashes(paymentHashes: List) { if (store.data.first().ldkSendHashesSeeded) return @@ -177,31 +192,49 @@ class CacheStore internal constructor( } /** - * Past the cap, drops the oldest of the node's sends a listing showed as paid or failed ([settled]); a send that - * may be pending stays. A retry moves its hash to the newest end, so a trim from an older listing drops others - * first. + * Past the cap, drops the oldest of the node's sends a listing showed as [failed], or as [paid] with an expired or + * unknown invoice expiry; a send that may be pending stays. A retry moves its hash to the newest end, so a trim + * from an older listing drops others first. */ - suspend fun trimLdkSendHashes(settled: Set) { + suspend fun trimLdkSendHashes(paid: Set, failed: Set) { if (store.data.first().ldkSendHashes.size <= MAX_SPARK_SEND_HASHES) return - store.updateData { it.copy(ldkSendHashes = it.ldkSendHashes.withoutOldestSettled(settled)) } + store.updateData { + val (hashes, expiries) = withoutOldestSettled(it.ldkSendHashes, it.ldkSendExpiries, paid, failed) + it.copy(ldkSendHashes = hashes, ldkSendExpiries = expiries) + } } - /** Past the cap, drops the oldest of Spark's sends a listing showed as paid or failed ([settled]). */ - suspend fun trimSparkSendHashes(settled: Set) { + /** Past the cap, drops the oldest of Spark's sends a listing showed as [failed], or as [paid] once expired. */ + suspend fun trimSparkSendHashes(paid: Set, failed: Set) { if (store.data.first().sparkSendHashes.size <= MAX_SPARK_SEND_HASHES) return - store.updateData { it.copy(sparkSendHashes = it.sparkSendHashes.withoutOldestSettled(settled)) } + store.updateData { + val (hashes, expiries) = withoutOldestSettled(it.sparkSendHashes, it.sparkSendExpiries, paid, failed) + it.copy(sparkSendHashes = hashes, sparkSendExpiries = expiries) + } } - private fun List.withoutOldestSettled(settled: Set): List { - val lowercaseSettled = settled.mapTo(mutableSetOf()) { it.lowercase() } - var excess = size - MAX_SPARK_SEND_HASHES - return filterNot { hash -> (excess > 0 && hash in lowercaseSettled).also { if (it) excess-- } } + private fun withoutOldestSettled( + hashes: List, + expiries: Map, + paid: Set, + failed: Set, + ): Pair, Map> { + val now = clock.now().epochSeconds + val paidHashes = paid.mapTo(mutableSetOf()) { it.lowercase() } + val failedHashes = failed.mapTo(mutableSetOf()) { it.lowercase() } + fun droppable(hash: String) = + hash in failedHashes || hash in paidHashes && expiries[hash].let { it == null || it <= now } + var excess = hashes.size - MAX_SPARK_SEND_HASHES + val kept = hashes.filterNot { hash -> (excess > 0 && droppable(hash)).also { if (it) excess-- } } + return kept to expiries.filterKeys { it in kept } } suspend fun removeLdkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().ldkSendHashes) return - store.updateData { it.copy(ldkSendHashes = it.ldkSendHashes - hash) } + store.updateData { + it.copy(ldkSendHashes = it.ldkSendHashes - hash, ldkSendExpiries = it.ldkSendExpiries - hash) + } } suspend fun setBackgroundReceive(details: NewTransactionSheetDetails) = store.updateData { @@ -239,8 +272,12 @@ data class AppCacheData( val pendingLightningMessages: Map = mapOf(), /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ val sparkSendHashes: List = listOf(), + /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ + val sparkSendExpiries: Map = mapOf(), /** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */ val ldkSendHashes: List = listOf(), + /** Invoice expiry in epoch seconds of the [ldkSendHashes] that know it. */ + val ldkSendExpiries: Map = mapOf(), /** * Set once the node's own list has filled [ldkSendHashes], as node sends made before hashes were kept carry none * there. Until then an unlistable node holds every Spark send. diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 8d29681246..dd27e6119d 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1577,7 +1577,7 @@ class LightningRepo @Inject constructor( sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() - cacheStore.addLdkSendHash(ldkSendKey(bolt11, paymentHash)) + cacheStore.addLdkSendHash(ldkSendKey(bolt11, paymentHash), invoiceExpiresAt(bolt11)) runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } .onSuccess { recordSendRail(it, LightningRail.Ldk) } .also { syncState() } @@ -1591,12 +1591,20 @@ class LightningRepo @Inject constructor( val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND } val sends = outbound.filter { it.status != PaymentStatus.FAILED }.sortedBy { it.latestUpdateTimestamp } cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }) - cacheStore.trimLdkSendHashes( - outbound.filter { it.status != PaymentStatus.PENDING } + val hashes = { status: PaymentStatus -> + outbound.filter { it.status == status } .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } - ) + } + cacheStore.trimLdkSendHashes(paid = hashes(PaymentStatus.SUCCEEDED), failed = hashes(PaymentStatus.FAILED)) } + /** When [bolt11] expires, in epoch seconds, or null when it can't be parsed. */ + private fun invoiceExpiresAt(bolt11: String): Long? = runCatching { + val invoice = Bolt11Invoice.fromStr(bolt11) + (invoice.secondsSinceEpoch().safe() + invoice.expiryTimeSeconds().safe()) + .coerceAtMost(Long.MAX_VALUE.toULong()).toLong() + }.getOrNull() + /** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */ private fun ldkSendKey(bolt11: String, paymentHash: String?): String = (paymentHash ?: bolt11).lowercase() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 479480a9ad..b8b2ba4455 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -287,7 +287,9 @@ class SparkRepo @Inject constructor( throw PaymentPendingException(paymentHash) } val sent = try { - cacheStore.addSparkSendHash(paymentHash) + val invoice = method.invoiceDetails + val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() + cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) @@ -822,9 +824,10 @@ class SparkRepo @Inject constructor( payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } // A send in flight may be missing from this list, or show only its earlier failed attempt, so it stays. + val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys cacheStore.trimSparkSendHashes( - sendHashes(PaymentStatus.COMPLETED) + sendHashes(PaymentStatus.FAILED) - sendHashes(PaymentStatus.PENDING) - - sendsInFlight.keys + paid = sendHashes(PaymentStatus.COMPLETED) - live, + failed = sendHashes(PaymentStatus.FAILED) - live, ) // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a // retry of it is still live. diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 693677b421..8394bd4a52 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -13,9 +13,12 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import to.bitkit.ext.scopedActivityId import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant @Config(application = Application::class, sdk = [34]) @RunWith(RobolectricTestRunner::class) @@ -97,7 +100,7 @@ class CacheStoreTest : BaseUnitTest() { val paid = settledHashes() sut.seedLdkSendHashes(listOf("pending") + paid) - sut.trimLdkSendHashes(paid.toSet()) + sut.trimLdkSendHashes(paid = paid.toSet(), failed = emptySet()) val kept = sut.data.first().ldkSendHashes assertTrue("pending" in kept) @@ -119,7 +122,7 @@ class CacheStoreTest : BaseUnitTest() { val paid = settledHashes() paid.forEach { sut.addSparkSendHash(it) } - sut.trimSparkSendHashes(paid.toSet()) + sut.trimSparkSendHashes(paid = paid.toSet(), failed = emptySet()) val kept = sut.data.first().sparkSendHashes assertTrue("pending" in kept) @@ -132,7 +135,7 @@ class CacheStoreTest : BaseUnitTest() { val failed = settledHashes() failed.forEach { sut.addLdkSendHash(it) } - sut.trimLdkSendHashes(failed.toSet()) + sut.trimLdkSendHashes(paid = emptySet(), failed = failed.toSet()) val kept = sut.data.first().ldkSendHashes assertTrue("pending" in kept) @@ -147,12 +150,52 @@ class CacheStoreTest : BaseUnitTest() { failed.forEach { sut.addLdkSendHash(it) } sut.addLdkSendHash("retried") - sut.trimLdkSendHashes(failed.toSet() + "retried") + sut.trimLdkSendHashes(paid = emptySet(), failed = failed.toSet() + "retried") val kept = sut.data.first().ldkSendHashes assertEquals("retried", kept.last()) assertEquals(MAX_SPARK_SEND_HASHES, kept.size) } + @Test + fun `a paid node send whose invoice is unexpired stays past the cap of newer paid ones`() = test { + val store = expiringStore() + store.addLdkSendHash("unexpired", expiresAt = NOW + 3_600) + val paid = settledHashes() + paid.forEach { store.addLdkSendHash(it, expiresAt = NOW - 1) } + + store.trimLdkSendHashes(paid = paid.toSet() + "unexpired", failed = emptySet()) + + val data = store.data.first() + assertTrue("unexpired" in data.ldkSendHashes, "The unexpired paid send was dropped") + assertEquals(NOW + 3_600, data.ldkSendExpiries["unexpired"]) + assertEquals(MAX_SPARK_SEND_HASHES, data.ldkSendHashes.size) + } + + @Test + fun `a paid spark send whose invoice expired is trimmed past the cap with its expiry`() = test { + val store = expiringStore() + store.addSparkSendHash("expired", expiresAt = NOW - 1) + val paid = settledHashes() + paid.forEach { store.addSparkSendHash(it, expiresAt = NOW + 3_600) } + + store.trimSparkSendHashes(paid = paid.toSet() + "expired", failed = emptySet()) + + val data = store.data.first() + assertFalse("expired" in data.sparkSendHashes, "The expired paid send stayed past the cap") + assertFalse("expired" in data.sparkSendExpiries) + } + + private fun expiringStore() = CacheStore( + InMemoryDataStore(AppCacheData()), + object : Clock { + override fun now() = Instant.fromEpochSeconds(NOW) + }, + ) + private fun settledHashes() = (1..MAX_SPARK_SEND_HASHES).map { "paid$it" } + + private companion object { + const val NOW = 1_800_000_000L + } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index fe6c85ab3c..3e5b538adb 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1427,7 +1427,7 @@ class LightningRepoTest : BaseUnitTest() { sut.payInvoice("bolt11", 1_000uL) - verifyBlocking(cacheStore) { trimLdkSendHashes(setOf("paid", "failed")) } + verifyBlocking(cacheStore) { trimLdkSendHashes(paid = setOf("paid"), failed = setOf("failed")) } } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8e7d83bf99..940826a306 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -57,6 +57,7 @@ import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore +import to.bitkit.data.MAX_SPARK_SEND_HASHES import to.bitkit.env.Env import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId @@ -65,6 +66,7 @@ import to.bitkit.models.WalletScope import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.ServiceError import java.io.File import java.math.BigInteger @@ -96,7 +98,7 @@ class SparkRepoTest : BaseUnitTest() { override fun now() = this@SparkRepoTest.now } - private fun createSut() = SparkRepo( + private fun createSut(cacheStore: CacheStore = this.cacheStore) = SparkRepo( bgDispatcher = testDispatcher, sparkService = sparkService, activityRepo = { activityRepo }, @@ -220,7 +222,7 @@ class SparkRepoTest : BaseUnitTest() { createSut().payInvoice("lnbc1280n1send", 128uL).getOrThrow() inOrder(cacheStore, sparkService) { - verifyBlocking(cacheStore) { addSparkSendHash("hash") } + verifyBlocking(cacheStore) { addSparkSendHash(eq("hash"), anyOrNull()) } verifyBlocking(sparkService) { send(any()) } } } @@ -258,6 +260,23 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a paid send whose invoice is unexpired still holds the node behind the cap while spark cant list`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + store.addSparkSendHash("hash", expiresAt = now.epochSeconds + 3_600) + val newer = (1..MAX_SPARK_SEND_HASHES).map { sentPayment(fees = 2).copy(id = "send$it").withHash("newer$it") } + (1..MAX_SPARK_SEND_HASHES).forEach { store.addSparkSendHash("newer$it", expiresAt = now.epochSeconds - 1) } + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2)) + newer) + val sut = createSut(store) + sut.start(0).getOrThrow() + whenever { sparkService.listPayments() }.thenThrow(IllegalStateException("list failed")) + + val earlier = sut.earlierLightningSend("lnbc1280n1other", "hash") + + assertEquals(EarlierSend.Pending("hash"), earlier, "The node may pay an unexpired invoice Spark already paid") + } + @Test fun `spark's paid and failed sends are trimmed past the cap when spark syncs on start`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -273,7 +292,7 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() - verifyBlocking(cacheStore) { trimSparkSendHashes(setOf("hash", "failed")) } + verifyBlocking(cacheStore) { trimSparkSendHashes(paid = setOf("hash"), failed = setOf("failed")) } } @Test From 9e5379821d7591b8238e6c2c9a9500dfcf3939a6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:45:14 +0100 Subject: [PATCH 060/135] fix: withdraw spark to savings at the confirmed fee --- .../screens/transfer/SavingsConfirmScreen.kt | 2 +- .../to/bitkit/viewmodels/TransferViewModel.kt | 10 +++-- .../viewmodels/TransferViewModelTest.kt | 38 +++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 6ccf1e6237..8da726e80c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -145,7 +145,7 @@ fun SavingsConfirmScreen( .also { if (it) onConfirm() } }, onCloseConfirm = { - transfer.onTransferToSavingsConfirm(channels, withdrawsSpark, SavingsTransferMode.CLOSE) + transfer.onTransferToSavingsConfirm(channels, withdrawsSpark, SavingsTransferMode.CLOSE, sparkFeeSats) onConfirm() }, ) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index b5e30952cf..0d4fc6d384 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -80,6 +80,7 @@ class TransferViewModel @Inject constructor( val isSparkWithdrawTooSmall = _isSparkWithdrawTooSmall.asStateFlow() private var sparkFeeJob: Job? = null + private var confirmedSparkFeeSats: ULong? = null private var sparkWithdrawJob: Job? = null private var sparkFeeBalanceSats: ULong? = null private var sparkAddress: String? = null @@ -367,7 +368,7 @@ class TransferViewModel @Inject constructor( Logger.info("Refused the savings swipe as Spark changed since it was shown", context = TAG) return false } - onTransferToSavingsConfirm(channels, withdrawSpark) + onTransferToSavingsConfirm(channels, withdrawSpark, confirmedSparkFeeSats = shownFeeSats) return true } @@ -381,12 +382,14 @@ class TransferViewModel @Inject constructor( /** * Commit the transfer and pick how it runs. A swap needs a priced quote, so without one * (swaps unsupported on this network, Boltz unreachable, or an amount below the swap - * minimum) the transfer closes a channel exactly as it did before swaps existed. + * minimum) the transfer closes a channel exactly as it did before swaps existed. Spark's withdrawal pays at most + * [confirmedSparkFeeSats], the fee shown when the user confirmed, even if the screen prices it again after. */ fun onTransferToSavingsConfirm( channels: List, withdrawSpark: Boolean, mode: SavingsTransferMode = resolveSavingsTransferMode(channels), + confirmedSparkFeeSats: ULong? = _sparkWithdrawFeeSats.value, ) { _savingsTransferMode.update { mode } // Drop any outcome from an earlier attempt so the progress screen cannot act on it. @@ -396,6 +399,7 @@ class TransferViewModel @Inject constructor( _savingsSelection.update { SavingsSelection() } channelsToClose = channels withdrawsSpark = withdrawSpark + this.confirmedSparkFeeSats = confirmedSparkFeeSats } private fun resolveSavingsTransferMode(channels: List): SavingsTransferMode = @@ -424,7 +428,7 @@ class TransferViewModel @Inject constructor( sparkFeeJob?.join() if (sparkRepo.state.value.balanceSats == 0uL) return val address = sparkWithdrawAddress() - val confirmedFeeSats = _sparkWithdrawFeeSats.value + val confirmedFeeSats = confirmedSparkFeeSats if (address == null || confirmedFeeSats == null) { Logger.warn("Skipped Spark withdrawal without an address or a priced fee", context = TAG) _isSparkWithdrawFailed.update { true } diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index a832683b1d..65c5098e52 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -193,6 +193,44 @@ class TransferViewModelTest : BaseUnitTest() { verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) } + @Test + fun `the swipe withdraws spark at the fee it confirmed when spark is priced again before the withdrawal`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + assertTrue( + sut.confirmSavingsSwipe( + channels = emptyList(), + withdrawSpark = true, + shownSparkSats = SPARK_SATS, + shownFeeSats = SPARK_FEE, + ) + ) + repriceSpark() + + sut.closeSelectedChannels() + + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) + } + + @Test + fun `closing instead withdraws spark at the fee shown when spark is priced again before the withdrawal`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true, SavingsTransferMode.CLOSE) + repriceSpark() + + sut.closeSelectedChannels() + + verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) + } + + /** A receive lands during the transition, so the confirm screen prices Spark's new balance. */ + private suspend fun repriceSpark() { + whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) }.thenReturn(Result.success(NEW_SPARK_FEE)) + sparkState.value = SparkState(balanceSats = NEW_SPARK_SATS) + sut.loadSparkWithdrawFee(NEW_SPARK_SATS) + } + @Test fun `transfer to savings with only channels leaves spark untouched`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) From 9b555f519e60039d25116b229b9cb79a6801259b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:45:14 +0100 Subject: [PATCH 061/135] fix: drop node send hashes listed only as failed --- .../main/java/to/bitkit/data/CacheStore.kt | 10 +-- .../to/bitkit/repositories/LightningRepo.kt | 17 +++-- .../bitkit/repositories/LightningRepoTest.kt | 68 ++++++++++++++++++- 3 files changed, 85 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index f593a69419..d6ebaaf6ac 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -229,11 +229,13 @@ class CacheStore internal constructor( return kept to expiries.filterKeys { it in kept } } - suspend fun removeLdkSendHash(paymentHash: String) { - val hash = paymentHash.lowercase() - if (hash !in store.data.first().ldkSendHashes) return + suspend fun removeLdkSendHash(paymentHash: String) = removeLdkSendHashes(setOf(paymentHash)) + + suspend fun removeLdkSendHashes(paymentHashes: Set) { + val hashes = paymentHashes.mapTo(mutableSetOf()) { it.lowercase() } + if (store.data.first().ldkSendHashes.none { it in hashes }) return store.updateData { - it.copy(ldkSendHashes = it.ldkSendHashes - hash, ldkSendExpiries = it.ldkSendExpiries - hash) + it.copy(ldkSendHashes = it.ldkSendHashes - hashes, ldkSendExpiries = it.ldkSendExpiries - hashes) } } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index dd27e6119d..14f19982cd 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -169,6 +169,9 @@ class LightningRepo @Inject constructor( /** The rail each Lightning send last went out on, by payment hash, so a retry settles only from its own rail. */ private val sendRails = ConcurrentHashMap() + /** Node sends under way, kept so a listing read before one began doesn't drop its hash as failed. */ + private val ldkSendsInFlight = ConcurrentHashMap.newKeySet() + @Volatile private var lastKnownNodeId: String? = null @@ -1577,15 +1580,18 @@ class LightningRepo @Inject constructor( sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() - cacheStore.addLdkSendHash(ldkSendKey(bolt11, paymentHash), invoiceExpiresAt(bolt11)) + val key = ldkSendKey(bolt11, paymentHash) + ldkSendsInFlight += key + cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } + .also { ldkSendsInFlight -= key } .onSuccess { recordSendRail(it, LightningRail.Ldk) } .also { syncState() } } /** - * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, then trims - * only paid and failed ones past the cap, so a send that may still be pending always holds Spark. + * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, drops sends + * listed only as failed, then trims paid ones past the cap, so a send that may still be pending always holds Spark. */ private suspend fun keepLdkSendHashes(payments: List) { val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND } @@ -1595,7 +1601,10 @@ class LightningRepo @Inject constructor( outbound.filter { it.status == status } .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } } - cacheStore.trimLdkSendHashes(paid = hashes(PaymentStatus.SUCCEEDED), failed = hashes(PaymentStatus.FAILED)) + val paid = hashes(PaymentStatus.SUCCEEDED) + val live = paid + hashes(PaymentStatus.PENDING) + ldkSendsInFlight + cacheStore.removeLdkSendHashes(hashes(PaymentStatus.FAILED) - live) + cacheStore.trimLdkSendHashes(paid = paid, failed = emptySet()) } /** When [bolt11] expires, in epoch seconds, or null when it can't be parsed. */ diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 3e5b538adb..904a830d8c 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -99,6 +99,7 @@ import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore import to.bitkit.test.connectionRecoveryFixture import to.bitkit.test.idleSparkRepo import to.bitkit.utils.AppError @@ -1395,7 +1396,69 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `a node listing trims only its paid and failed sends past the cap`() = test { + fun `a node send listed only as failed leaves the kept hashes`() = test { + val cache = AppCacheData(ldkSendHashes = listOf("h"), ldkSendHashesSeeded = true) + val store = CacheStore(InMemoryDataStore(cache)) + sut = repoWith(store) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + + startNodeForTesting() + + assertEquals(emptyList(), store.data.first().ldkSendHashes) + } + + @Test + fun `a node retry in flight keeps its hash while an older listing shows it failed`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + val sent = CompletableDeferred() + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .doSuspendableAnswer { sent.await() } + val retry = async { sut.payInvoiceWithNode("h") } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("other")) + + sut.payInvoice("other", 1_000uL) + + assertEquals(listOf("h"), store.data.first().ldkSendHashes) + sent.complete("h") + retry.await() + } + + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( + id = hash, + kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), + amountMsat = 1_000_000uL, + feePaidMsat = null, + direction = PaymentDirection.OUTBOUND, + status = status, + latestUpdateTimestamp = 0uL, + ) + + private fun repoWith(store: CacheStore) = LightningRepo( + bgDispatcher = testDispatcher, + lightningService = lightningService, + settingsStore = settingsStore, + coreService = coreService, + keychain = keychain, + lnurlService = lnurlService, + cacheStore = store, + preActivityMetadataRepo = preActivityMetadataRepo, + onchainSendAttemptStore = onchainSendAttemptStore, + connectivityRepo = connectivityRepo, + vssBackupClientLdk = vssBackupClientLdk, + urlValidator = urlValidator, + electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, + ) + + @Test + fun `a node listing drops its failed sends and trims its paid ones past the cap`() = test { startNodeForTesting() val earlier = { status: PaymentStatus, hash: String -> PaymentDetails( @@ -1427,7 +1490,8 @@ class LightningRepoTest : BaseUnitTest() { sut.payInvoice("bolt11", 1_000uL) - verifyBlocking(cacheStore) { trimLdkSendHashes(paid = setOf("paid"), failed = setOf("failed")) } + verifyBlocking(cacheStore) { removeLdkSendHashes(setOf("failed")) } + verifyBlocking(cacheStore) { trimLdkSendHashes(paid = setOf("paid"), failed = emptySet()) } } @Test From a8c7e86540bf4154aba83916aba2e3e510669dc5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:12:04 +0100 Subject: [PATCH 062/135] fix: trim send hashes by invoice expiry on both rails --- .../main/java/to/bitkit/data/CacheStore.kt | 42 +++++++++---------- .../to/bitkit/repositories/LightningRepo.kt | 33 ++++++++++----- .../java/to/bitkit/repositories/SparkRepo.kt | 6 +-- .../java/to/bitkit/data/CacheStoreTest.kt | 35 +++++++--------- .../bitkit/repositories/LightningRepoTest.kt | 31 ++++++++++++-- 5 files changed, 88 insertions(+), 59 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index d6ebaaf6ac..ad85ac4a36 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -24,9 +24,9 @@ import javax.inject.Singleton import kotlin.time.Clock /** - * How many send hashes to keep per rail before a listing drops the oldest it shows as failed, or as paid once the - * paid send's invoice has expired, so the other rail cannot pay it again. A paid send with no known expiry is dropped - * like a failed one. Pending sends, unexpired paid ones and ones no listing has shown yet are kept past this cap. + * A listing drops a rail's send hashes it shows failed only, or paid once the invoice has expired, so the other rail + * cannot pay it again. Paid sends with no known expiry (kept before expiries were, or whose invoice can't be parsed) + * are dropped oldest first only past this many hashes. Pending sends and ones no listing has shown yet always stay. */ internal const val MAX_SPARK_SEND_HASHES = 100 @@ -192,28 +192,25 @@ class CacheStore internal constructor( } /** - * Past the cap, drops the oldest of the node's sends a listing showed as [failed], or as [paid] with an expired or - * unknown invoice expiry; a send that may be pending stays. A retry moves its hash to the newest end, so a trim - * from an older listing drops others first. + * Drops the node's sends a listing showed as [failed] only, or as [paid] with an expired invoice, and past the cap + * the oldest paid ones with no known expiry; a send that may be pending is never passed in, so it stays. */ suspend fun trimLdkSendHashes(paid: Set, failed: Set) { - if (store.data.first().ldkSendHashes.size <= MAX_SPARK_SEND_HASHES) return store.updateData { - val (hashes, expiries) = withoutOldestSettled(it.ldkSendHashes, it.ldkSendExpiries, paid, failed) + val (hashes, expiries) = withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, paid, failed) it.copy(ldkSendHashes = hashes, ldkSendExpiries = expiries) } } - /** Past the cap, drops the oldest of Spark's sends a listing showed as [failed], or as [paid] once expired. */ + /** Drops Spark's sends as [trimLdkSendHashes] drops the node's. */ suspend fun trimSparkSendHashes(paid: Set, failed: Set) { - if (store.data.first().sparkSendHashes.size <= MAX_SPARK_SEND_HASHES) return store.updateData { - val (hashes, expiries) = withoutOldestSettled(it.sparkSendHashes, it.sparkSendExpiries, paid, failed) + val (hashes, expiries) = withoutSettled(it.sparkSendHashes, it.sparkSendExpiries, paid, failed) it.copy(sparkSendHashes = hashes, sparkSendExpiries = expiries) } } - private fun withoutOldestSettled( + private fun withoutSettled( hashes: List, expiries: Map, paid: Set, @@ -222,20 +219,21 @@ class CacheStore internal constructor( val now = clock.now().epochSeconds val paidHashes = paid.mapTo(mutableSetOf()) { it.lowercase() } val failedHashes = failed.mapTo(mutableSetOf()) { it.lowercase() } - fun droppable(hash: String) = - hash in failedHashes || hash in paidHashes && expiries[hash].let { it == null || it <= now } - var excess = hashes.size - MAX_SPARK_SEND_HASHES - val kept = hashes.filterNot { hash -> (excess > 0 && droppable(hash)).also { if (it) excess-- } } + val listed = hashes.filterNot { hash -> + hash in failedHashes || hash in paidHashes && expiries[hash]?.let { it <= now } == true + } + var excess = listed.size - MAX_SPARK_SEND_HASHES + val kept = listed.filterNot { hash -> + (excess > 0 && hash in paidHashes && hash !in expiries).also { if (it) excess-- } + } return kept to expiries.filterKeys { it in kept } } - suspend fun removeLdkSendHash(paymentHash: String) = removeLdkSendHashes(setOf(paymentHash)) - - suspend fun removeLdkSendHashes(paymentHashes: Set) { - val hashes = paymentHashes.mapTo(mutableSetOf()) { it.lowercase() } - if (store.data.first().ldkSendHashes.none { it in hashes }) return + suspend fun removeLdkSendHash(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash !in store.data.first().ldkSendHashes) return store.updateData { - it.copy(ldkSendHashes = it.ldkSendHashes - hashes, ldkSendExpiries = it.ldkSendExpiries - hashes) + it.copy(ldkSendHashes = it.ldkSendHashes - hash, ldkSendExpiries = it.ldkSendExpiries - hash) } } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 14f19982cd..ddf5b253f7 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -111,6 +111,7 @@ import to.bitkit.utils.UrlValidator import java.io.File import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton @@ -169,9 +170,13 @@ class LightningRepo @Inject constructor( /** The rail each Lightning send last went out on, by payment hash, so a retry settles only from its own rail. */ private val sendRails = ConcurrentHashMap() - /** Node sends under way, kept so a listing read before one began doesn't drop its hash as failed. */ + /** Node sends under way, kept so a listing that shows only an earlier failed attempt doesn't drop its hash. */ private val ldkSendsInFlight = ConcurrentHashMap.newKeySet() + /** Counts node sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ + private val ldkSendRecords = AtomicLong() + private val ldkSendRecordedAt = ConcurrentHashMap() + @Volatile private var lastKnownNodeId: String? = null @@ -433,7 +438,7 @@ class LightningRepo @Inject constructor( lightningService.start(timeout, ::onEvent) _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } - listPaymentsOrNull()?.let { keepLdkSendHashes(it) } + listPaymentsKeepingSendHashes() // Initial state sync syncState() @@ -1535,7 +1540,7 @@ class LightningRepo @Inject constructor( */ private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) - val payments = listPaymentsOrNull() + val payments = listPaymentsKeepingSendHashes() if (payments == null) { val cache = cacheStore.data.first() if (key in cache.ldkSendHashes) return EarlierSend.Pending(key) @@ -1545,7 +1550,6 @@ class LightningRepo @Inject constructor( } return null } - keepLdkSendHashes(payments) val send = payments.firstOrNull { val kind = it.kind as? PaymentKind.Bolt11 ?: return@firstOrNull false it.direction == PaymentDirection.OUTBOUND && @@ -1582,6 +1586,7 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() val key = ldkSendKey(bolt11, paymentHash) ldkSendsInFlight += key + ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet() cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } .also { ldkSendsInFlight -= key } @@ -1589,11 +1594,18 @@ class LightningRepo @Inject constructor( .also { syncState() } } + /** The node's payments after keeping its send hashes from them, or null while it can't list them. */ + private suspend fun listPaymentsKeepingSendHashes(): List? { + val recordsBefore = ldkSendRecords.get() + return listPaymentsOrNull()?.also { keepLdkSendHashes(it, recordsBefore) } + } + /** - * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, drops sends - * listed only as failed, then trims paid ones past the cap, so a send that may still be pending always holds Spark. + * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, then trims + * the ones listed failed only or paid with an expired invoice. A send that may still be pending always holds Spark: + * one in flight, or recorded after [recordsBefore] while the listing was read, can show an earlier failed attempt. */ - private suspend fun keepLdkSendHashes(payments: List) { + private suspend fun keepLdkSendHashes(payments: List, recordsBefore: Long) { val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND } val sends = outbound.filter { it.status != PaymentStatus.FAILED }.sortedBy { it.latestUpdateTimestamp } cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }) @@ -1602,9 +1614,10 @@ class LightningRepo @Inject constructor( .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } } val paid = hashes(PaymentStatus.SUCCEEDED) - val live = paid + hashes(PaymentStatus.PENDING) + ldkSendsInFlight - cacheStore.removeLdkSendHashes(hashes(PaymentStatus.FAILED) - live) - cacheStore.trimLdkSendHashes(paid = paid, failed = emptySet()) + val failed = (hashes(PaymentStatus.FAILED) - paid - hashes(PaymentStatus.PENDING) - ldkSendsInFlight) + .filterTo(mutableSetOf()) { (ldkSendRecordedAt[it] ?: 0) <= recordsBefore } + cacheStore.trimLdkSendHashes(paid = paid, failed = failed) + failed.forEach { ldkSendRecordedAt.remove(it) } } /** When [bolt11] expires, in epoch seconds, or null when it can't be parsed. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b8b2ba4455..824c4fb366 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -825,10 +825,8 @@ class SparkRepo @Inject constructor( } // A send in flight may be missing from this list, or show only its earlier failed attempt, so it stays. val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys - cacheStore.trimSparkSendHashes( - paid = sendHashes(PaymentStatus.COMPLETED) - live, - failed = sendHashes(PaymentStatus.FAILED) - live, - ) + val paid = sendHashes(PaymentStatus.COMPLETED) - live + cacheStore.trimSparkSendHashes(paid = paid, failed = sendHashes(PaymentStatus.FAILED) - paid - live) // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a // retry of it is still live. val failed = payments.mapNotNull { it.sendHash(PaymentStatus.FAILED) }.distinct() diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 8394bd4a52..ae0c71bc8e 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -130,31 +130,27 @@ class CacheStoreTest : BaseUnitTest() { } @Test - fun `node sends listed as failed are trimmed past the cap, a pending one stays`() = test { + fun `node sends listed failed only are dropped under the cap too, a pending one stays`() = test { sut.addLdkSendHash("pending") - val failed = settledHashes() - failed.forEach { sut.addLdkSendHash(it) } + sut.addLdkSendHash("failed") - sut.trimLdkSendHashes(paid = emptySet(), failed = failed.toSet()) + sut.trimLdkSendHashes(paid = emptySet(), failed = setOf("failed")) - val kept = sut.data.first().ldkSendHashes - assertTrue("pending" in kept) - assertEquals(MAX_SPARK_SEND_HASHES, kept.size) - assertFalse(failed.first() in kept, "The oldest failed send was kept over the cap") + assertEquals(listOf("pending"), sut.data.first().ldkSendHashes) } @Test - fun `a retried node send survives a trim from a listing that still shows it failed`() = test { - sut.addLdkSendHash("retried") - val failed = settledHashes() - failed.forEach { sut.addLdkSendHash(it) } - sut.addLdkSendHash("retried") + fun `a paid spark send whose invoice expired is dropped under the cap, an unexpired one stays`() = test { + val store = expiringStore() + store.addSparkSendHash("expired", expiresAt = NOW) + store.addSparkSendHash("unexpired", expiresAt = NOW + 1) + store.addSparkSendHash("unknown") - sut.trimLdkSendHashes(paid = emptySet(), failed = failed.toSet() + "retried") + store.trimSparkSendHashes(paid = setOf("expired", "unexpired", "unknown"), failed = emptySet()) - val kept = sut.data.first().ldkSendHashes - assertEquals("retried", kept.last()) - assertEquals(MAX_SPARK_SEND_HASHES, kept.size) + val data = store.data.first() + assertEquals(listOf("unexpired", "unknown"), data.sparkSendHashes) + assertEquals(mapOf("unexpired" to NOW + 1), data.sparkSendExpiries) } @Test @@ -167,9 +163,8 @@ class CacheStoreTest : BaseUnitTest() { store.trimLdkSendHashes(paid = paid.toSet() + "unexpired", failed = emptySet()) val data = store.data.first() - assertTrue("unexpired" in data.ldkSendHashes, "The unexpired paid send was dropped") - assertEquals(NOW + 3_600, data.ldkSendExpiries["unexpired"]) - assertEquals(MAX_SPARK_SEND_HASHES, data.ldkSendHashes.size) + assertEquals(listOf("unexpired"), data.ldkSendHashes, "The unexpired paid send was dropped") + assertEquals(mapOf("unexpired" to NOW + 3_600), data.ldkSendExpiries) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 904a830d8c..a1d27d5cc9 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1430,6 +1430,32 @@ class LightningRepoTest : BaseUnitTest() { retry.await() } + @Test + fun `a node retry that ends while an older listing is read keeps its hash`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + var isRetried = false + // The node retries the invoice, and its send returns, after this listing was read with the failed attempt. + whenever(lightningService.listPayments()).doSuspendableAnswer { + val listed = listOf(nodeSend("h", PaymentStatus.FAILED)) + if (!isRetried) { + isRetried = true + sut.payInvoiceWithNode("h") + } + listed + } + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("other")) + + sut.payInvoice("other", 1_000uL) + + assertEquals(listOf("h"), store.data.first().ldkSendHashes) + } + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( id = hash, kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), @@ -1458,7 +1484,7 @@ class LightningRepoTest : BaseUnitTest() { ) @Test - fun `a node listing drops its failed sends and trims its paid ones past the cap`() = test { + fun `a node listing trims its paid and failed sends but not its pending ones`() = test { startNodeForTesting() val earlier = { status: PaymentStatus, hash: String -> PaymentDetails( @@ -1490,8 +1516,7 @@ class LightningRepoTest : BaseUnitTest() { sut.payInvoice("bolt11", 1_000uL) - verifyBlocking(cacheStore) { removeLdkSendHashes(setOf("failed")) } - verifyBlocking(cacheStore) { trimLdkSendHashes(paid = setOf("paid"), failed = emptySet()) } + verifyBlocking(cacheStore) { trimLdkSendHashes(paid = setOf("paid"), failed = setOf("failed")) } } @Test From 02b16e9ac0d6d7b88feea36598a27da8bc07b946 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:19:13 +0100 Subject: [PATCH 063/135] fix: claim an older spark funding only at its own approval --- .../screens/transfer/SparkFundingViewModel.kt | 29 ++++++++++----- .../transfer/SparkFundingViewModelTest.kt | 35 +++++++++++++++++++ 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 0b66e8d680..6f39e3fd2c 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 @@ -300,7 +300,7 @@ class SparkFundingViewModel @Inject constructor( ).getOrThrow() if (outcome !is OnchainSendOutcome.Accepted) { Logger.warn("Spark funding was not accepted: '$outcome'", context = TAG) - if (showRetainedFunding(quote)) return@runSuspendCatching + if (showRetainedFunding(quote, isThisSwipes = true)) return@runSuspendCatching error("Spark funding was not accepted: '$outcome'") } withContext(NonCancellable) { @@ -319,7 +319,7 @@ class SparkFundingViewModel @Inject constructor( return@onFailure } Logger.error("Failed to fund Spark", it, context = TAG) - if (it is OnchainSendBlockedError && showRetainedFunding(quote)) return@onFailure + if (it is OnchainSendBlockedError && showRetainedFunding(quote, isThisSwipes = false)) return@onFailure toast( title = R.string.lightning__close_error, description = context.getString(R.string.wallet__send_error_create_tx), @@ -328,28 +328,39 @@ class SparkFundingViewModel @Inject constructor( _uiState.update { it.copy(isSending = false) } } - private suspend fun onFundingAccepted(txid: String, amountSats: ULong, quote: Quote) { + /** With [ceilingSats] 0, as for a funding no swipe on this screen approved, an early claim asks first. */ + private suspend fun onFundingAccepted( + txid: String, + amountSats: ULong, + quote: Quote, + ceilingSats: ULong = quote.instantFeeSats.toULong(), + ) { val speed = _uiState.value.speed withContext(NonCancellable) { sparkRepo.onDepositBroadcast(txid, amountSats) - sparkRepo.followDepositClaim(txid, speed, quote.instantFeeSats.toULong()) + sparkRepo.followDepositClaim(txid, speed, ceilingSats) } Logger.info("Funded Spark with '$amountSats' sats in '$txid'", context = TAG) _uiState.update { it.copy(txid = txid, claim = sparkRepo.depositClaims.value[txid] ?: it.claim) } _effects.emit(SideEffect.Sent) } - // A signed funding that was not accepted is kept; Payment Pending shows it and retries it at a new fee. - private suspend fun showRetainedFunding(quote: Quote): Boolean { + // A signed funding that was not accepted is kept; Payment Pending shows it and retries it at a new fee. A swipe + // refused for an earlier funding approved no claim fee for it: one this screen already follows keeps its own, + // and one from before, as after a relaunch, asks before an early claim. + private suspend fun showRetainedFunding(quote: Quote, isThisSwipes: Boolean): Boolean { val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() if (attempt == null || !attempt.isTransfer || !attempt.blocksNextSend) return false - watchRetainedFunding(attempt, quote) + when { + isThisSwipes -> watchRetainedFunding(attempt, quote, quote.instantFeeSats.toULong()) + attempt.attemptId != ownedFundingAttemptId -> watchRetainedFunding(attempt, quote, ceilingSats = 0uL) + } _effects.emit(SideEffect.FundingPending(attempt)) return true } // Payment Pending can be dismissed, so the confirm screen leaves for Setting Up once the kept funding completes. - private fun watchRetainedFunding(retained: OnchainSendAttempt, quote: Quote) { + private fun watchRetainedFunding(retained: OnchainSendAttempt, quote: Quote, ceilingSats: ULong) { retainedFundingJob?.cancel() ownedFundingAttemptId?.takeIf { it != retained.attemptId } ?.let { lightningRepo.followFundingOnScreen(it, isFollowed = false) } @@ -363,7 +374,7 @@ class SparkFundingViewModel @Inject constructor( it.attemptId == retained.attemptId && it.address == quote.address && it.hasPositiveEvidence && it.localFollowupComplete && it.txid != null } - onFundingAccepted(requireNotNull(completed.txid), completed.amountSats, quote) + onFundingAccepted(requireNotNull(completed.txid), completed.amountSats, quote, ceilingSats) } } 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 3774fb8615..26a9229bf4 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 @@ -32,6 +32,7 @@ import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.OnchainSendAttempt +import to.bitkit.repositories.OnchainSendBlockedError import to.bitkit.repositories.OnchainSendEvidence import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.SparkClaimSpeed @@ -277,6 +278,40 @@ class SparkFundingViewModelTest : BaseUnitTest() { verify(lightningRepo, never()).followFundingOnScreen("attempt", false) } + @Test + fun `a swipe refused for an older funding after a relaunch leaves that funding's early claim asking`() = test { + val older = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "older", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + }.thenReturn(Result.failure(OnchainSendBlockedError(older))) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(older) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + sut.onConfirm() + advanceUntilIdle() + + val confirmed = older.copy(evidence = OnchainSendEvidence.Observed, localFollowupComplete = true) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(confirmed) + attemptUpdates.value++ + advanceUntilIdle() + + verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Instant, 0uL) + } + @Test fun `the funding screen owns a kept funding until it closes`() = test { whenever { From 95f1c9a95df0b44f0e1efe9ab5ee52f90b30b7d7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:03:46 +0100 Subject: [PATCH 064/135] fix: restore the spending amount screen layout --- .../screens/transfer/SpendingAmountScreen.kt | 106 ++++++++---------- 1 file changed, 47 insertions(+), 59 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt index dde1890aee..68a2bc498d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt @@ -9,7 +9,6 @@ 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.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.material3.HorizontalDivider @@ -31,6 +30,7 @@ import to.bitkit.repositories.CurrencyState import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.Display +import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.FillWidth import to.bitkit.ui.components.MoneySSB import to.bitkit.ui.components.NumberPad @@ -198,69 +198,60 @@ private fun SpendingAmountNodeRunning( .testTag("${tag}NumberField") ) - // Keys shrink on short screens, so Continue stays visible below the pad. - Column( - verticalArrangement = Arrangement.Bottom, - modifier = Modifier - .weight(1f) - .fillMaxWidth() + FillHeight() + + Row( + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.testTag( + if (isHardware) "HardwareTransferAmountNumberPad" else "SendAmountNumberPad" + ) ) { - Row( - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.testTag( - if (isHardware) "HardwareTransferAmountNumberPad" else "SendAmountNumberPad" - ) - ) { - Column { - Text13Up( - text = stringResource(R.string.wallet__send_available), - color = Colors.White64, - modifier = Modifier.testTag("${tag}Available") - ) - VerticalSpacer(8.dp) - MoneySSB( - sats = uiState.maxSats, - showSymbol = true, - modifier = Modifier.testTag("${tag}Unit") - ) - } - FillWidth() - UnitButton( - color = Colors.Purple, - onClick = { amountInputViewModel.switchUnit(currencies) }, - modifier = Modifier.testTag( - if (isHardware) "HardwareTransferAmountUnitButton" else "SpendingNumberPadUnit" - ) - ) - NumberPadActionButton( - text = stringResource(R.string.lightning__spending_amount__quarter), - color = Colors.Purple, - enabled = isReady && hasFunds, - onClick = onClickQuarter, - modifier = Modifier.testTag("${tag}Quarter") + Column { + Text13Up( + text = stringResource(R.string.wallet__send_available), + color = Colors.White64, + modifier = Modifier.testTag("${tag}Available") ) - NumberPadActionButton( - text = stringResource(R.string.common__max), - color = Colors.Purple, - enabled = isReady && hasFunds, - onClick = onClickMaxAmount, - modifier = Modifier.testTag("${tag}Max") + VerticalSpacer(8.dp) + MoneySSB( + sats = uiState.maxSats, + showSymbol = true, + modifier = Modifier.testTag("${tag}Unit") ) } - - HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) - - NumberPad( - viewModel = amountInputViewModel, - currencies = currencies, + FillWidth() + UnitButton( + color = Colors.Purple, + onClick = { amountInputViewModel.switchUnit(currencies) }, + modifier = Modifier.testTag( + if (isHardware) "HardwareTransferAmountUnitButton" else "SpendingNumberPadUnit" + ) + ) + NumberPadActionButton( + text = stringResource(R.string.lightning__spending_amount__quarter), + color = Colors.Purple, enabled = isReady && hasFunds, - modifier = Modifier - .weight(1f) - .heightIn(max = NUMBER_PAD_MAX_HEIGHT) + onClick = onClickQuarter, + modifier = Modifier.testTag("${tag}Quarter") + ) + NumberPadActionButton( + text = stringResource(R.string.common__max), + color = Colors.Purple, + enabled = isReady && hasFunds, + onClick = onClickMaxAmount, + modifier = Modifier.testTag("${tag}Max") ) } + HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) + + NumberPad( + viewModel = amountInputViewModel, + currencies = currencies, + enabled = isReady && hasFunds, + ) + PrimaryButton( text = stringResource(R.string.common__continue), onClick = onConfirmAmount, @@ -273,9 +264,6 @@ private fun SpendingAmountNodeRunning( } } -/** The number pad's height at its ideal key size. */ -private val NUMBER_PAD_MAX_HEIGHT = 300.dp - @Preview(showSystemUi = true) @Preview(showSystemUi = true, device = "id:pixel_9_pro_xl", name = "Large") @Preview(showSystemUi = true, device = NEXUS_5, name = "Small") From 73806c5a1507763ddbc2e8ecec20d18d35ee8cc0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:12:58 +0100 Subject: [PATCH 065/135] fix: restore the setting up screen illustration and steps --- .../screens/transfer/SavingsProgressScreen.kt | 1 + .../ui/screens/transfer/SettingUpScreen.kt | 44 ++++++------- .../components/TransferAnimationView.kt | 64 +++++++++++++++++++ app/src/main/res/values-ar/strings.xml | 6 +- app/src/main/res/values-b+es+419/strings.xml | 6 +- app/src/main/res/values-ca/strings.xml | 6 +- app/src/main/res/values-cs/strings.xml | 6 +- app/src/main/res/values-de/strings.xml | 6 +- app/src/main/res/values-el/strings.xml | 6 +- app/src/main/res/values-es-rES/strings.xml | 6 +- app/src/main/res/values-es/strings.xml | 6 +- app/src/main/res/values-fr/strings.xml | 6 +- app/src/main/res/values-it/strings.xml | 6 +- app/src/main/res/values-nl/strings.xml | 6 +- app/src/main/res/values-pl/strings.xml | 6 +- app/src/main/res/values-pt-rBR/strings.xml | 6 +- app/src/main/res/values-pt/strings.xml | 6 +- app/src/main/res/values-ru/strings.xml | 6 +- app/src/main/res/values/strings.xml | 6 +- .../screens/transfer/SettingUpScreenTest.kt | 2 +- 20 files changed, 135 insertions(+), 72 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt index 843ae080b3..7a63b9649f 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt @@ -224,6 +224,7 @@ private fun Content( TransferAnimationView( largeCircleRes = R.drawable.onchain_sync_large, smallCircleRes = R.drawable.onchain_sync_small, + keepAssetRatios = true, ) } else { Box( diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt index 9fbe7512af..a6f91b1bf7 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt @@ -5,9 +5,9 @@ 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.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue @@ -43,6 +43,7 @@ import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.localizedRandom import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright /** Confirmations Spark waits for before it adds a deposit by itself. */ private const val MATURE_CONFIRMATIONS = 3 @@ -50,9 +51,6 @@ private const val MATURE_CONFIRMATIONS = 3 /** About how long [MATURE_CONFIRMATIONS] take. */ private const val MATURE_MINUTES = 30 -/** The arrows' share of the illustration, as on iOS, so the inner circle shows around them. */ -private const val FIGURE_FRACTION = 0.85f - @Composable fun SettingUpScreen( viewModel: SparkFundingViewModel, @@ -112,7 +110,7 @@ internal fun Content( ) VerticalSpacer(8.dp) BodyM( - text = claimText(claim), + text = claimText(claim).withAccentBoldBright(), color = Colors.White64, modifier = Modifier .fillMaxWidth() @@ -141,23 +139,18 @@ internal fun Content( } VerticalSpacer(28.dp) if (inProgress) { - Box( - contentAlignment = Alignment.Center, + TransferAnimationView( + largeCircleRes = R.drawable.ln_sync_large, + smallCircleRes = R.drawable.ln_sync_small, + keepAssetRatios = true, modifier = Modifier .weight(1f) .fillMaxWidth() - ) { - TransferAnimationView( - largeCircleRes = R.drawable.ln_sync_large, - smallCircleRes = R.drawable.ln_sync_small, - contentWidthFraction = FIGURE_FRACTION, - modifier = Modifier.aspectRatio(1f) - ) - } + ) VerticalSpacer(16.dp) val steps = persistentListOf( - stringResource(R.string.lightning__setting_up__step_sent), - stringResource(R.string.lightning__setting_up__step_seen), + stringResource(R.string.lightning__setting_up_step1), + stringResource(R.string.lightning__setting_up_step2), stringResource(R.string.lightning__setting_up__step_adding), ) ProgressSteps( @@ -167,14 +160,19 @@ internal fun Content( ) VerticalSpacer(16.dp) } else { - Image( - painter = painterResource(id = R.drawable.check), - contentDescription = null, - contentScale = ContentScale.Fit, + Box( + contentAlignment = Alignment.Center, modifier = Modifier .weight(1f) - .padding(16.dp) - ) + .fillMaxWidth() + ) { + Image( + painter = painterResource(id = R.drawable.check), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier.size(256.dp) + ) + } } if (claim is SparkDepositClaim.Repriced) { diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt index 8be2b81f69..097f76eb43 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt @@ -10,9 +10,11 @@ import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -20,6 +22,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @@ -34,6 +37,7 @@ fun TransferAnimationView( @DrawableRes contentRes: Int = R.drawable.transfer, rotateContent: Boolean = true, contentWidthFraction: Float = 1f, + keepAssetRatios: Boolean = false, ) { val animationSpec: InfiniteRepeatableSpec = infiniteRepeatable( animation = tween(durationMillis = 3000, easing = EaseInOut), @@ -64,6 +68,17 @@ fun TransferAnimationView( animationSpec = animationSpec, label = "rotationArrows", ) + if (keepAssetRatios) { + ScaledLayers( + largeCircleRes = largeCircleRes, + smallCircleRes = smallCircleRes, + contentRes = contentRes, + rotationLarge = rotationLarge, + rotationSmall = rotationSmall, + rotationContent = if (rotateContent) rotationArrows else 0f, + ) + return@Box + } Image( painter = painterResource(largeCircleRes), contentDescription = null, @@ -100,6 +115,55 @@ fun TransferAnimationView( } } +/** + * Draws the rings and figure at their sizes relative to the large ring, as the design sets them, at any density: + * the assets are `nodpi`, so drawn at their own pixel size the small ring grows against the clamped large one. + */ +@Composable +private fun ScaledLayers( + @DrawableRes largeCircleRes: Int, + @DrawableRes smallCircleRes: Int, + @DrawableRes contentRes: Int, + rotationLarge: Float, + rotationSmall: Float, + rotationContent: Float, +) { + val large = painterResource(largeCircleRes) + val small = painterResource(smallCircleRes) + val content = painterResource(contentRes) + val largeWidth = large.intrinsicSize.width + val maxSize = with(LocalDensity.current) { largeWidth.toDp() } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .widthIn(max = maxSize) + .aspectRatio(1f), + ) { + Image( + painter = large, + contentDescription = null, + modifier = Modifier + .fillMaxSize() + .rotate(rotationLarge), + ) + Image( + painter = small, + contentDescription = null, + modifier = Modifier + .fillMaxSize(small.intrinsicSize.width / largeWidth) + .rotate(rotationSmall), + ) + Image( + painter = content, + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .fillMaxSize(content.intrinsicSize.width / largeWidth) + .rotate(rotationContent), + ) + } +} + @Preview @Composable private fun PreviewSyncing() { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 7c0396b6d5..c5d5c6abad 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -212,13 +212,13 @@ وقت مزامنة درجات تحديد المسار لم يرَ Spark تحويلك بعد. يُضاف بعد 3 تأكيدات؛ يمكنك مغادرة هذه الشاشة. ادفع ₿ {amount} - أصبح الفوري يكلّف الآن ₿ {amount}. ادفعه، أو انتظر 3 تأكيدات، نحو 30 دقيقة، برسوم أقل. + أصبح الفوري يكلّف الآن <accent>₿ {amount}</accent>. ادفعه، أو انتظر 3 تأكيدات، نحو 30 دقيقة، برسوم أقل. السرعة: {speed} جارٍ الإضافة إلى الإنفاق - رآه Spark - تم إرسال التحويل الفوري غير متاح لهذا التحويل. يضيفه Spark إلى رصيد الإنفاق بعد 3 تأكيدات، نحو 30 دقيقة. متابعة استخدام Bitkit + جارٍ معالجة الدفع + الدفع ناجح Spark رسوم المطالبة %1$d/3 تأكيدات 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 2d338c238b..e55671de1f 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -219,13 +219,13 @@ Hora de sincronización de puntuaciones de ruta Spark todavía no vio tu transferencia. Se agrega después de 3 confirmaciones; puedes salir de esta pantalla. Pagar ₿ {amount} - Instantáneo ahora cuesta ₿ {amount}. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Instantáneo ahora cuesta <accent>₿ {amount}</accent>. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. Velocidad: {speed} Agregando a gastos - Visto por Spark - Transferencia enviada Instantáneo no está disponible para esta transferencia. Spark la agrega a tu saldo para gastos después de 3 confirmaciones, unos 30 minutos. Continuar Usando Bitkit + Procesando pago + Pago Efectuado Spark Comisión de reclamo %1$d/3 confirmaciones diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 1ee5cf79a7..9f8aebd4de 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -216,13 +216,13 @@ Temps de sincronització de puntuacions de rutes Spark encara no ha vist la teva transferència. S\'afegeix després de 3 confirmacions; pots sortir d\'aquesta pantalla. Paga ₿ {amount} - Instant ara costa ₿ {amount}. Paga-ho o espera 3 confirmacions, uns 30 minuts, amb una comissió més baixa. + Instant ara costa <accent>₿ {amount}</accent>. Paga-ho o espera 3 confirmacions, uns 30 minuts, amb una comissió més baixa. Velocitat: {speed} Afegint a despesa - Vist per Spark - Transferència enviada Instant no està disponible per a aquesta transferència. Spark l\'afegeix al teu saldo de despesa després de 3 confirmacions, uns 30 minuts. Continua utilitzant Bitkit + Processant pagament + Pagament realitzat amb èxit Spark Comissió de reclamació %1$d/3 confirmacions diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 47df4ab171..861c66fb5d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -219,13 +219,13 @@ Čas synchronizace skóre hledání cest Spark tvůj převod zatím neviděl. Připíše se po 3 potvrzeních; tuto obrazovku můžeš opustit. Zaplatit ₿ {amount} - Okamžitě nyní stojí ₿ {amount}. Zaplať, nebo počkej na 3 potvrzení, asi 30 minut, s nižším poplatkem. + Okamžitě nyní stojí <accent>₿ {amount}</accent>. Zaplať, nebo počkej na 3 potvrzení, asi 30 minut, s nižším poplatkem. Rychlost: {speed} Přidávání do výdajů - Viděno Sparkem - Převod odeslán Okamžitě není pro tento převod dostupné. Spark ho přidá do tvého zůstatku pro výdaje po 3 potvrzeních, asi za 30 minut. Pokračujte v používání Bitkit + Zpracování platby + Platba úspěšně proběhla Spark Poplatek za připsání %1$d/3 potvrzení diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 873273a35b..1242920b8a 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -273,13 +273,13 @@ Pathfinding-Scores Sync-Zeit Spark hat deine Überweisung noch nicht gesehen. Sie wird nach 3 Bestätigungen gutgeschrieben; du kannst diesen Bildschirm verlassen. ₿ {amount} zahlen - Sofort kostet jetzt ₿ {amount}. Zahle es oder warte auf 3 Bestätigungen, etwa 30 Minuten, zu einer niedrigeren Gebühr. + Sofort kostet jetzt <accent>₿ {amount}</accent>. Zahle es oder warte auf 3 Bestätigungen, etwa 30 Minuten, zu einer niedrigeren Gebühr. Geschwindigkeit: {speed} Wird hinzugefügt - Von Spark gesehen - Überweisung gesendet Sofort ist für diese Überweisung nicht verfügbar. Spark fügt sie nach 3 Bestätigungen, etwa 30 Minuten, deinem Ausgabenguthaben hinzu. Bitkit weiter verwenden + Zahlung wird verarbeitet + Zahlung erfolgreich Onchain verfügbar Gesamte Anchor-Channels-Reserve Gesamt Lightning diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index ccd1a458c5..04699667fa 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -212,13 +212,13 @@ Χρόνος συγχρονισμού βαθμολογιών εύρεσης διαδρομής Το Spark δεν έχει δει ακόμα τη μεταφορά σου. Προστίθεται μετά από 3 επιβεβαιώσεις· μπορείς να φύγεις από αυτή την οθόνη. Πλήρωσε ₿ {amount} - Το Άμεσα κοστίζει τώρα ₿ {amount}. Πλήρωσέ το ή περίμενε 3 επιβεβαιώσεις, περίπου 30 λεπτά, με χαμηλότερη χρέωση. + Το Άμεσα κοστίζει τώρα <accent>₿ {amount}</accent>. Πλήρωσέ το ή περίμενε 3 επιβεβαιώσεις, περίπου 30 λεπτά, με χαμηλότερη χρέωση. Ταχύτητα: {speed} Προσθήκη στις δαπάνες - Το είδε το Spark - Η μεταφορά στάλθηκε Το Άμεσα δεν είναι διαθέσιμο για αυτή τη μεταφορά. Το Spark την προσθέτει στο υπόλοιπο δαπανών σου μετά από 3 επιβεβαιώσεις, περίπου 30 λεπτά. Συνέχισε να χρησιμοποιείς το Bitkit + Επεξεργασία πληρωμής + Επιτυχής πληρωμή Spark Χρέωση εξαργύρωσης %1$d/3 επιβεβαιώσεις diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 29d85165c0..ed9435fea5 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -218,13 +218,13 @@ Hora de sincronización de puntuaciones de rutas Spark aún no ha visto su transferencia. Se añade tras 3 confirmaciones; puede salir de esta pantalla. Pagar ₿ {amount} - Instantáneo ahora cuesta ₿ {amount}. Páguelo o espere 3 confirmaciones, unos 30 minutos, con una comisión menor. + Instantáneo ahora cuesta <accent>₿ {amount}</accent>. Páguelo o espere 3 confirmaciones, unos 30 minutos, con una comisión menor. Velocidad: {speed} Añadiendo a gastos - Visto por Spark - Transferencia enviada Instantáneo no está disponible para esta transferencia. Spark la añade a su saldo para gastos tras 3 confirmaciones, unos 30 minutos. Continuar Usando Bitkit + Procesando Pago + Pago exitoso Spark Comisión de reclamación %1$d/3 confirmaciones diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 4ad68a6c49..df107b9315 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -160,13 +160,13 @@ Hora de sincronización de puntuaciones de rutas Spark aún no ha visto tu transferencia. Se añade tras 3 confirmaciones; puedes salir de esta pantalla. Pagar ₿ {amount} - Instantáneo ahora cuesta ₿ {amount}. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. + Instantáneo ahora cuesta <accent>₿ {amount}</accent>. Págalo o espera 3 confirmaciones, unos 30 minutos, con una comisión menor. Velocidad: {speed} Añadiendo a gastos - Visto por Spark - Transferencia enviada Instantáneo no está disponible para esta transferencia. Spark la añade a tu saldo para gastos tras 3 confirmaciones, unos 30 minutos. Continuar Usando Bitkit + Pago Exitoso + Procesando Pago Spark Comisión de reclamo %1$d/3 confirmaciones diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0772fc8048..b3e6d622dc 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -190,13 +190,13 @@ Heure de synchronisation des scores de routage Spark n\'a pas encore vu votre transfert. Il est ajouté après 3 confirmations ; vous pouvez quitter cet écran. Payer ₿ {amount} - Instantané coûte maintenant ₿ {amount}. Payez-le, ou attendez 3 confirmations, environ 30 minutes, pour des frais moins élevés. + Instantané coûte maintenant <accent>₿ {amount}</accent>. Payez-le, ou attendez 3 confirmations, environ 30 minutes, pour des frais moins élevés. Vitesse : {speed} Ajout aux dépenses - Vu par Spark - Transfert envoyé Instantané n\'est pas disponible pour ce transfert. Spark l\'ajoute à votre solde de dépenses après 3 confirmations, environ 30 minutes. Continuer à utiliser Bitkit + Traitement des paiements + Paiement réussi Dépensable Onchain Réserve totale des canaux Anchor Total Lightning diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0633e3bf9f..a81f182535 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -217,13 +217,13 @@ Tempo Sincronizzazione Punteggi Pathfinding Spark non ha ancora visto il tuo trasferimento. Viene aggiunto dopo 3 conferme; puoi lasciare questa schermata. Paga ₿ {amount} - Istantanea ora costa ₿ {amount}. Pagala, oppure attendi 3 conferme, circa 30 minuti, con una commissione più bassa. + Istantanea ora costa <accent>₿ {amount}</accent>. Pagala, oppure attendi 3 conferme, circa 30 minuti, con una commissione più bassa. Velocità: {speed} Aggiunta alle spese - Visto da Spark - Trasferimento inviato Istantanea non è disponibile per questo trasferimento. Spark lo aggiunge al tuo conto di spesa dopo 3 conferme, circa 30 minuti. Continua ad utilizzare Bitkit + Elaborazione del pagamento + Pagamento Riuscito Spark Commissione di riscatto %1$d/3 conferme diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 37f252061b..d250dda657 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -216,13 +216,13 @@ Pathfinding scores synchronisatietijd Spark heeft je overboeking nog niet gezien. Hij wordt toegevoegd na 3 bevestigingen; je kunt dit scherm verlaten. Betaal ₿ {amount} - Direct kost nu ₿ {amount}. Betaal het, of wacht op 3 bevestigingen, ongeveer 30 minuten, tegen lagere kosten. + Direct kost nu <accent>₿ {amount}</accent>. Betaal het, of wacht op 3 bevestigingen, ongeveer 30 minuten, tegen lagere kosten. Snelheid: {speed} Toevoegen aan besteding - Gezien door Spark - Overboeking verzonden Direct is niet beschikbaar voor deze overboeking. Spark voegt hem na 3 bevestigingen, ongeveer 30 minuten, toe aan je bestedingssaldo. Doorgaan met Bitkit + Betaling verwerken + Betaling succesvol Spark Claimkosten %1$d/3 bevestigingen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ca38f7f23a..b54c1b06b4 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -274,13 +274,13 @@ Czas synchronizacji wyników ścieżek Spark jeszcze nie widzi Twojego przelewu. Zostanie dodany po 3 potwierdzeniach; możesz opuścić ten ekran. Zapłać ₿ {amount} - Natychmiast kosztuje teraz ₿ {amount}. Zapłać albo poczekaj na 3 potwierdzenia, około 30 minut, z niższą opłatą. + Natychmiast kosztuje teraz <accent>₿ {amount}</accent>. Zapłać albo poczekaj na 3 potwierdzenia, około 30 minut, z niższą opłatą. Prędkość: {speed} Dodawanie do wydatków - Widziany przez Spark - Przelew wysłany Natychmiast nie jest dostępne dla tego przelewu. Spark doda go do Twojego salda wydatków po 3 potwierdzeniach, około 30 minut. Kontunuuj korzystanie z Bitkit\'a + Przetwarzanie płatności + Płatność powiodła się Dostępne Onchain Całkowita rezerwa kanałów anchor Całkowite Lightning diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index a6278393f7..a647e1530c 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -220,13 +220,13 @@ Sincronização de Scores de Roteamento A Spark ainda não viu sua transferência. Ela é adicionada após 3 confirmações; você pode sair desta tela. Pagar ₿ {amount} - Instantâneo agora custa ₿ {amount}. Pague ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa menor. + Instantâneo agora custa <accent>₿ {amount}</accent>. Pague ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa menor. Velocidade: {speed} Adicionando aos gastos - Vista pela Spark - Transferência enviada Instantâneo não está disponível para esta transferência. A Spark a adiciona ao seu saldo de gastos após 3 confirmações, cerca de 30 minutos. Continuar Usando o Bitkit + Processando Pagamento + Pagamento Realizado Spark Taxa de resgate %1$d/3 confirmações diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index a11db7af99..8f9ab2f3cc 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -264,13 +264,13 @@ Tempo de Sinc. das Pontuações de Pathfinding A Spark ainda não viu a sua transferência. É adicionada após 3 confirmações; pode sair deste ecrã. Pagar ₿ {amount} - Instantâneo custa agora ₿ {amount}. Pague-o ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa mais baixa. + Instantâneo custa agora <accent>₿ {amount}</accent>. Pague-o ou aguarde 3 confirmações, cerca de 30 minutos, com uma taxa mais baixa. Velocidade: {speed} A adicionar aos gastos - Vista pela Spark - Transferência enviada Instantâneo não está disponível para esta transferência. A Spark adiciona-a ao seu saldo de gastos após 3 confirmações, cerca de 30 minutos. Continuar Usando o Bitkit + Processando Pagamento + Pagamento Realizado Tempo de Atualização do Cache de Taxa Capacidade de Entrada Limite do Próximo HTLC de Saída diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 833868aaa2..8f0688518d 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -228,13 +228,13 @@ Время синхронизации оценок маршрутизации Spark ещё не увидел ваш перевод. Он будет зачислен после 3 подтверждений; можно покинуть этот экран. Оплатить ₿ {amount} - Мгновенно теперь стоит ₿ {amount}. Оплатите или дождитесь 3 подтверждений, около 30 минут, с меньшей комиссией. + Мгновенно теперь стоит <accent>₿ {amount}</accent>. Оплатите или дождитесь 3 подтверждений, около 30 минут, с меньшей комиссией. Скорость: {speed} Зачисление на расходы - Виден Spark - Перевод отправлен Мгновенно недоступно для этого перевода. Spark зачислит его на баланс расходов после 3 подтверждений, примерно через 30 минут. Продолжить Использование Bitkit + Обработка Платежа + Платеж Успешен Spark Комиссия за зачисление %1$d/3 подтверждений diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bd8e92248f..739de4d149 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -377,13 +377,13 @@ Pathfinding Scores Sync Time Spark hasn\'t seen your transfer yet. It\'s added after 3 confirmations; you can leave this screen. Pay ₿ {amount} - Instant now costs ₿ {amount}. Pay it, or wait for 3 confirmations, about 30 minutes, at a lower fee. + Instant now costs <accent>₿ {amount}</accent>. Pay it, or wait for 3 confirmations, about 30 minutes, at a lower fee. Speed: {speed} Adding To Spending - Seen By Spark - Transfer Sent Instant isn\'t available for this transfer. Spark adds it to your spending balance after 3 confirmations, about 30 minutes. Continue Using Bitkit + Processing Payment + Payment Successful Spark Claim fee %1$d/3 confirmations diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt index 083ab13329..85ef74c17d 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt @@ -38,7 +38,7 @@ class SettingUpScreenTest { fun `later steps and their label sit above the button on a small screen`() { setContent(SparkDepositClaim.Later, SparkClaimSpeed.Instant) - val label = composeRule.onNodeWithText("Seen By Spark").getUnclippedBoundsInRoot() + val label = composeRule.onNodeWithText("Payment Successful").getUnclippedBoundsInRoot() val button = composeRule.onNodeWithTag("TransferSuccess-button").getUnclippedBoundsInRoot() assertTrue(label.bottom <= button.top) From 1583dc98ef1aad65dd1c99f6e540240a2de3eed9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:13:06 +0100 Subject: [PATCH 066/135] fix: align the spending speed picker with the fee rows --- .../screens/transfer/SpendingConfirmScreen.kt | 33 ++++++++++--------- app/src/main/res/values-ar/strings.xml | 1 - app/src/main/res/values-b+es+419/strings.xml | 1 - app/src/main/res/values-ca/strings.xml | 1 - app/src/main/res/values-cs/strings.xml | 1 - app/src/main/res/values-de/strings.xml | 1 - app/src/main/res/values-el/strings.xml | 1 - app/src/main/res/values-es-rES/strings.xml | 1 - app/src/main/res/values-es/strings.xml | 1 - app/src/main/res/values-fr/strings.xml | 1 - app/src/main/res/values-it/strings.xml | 1 - app/src/main/res/values-nl/strings.xml | 1 - app/src/main/res/values-pl/strings.xml | 1 - app/src/main/res/values-pt-rBR/strings.xml | 1 - app/src/main/res/values-pt/strings.xml | 1 - app/src/main/res/values-ru/strings.xml | 1 - app/src/main/res/values/strings.xml | 3 +- .../transfer/spark-transfer-to-spending.xml | 6 ++-- 18 files changed, 21 insertions(+), 36 deletions(-) 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 4de87cc6fa..9b60b5df7b 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 @@ -45,6 +45,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BodySSB import to.bitkit.ui.components.ButtonSize @@ -52,6 +53,7 @@ import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.Display import to.bitkit.ui.components.FeeInfo import to.bitkit.ui.components.HorizontalSpacer +import to.bitkit.ui.components.MoneyMSB import to.bitkit.ui.components.MoneySSB import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SwipeToConfirm @@ -210,10 +212,7 @@ private fun Content( @Composable internal fun SpendingFeeGrid(quote: Quote?, speed: SparkClaimSpeed, modifier: Modifier = Modifier) { Column(modifier = modifier) { - val claimPrefix = when (speed) { - SparkClaimSpeed.Instant -> stringResource(R.string.lightning__spending_confirm__up_to) - SparkClaimSpeed.Later -> stringResource(R.string.lightning__spending_confirm__about) - } + val claimPrefix = stringResource(R.string.lightning__spending_confirm__about) Row( horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.height(IntrinsicSize.Min) @@ -261,7 +260,7 @@ internal fun SpendingSpeedRows( SpeedItem( title = stringResource(R.string.fee__instant__title), description = stringResource(R.string.lightning__spending_confirm__instant_text), - feePrefix = stringResource(R.string.lightning__spending_confirm__up_to), + feePrefix = stringResource(R.string.lightning__spending_confirm__about), feeSats = quote?.instantFeeSats, icon = R.drawable.ic_speed_fast, iconColor = Colors.Purple, @@ -280,7 +279,6 @@ internal fun SpendingSpeedRows( onClick = { onSpeedChange(SparkClaimSpeed.Later) }, modifier = Modifier.testTag("SpendingConfirmLater") ) - HorizontalDivider() } } @@ -296,15 +294,11 @@ private fun SpeedItem( onClick: () -> Unit, modifier: Modifier = Modifier, ) { - Column( - modifier = modifier - .clickableAlpha(onClick = onClick) - .then(if (isSelected) Modifier.background(Colors.White06) else Modifier) - ) { - HorizontalDivider() + Column(modifier = modifier.clickableAlpha(onClick = onClick)) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier + .then(if (isSelected) Modifier.background(Colors.White06) else Modifier) .padding(horizontal = 16.dp) .heightIn(min = 72.dp) .padding(vertical = 8.dp) @@ -316,19 +310,26 @@ private fun SpeedItem( modifier = Modifier.size(32.dp), ) HorizontalSpacer(16.dp) - // The text wraps, so the fee keeps its one line at the end of the row. + // The text wraps, so the fee keeps its lines at the end of the row. Column(modifier = Modifier.weight(1f)) { BodyMSB(title, color = MaterialTheme.colorScheme.primary) BodySSB(description, color = MaterialTheme.colorScheme.secondary) } if (feeSats != null) { HorizontalSpacer(8.dp) - Row { - BodySSB("$feePrefix ", color = Colors.White64) - MoneySSB(sats = feeSats, showSymbol = true) + Column(horizontalAlignment = Alignment.End) { + Row { + BodyMSB("$feePrefix ", color = Colors.White64) + MoneyMSB(sats = feeSats, showSymbol = true) + } + Row { + BodySSB("$feePrefix ", color = Colors.White64) + MoneySSB(sats = feeSats, unit = LocalCurrencies.current.primaryDisplay.not(), showSymbol = true) + } } } } + HorizontalDivider() } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c5d5c6abad..1d01dcf90e 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -254,7 +254,6 @@ الرسوم غير متاحة رسوم الإنفاق الإجمالي - حتى ابدأ حوّل الأموال إلى رصيد الإنفاق للاستمتاع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. تحويل\n<accent>إلى الإنفاق</accent> 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 e55671de1f..7734d0b72d 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -261,7 +261,6 @@ Comisiones no disponibles Comisión de gastos Total - hasta Empezar Transfiera fondos a su saldo de gastos para disfrutar de transacciones baratas e instantáneas con amigos y comercios. Transferir\n<accent>a gastos</accent> diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 9f8aebd4de..c759fa610c 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -258,7 +258,6 @@ Comissions no disponibles Comissió de despesa Total - fins a Començar Transfereix fons al teu saldo de despesa per gaudir de transaccions instantànies i barates amb amics, família i comerciants. Transferir\n<accent>a despesa</accent> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 861c66fb5d..e0770e5dc1 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -261,7 +261,6 @@ Poplatky nedostupné Poplatek za výdaje Celkem - až Začít Převeďte peníze na svůj disponibilní zůstatek a využívejte okamžité a levné transakce s přáteli, rodinou a obchodníky. Převést\n<accent>do výdajů</accent> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 1242920b8a..5c76401426 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -141,7 +141,6 @@ In wenigen Minuten bereit Nach 3 Bestätigungen, etwa 30 Minuten Total - bis zu Los geht\'s Überweisen Sie Geld auf Ihr Guthaben, um sofortige und günstige Transaktionen mit Freunden, Familie und Händlern zu tätigen. <accent>zu den Ausgaben</accent> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 04699667fa..08b636cf0f 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -254,7 +254,6 @@ Μη διαθέσιμες χρεώσεις Χρέωση δαπανών Σύνολο - έως Ξεκίνα Μετέφερε κεφάλαια στο υπόλοιπο δαπανών για να απολαύσεις άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. Μεταφορά\n<accent>σε δαπάνες</accent> diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index ed9435fea5..89dc8d50d4 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -260,7 +260,6 @@ Comisiones no disponibles Comisión de gastos Total - hasta Empezar Transfiera fondos a su saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. Transferir\n<accent>a gasto</accent> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index df107b9315..12ffe7a8cf 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -213,7 +213,6 @@ Comisión de gastos Comisión de servicio Total - hasta Empezar Transfiera fondos a su saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. Transferir\n<accent>a gastos</accent> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index b3e6d622dc..07ee832f96 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -140,7 +140,6 @@ Prêt en quelques minutes Après 3 confirmations, environ 30 minutes Total - jusqu\'à Commencer Transférez des fonds vers votre solde Dépenses pour profiter de transactions instantanées et moins chers avec vos amis, votre famille et les commerçants. Transfert\n<accent>aux dépenses</accent> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index a81f182535..3167901de8 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -259,7 +259,6 @@ Commissioni non disponibili Commissione di spesa Totale - fino a Inizia Trasferisci fondi al tuo conto di spesa per usufruire di transazioni istantanee ed economiche con amici, familiari e commercianti. Trasferisci\n<accent>alle spese</accent> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index d250dda657..0e03d2aa22 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -258,7 +258,6 @@ Kosten niet beschikbaar Bestedingskosten Totaal - tot Aan de slag Boek geld over naar je bestedingssaldo voor directe en goedkope transacties met vrienden, familie en winkeliers. Overboeken\n<accent>naar bestedingssaldo</accent> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index b54c1b06b4..fef6a04f31 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -142,7 +142,6 @@ Gotowe w kilka minut Po 3 potwierdzeniach, około 30 minut Razem - do Rozpocznij Przelewaj środki na swoje saldo wydatków, aby cieszyć się natychmiastowymi i tanimi transakcjami z przyjaciółmi, rodziną i sprzedawcami. Prześlij \n<accent>na saldo wydatków</accent> diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index a647e1530c..9d38f0ecc3 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -262,7 +262,6 @@ Taxas indisponíveis Taxa de gastos Total - até Começar Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. Transferir\n<accent>para gastos</accent> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 8f9ab2f3cc..02e82c37a5 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -137,7 +137,6 @@ Pronto em poucos minutos Após 3 confirmações, cerca de 30 minutos Total - até Começar Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. Transferir\n<accent>para gastos</accent> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 8f0688518d..962982d050 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -270,7 +270,6 @@ Комиссии недоступны Комиссия расходов Итого - до Начать Переведите средства на свой баланс расходов, чтобы наслаждаться мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. Перевод\n<accent>на Расходы</accent> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 739de4d149..abbf9a07b8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -408,7 +408,7 @@ Amount Too Small 25% Transfer\n<accent>to spending</accent> - ≈ + ± To spending Fees are {amount} higher because fee rates or your savings balance changed while you were on this screen. Swipe again to confirm. Fees changed @@ -420,7 +420,6 @@ Fees Unavailable Spending fee Total - up to Get Started Transfer funds to your spending balance to enjoy instant and cheap transactions with friends, family, and merchants. Transfer\n<accent>to spending</accent> diff --git a/journeys/transfer/spark-transfer-to-spending.xml b/journeys/transfer/spark-transfer-to-spending.xml index 5ede3e3336..b22360b9be 100644 --- a/journeys/transfer/spark-transfer-to-spending.xml +++ b/journeys/transfer/spark-transfer-to-spending.xml @@ -5,7 +5,7 @@ and "Use Other Wallet" (testTag "FundReceive") above "Manual Setup" (testTag "FundManual"). Transfer from Savings opens the "Transfer to spending" intro once, then the amount screen (testTag "SpendingAmount"). The confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", and the Instant and Later rows: - Instant shows its fee as "up to", Later as "≈", and picking a row updates the Spending fee and To spending + Both rows show their fee as "±" in sats and fiat, and picking a row updates the Spending fee and To spending tiles. Learn more explains Instant and Later. Whether the provider offers Instant needs a real deposit Spark sees, so this journey stops before the swipe; the states after it are covered by SettingUpScreen previews and SparkRepoTest. @@ -20,8 +20,8 @@ Tap "Transfer from Savings" and verify the "Transfer to spending" intro opens; tap "Get Started" (testTag "SpendingIntro-button") Verify the amount screen (testTag "SpendingAmount") opens and wait until the available amount (testTag "SpendingAmountAvailable") shows a positive value Tap "25%" (testTag "SpendingAmountQuarter") and verify the amount is a quarter of the available amount; tap "Max" (testTag "SpendingAmountMax") and verify it equals the available amount - Tap "Continue" (testTag "SpendingAmountContinue") and verify the confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", with "Instant" (testTag "SpendingConfirmInstant") selected and its fee shown as "up to" - Tap "Later" (testTag "SpendingConfirmLater") and verify the Spending fee shows "≈" with a lower amount and "To spending" grows by the difference + Tap "Continue" (testTag "SpendingAmountContinue") and verify the confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", with "Instant" (testTag "SpendingConfirmInstant") selected and its fee shown as "±" + Tap "Later" (testTag "SpendingConfirmLater") and verify the Spending fee shows "±" with a lower amount and "To spending" grows by the difference Tap "Learn More" (testTag "SpendingConfirmMore"), verify the "Transfer speed" screen with the spending balance bar, and tap "Understood" (testTag "LiquidityContinue") Verify the confirm screen still shows Later selected; go back to the wallet home Tap the Savings balance card (testTag "ActivitySavings"), tap "Transfer To Spending" (testTag "TransferToSpending") and verify the amount screen opens directly, with no intro From 0b423bf834f90884eec1e260950faed46f5d17dc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:32:03 +0100 Subject: [PATCH 067/135] fix: match the savings intro to figma --- .../ui/screens/transfer/SavingsIntroScreen.kt | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsIntroScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsIntroScreen.kt index bfe16c7d17..f4ea1d73fa 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsIntroScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsIntroScreen.kt @@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.sizeIn import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -43,6 +44,7 @@ fun SavingsIntroScreen( contentScale = ContentScale.Fit, modifier = Modifier .padding(top = 130.dp) + .sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) .fillMaxWidth() .graphicsLayer(scaleX = -1f) ) @@ -54,12 +56,19 @@ fun SavingsIntroScreen( Column( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 32.dp) + .padding(horizontal = 16.dp) .align(Alignment.BottomCenter) ) { - Display(stringResource(R.string.lightning__savings_intro__title).withAccent()) + Display( + text = stringResource(R.string.lightning__savings_intro__title).withAccent(), + modifier = Modifier.padding(horizontal = 16.dp), + ) Spacer(modifier = Modifier.height(8.dp)) - BodyM(stringResource(R.string.lightning__savings_intro__text), color = Colors.White64) + BodyM( + text = stringResource(R.string.lightning__savings_intro__text), + color = Colors.White64, + modifier = Modifier.padding(horizontal = 16.dp), + ) Spacer(modifier = Modifier.height(32.dp)) PrimaryButton( From fb9bd11df8bea501509c51b6fb667de2ee9a38a9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:32:03 +0100 Subject: [PATCH 068/135] fix: add the menu icon to savings availability --- .../to/bitkit/ui/screens/transfer/SavingsAvailabilityScreen.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAvailabilityScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAvailabilityScreen.kt index 622cca9396..d738b4dd3c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAvailabilityScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAvailabilityScreen.kt @@ -25,6 +25,7 @@ import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors @@ -41,6 +42,7 @@ fun SavingsAvailabilityScreen( AppTopBar( titleText = stringResource(R.string.lightning__transfer__nav_title), onBackClick = onBackClick, + actions = { DrawerNavIcon() }, ) Column( modifier = Modifier From 1dda91ade7b744007db14287387b45801ac9acda Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:33:50 +0100 Subject: [PATCH 069/135] fix: match the savings confirm screen to figma and ios --- .../java/to/bitkit/ui/components/FeeInfo.kt | 13 ++- .../screens/transfer/SavingsConfirmScreen.kt | 59 ++++++++++---- app/src/main/res/values/strings.xml | 1 + .../transfer/SavingsConfirmScreenTest.kt | 81 +++++++++++++++++++ 4 files changed, 137 insertions(+), 17 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt 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 2a56a23f92..1e63a3c39c 100644 --- a/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt +++ b/app/src/main/java/to/bitkit/ui/components/FeeInfo.kt @@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.material3.HorizontalDivider import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @@ -19,6 +20,7 @@ fun RowScope.FeeInfo( amount: Long, modifier: Modifier = Modifier, prefix: String? = null, + isLoading: Boolean = false, ) { Column( modifier = modifier @@ -33,7 +35,16 @@ fun RowScope.FeeInfo( Spacer(modifier = Modifier.height(8.dp)) Row { prefix?.let { BodySSB(text = "$it ", color = Colors.White64) } - MoneySSB(sats = amount, showSymbol = true) + if (isLoading) { + GradientCircularProgressIndicator( + strokeWidth = 2.dp, + modifier = Modifier + .padding(vertical = 2.dp) + .size(16.dp), + ) + } else { + MoneySSB(sats = amount, showSymbol = true) + } } Spacer(modifier = Modifier.weight(1f)) HorizontalDivider(modifier = Modifier.padding(top = 16.dp)) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 8da726e80c..0fc23e52e0 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -16,6 +16,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -31,6 +32,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview @@ -44,7 +46,7 @@ import to.bitkit.ext.filterOpen import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.safe import to.bitkit.ui.components.AmountSlider -import to.bitkit.ui.components.BodyS +import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Caption13Up import to.bitkit.ui.components.ConnectionIssuesView @@ -140,6 +142,7 @@ fun SavingsConfirmScreen( onAmountClick = { currency.switchUnit() }, onAdvancedClick = onAdvancedClick, onSelectAllClick = { transfer.setSavingsSelection(SavingsSelection()) }, + onSparkFeeRetry = { transfer.loadSparkWithdrawFee(sparkSats) }, onSwipeConfirm = { shownSparkSats, shownFeeSats -> transfer.confirmSavingsSwipe(channels, withdrawsSpark, shownSparkSats, shownFeeSats) .also { if (it) onConfirm() } @@ -163,7 +166,7 @@ fun SavingsConfirmScreen( } @Composable -private fun SavingsConfirmContent( +internal fun SavingsConfirmContent( fallbackAmount: ULong, sparkAmount: ULong, sparkFeeSats: ULong?, @@ -183,6 +186,7 @@ private fun SavingsConfirmContent( onAmountClick: () -> Unit = {}, onAdvancedClick: () -> Unit = {}, onSelectAllClick: () -> Unit = {}, + onSparkFeeRetry: () -> Unit = {}, onSwipeConfirm: (shownSparkSats: ULong, shownFeeSats: ULong?) -> Boolean = { _, _ -> true }, onCloseConfirm: () -> Unit = {}, ) { @@ -223,7 +227,7 @@ private fun SavingsConfirmContent( text = stringResource(R.string.lightning__savings_confirm__label), color = Colors.White64, ) - VerticalSpacer(8.dp) + VerticalSpacer(16.dp) MoneyDisplay(sats = headlineAmount.toLong(), onClick = onAmountClick) if (quote != null) { @@ -267,7 +271,7 @@ private fun SavingsConfirmContent( } } - if (sparkFeeSats != null) { + if (sparkFeeSats != null || isSparkFeePricing) { VerticalSpacer(if (quote != null) 0.dp else 24.dp) Row( horizontalArrangement = Arrangement.spacedBy(16.dp), @@ -275,27 +279,26 @@ private fun SavingsConfirmContent( ) { FeeInfo( label = stringResource(R.string.lightning__savings_confirm__spark_fee), - amount = sparkFeeSats.toLong(), + amount = (sparkFeeSats ?: 0uL).toLong(), + isLoading = isSparkFeePricing, ) } } if (isSparkUnpriced && !isSparkFeePricing) { VerticalSpacer(16.dp) - BodyS( - text = stringResource( - if (isSparkTooSmall) { - R.string.lightning__savings_confirm__amount_too_low - } else { - R.string.lightning__savings_spark_failed - } - ), - color = Colors.Red, - ) + if (isSparkTooSmall) { + BodyM( + text = stringResource(R.string.lightning__savings_confirm__amount_too_low), + color = Colors.Red, + ) + } else { + SparkFeeError(onRetry = onSparkFeeRetry) + } } if (hasMultiple) { - VerticalSpacer(24.dp) + VerticalSpacer(32.dp) if (hasSelected) { PrimaryButton( text = stringResource(R.string.lightning__savings_confirm__transfer_all), @@ -333,6 +336,7 @@ private fun SavingsConfirmContent( contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier + .sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) .fillMaxSize() .graphicsLayer(scaleX = -1f), ) @@ -377,6 +381,29 @@ private fun SavingsConfirmContent( } } +/** Spark's withdrawal fee could not be priced; the swipe waits for it, so it can be retried here. */ +@Composable +private fun SparkFeeError(onRetry: () -> Unit) { + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth(), + ) { + BodyM( + text = stringResource(R.string.lightning__spending_confirm__error_quote), + color = Colors.Red, + modifier = Modifier.weight(1f), + ) + PrimaryButton( + text = stringResource(R.string.common__retry), + size = ButtonSize.Small, + fullWidth = false, + onClick = onRetry, + modifier = Modifier.testTag("SavingsSparkFeeRetry"), + ) + } +} + @Preview(showSystemUi = true, showBackground = true) @Composable private fun SavingsConfirmScreenPreview() { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index abbf9a07b8..a136dc2216 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -410,6 +410,7 @@ Transfer\n<accent>to spending</accent> ± To spending + Bitkit couldn\'t get the fees for this transfer. Check your connection and try again. Fees are {amount} higher because fee rates or your savings balance changed while you were on this screen. Swipe again to confirm. Fees changed Ready in a few minutes diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt new file mode 100644 index 0000000000..824c9acc2c --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt @@ -0,0 +1,81 @@ +package to.bitkit.ui.screens.transfer + +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 androidx.compose.ui.test.performScrollTo +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.ui.theme.AppThemeSurface +import kotlin.test.assertEquals +import kotlin.time.Duration.Companion.seconds +import kotlin.time.toJavaDuration + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class SavingsConfirmScreenTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `the spark fee row shows while the fee is being priced`() { + setContent(isSparkFeePricing = true, isSparkUnpriced = true) + + composeRule.onNodeWithText("SPARK FEE", substring = true, ignoreCase = true).assertExists() + composeRule.onNodeWithTag("SavingsSparkFeeRetry").assertDoesNotExist() + } + + @Test + fun `an unpriced spark fee shows the quote error with a retry that prices it again`() { + var retries = 0 + setContent(isSparkUnpriced = true, onSparkFeeRetry = { retries++ }) + ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) + + composeRule.onNodeWithText("Bitkit couldn't get the fees", substring = true).assertExists() + composeRule.onNodeWithTag("SavingsSparkFeeRetry").performScrollTo().performClick() + + assertEquals(1, retries) + } + + @Test + fun `a spark amount too low to withdraw says so without a retry`() { + setContent(isSparkUnpriced = true, isSparkTooSmall = true) + + composeRule.onNodeWithText("Amount is too low to transfer to savings.").assertExists() + composeRule.onNodeWithTag("SavingsSparkFeeRetry").assertDoesNotExist() + } + + private fun setContent( + isSparkFeePricing: Boolean = false, + isSparkUnpriced: Boolean = false, + isSparkTooSmall: Boolean = false, + onSparkFeeRetry: () -> Unit = {}, + ) { + composeRule.setContent { + AppThemeSurface { + SavingsConfirmContent( + fallbackAmount = 0u, + sparkAmount = 12_000u, + sparkFeeSats = null, + isSparkFeePricing = isSparkFeePricing, + isSparkUnpriced = isSparkUnpriced, + isSparkTooSmall = isSparkTooSmall, + isSwapEnabled = false, + quote = null, + isQuoteLoading = false, + minSat = 0u, + maxSat = 0u, + onAmountChange = {}, + hasMultiple = false, + hasSelected = false, + onSparkFeeRetry = onSparkFeeRetry, + ) + } + } + } +} From cb34f64bac52be899a5177dace1335ecbd4075db Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:34:45 +0100 Subject: [PATCH 070/135] fix: show the spark failure on the savings progress screen --- .../screens/transfer/SavingsProgressScreen.kt | 53 +++++++++++++++---- app/src/main/res/values/strings.xml | 5 +- .../transfer/SavingsProgressScreenTest.kt | 40 ++++++++++++++ 3 files changed, 86 insertions(+), 12 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt index 7a63b9649f..3fdd132cc7 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt @@ -75,8 +75,11 @@ fun SavingsProgressScreen( } fun showSparkFailure(movesChannels: Boolean) { - toastSparkFailure(movesChannels) - onTransferUnavailable() + progressState = if (movesChannels) { + SavingsProgressState.SPARK_FAILED_PARTIAL + } else { + SavingsProgressState.SPARK_FAILED + } } // Effect to execute the transfer & update UI @@ -147,7 +150,7 @@ fun SavingsProgressScreen( } } - Content( + SavingsProgressContent( progressState = progressState, onContinueClick = { onContinueClick() }, modifier = Modifier.keepScreenOn(), @@ -181,18 +184,23 @@ private suspend fun runChannelClose( } @Composable -private fun Content( +internal fun SavingsProgressContent( progressState: SavingsProgressState, modifier: Modifier = Modifier, onContinueClick: () -> Unit = {}, ) { val inProgress = progressState == SavingsProgressState.PROGRESS val showAnimation = inProgress || progressState == SavingsProgressState.SETTLING + val isSparkFailed = progressState.isSparkFailed ScreenColumn( modifier = modifier.testTag( when (progressState) { SavingsProgressState.PROGRESS -> "TransferSettingUp" SavingsProgressState.SETTLING -> "TransferSettling" + SavingsProgressState.SPARK_FAILED, + SavingsProgressState.SPARK_FAILED_PARTIAL, + -> "SavingsSparkFailed" + else -> "TransferSuccess" } ) @@ -201,6 +209,8 @@ private fun Content( titleText = when (progressState) { SavingsProgressState.PROGRESS, SavingsProgressState.SETTLING, + SavingsProgressState.SPARK_FAILED, + SavingsProgressState.SPARK_FAILED_PARTIAL, -> stringResource(R.string.lightning__transfer__nav_title) SavingsProgressState.SUCCESS -> stringResource(R.string.lightning__transfer_success__nav_title) @@ -255,7 +265,9 @@ private fun Content( PrimaryButton( text = stringResource(R.string.common__ok), onClick = onContinueClick, - modifier = Modifier.testTag("TransferSuccess-button") + modifier = Modifier.testTag( + if (isSparkFailed) "SavingsSparkFailed-button" else "TransferSuccess-button" + ), ) } VerticalSpacer(16.dp) @@ -277,6 +289,12 @@ private fun ProgressMessage(progressState: SavingsProgressState) { SavingsProgressState.INTERRUPTED -> R.string.lightning__savings_interrupted__title to R.string.lightning__savings_interrupted__text + + SavingsProgressState.SPARK_FAILED -> + R.string.lightning__savings_spark_failed__title to R.string.lightning__savings_spark_failed + + SavingsProgressState.SPARK_FAILED_PARTIAL -> + R.string.lightning__savings_spark_failed__title to R.string.lightning__savings_spark_failed_channels } Display(text = stringResource(titleRes).withAccent()) VerticalSpacer(8.dp) @@ -286,13 +304,18 @@ private fun ProgressMessage(progressState: SavingsProgressState) { ) } -enum class SavingsProgressState { PROGRESS, SETTLING, SUCCESS, INTERRUPTED } +/** `SPARK_FAILED_PARTIAL`: Spark's balance did not move, while the selected channels still did. */ +enum class SavingsProgressState { + PROGRESS, SETTLING, SUCCESS, INTERRUPTED, SPARK_FAILED, SPARK_FAILED_PARTIAL; + + val isSparkFailed get() = this == SPARK_FAILED || this == SPARK_FAILED_PARTIAL +} @Preview(showSystemUi = true) @Composable private fun PreviewProgress() { AppThemeSurface { - Content( + SavingsProgressContent( progressState = SavingsProgressState.PROGRESS, ) } @@ -302,7 +325,7 @@ private fun PreviewProgress() { @Composable private fun PreviewSettling() { AppThemeSurface { - Content( + SavingsProgressContent( progressState = SavingsProgressState.SETTLING, ) } @@ -312,7 +335,7 @@ private fun PreviewSettling() { @Composable private fun PreviewSuccess() { AppThemeSurface { - Content( + SavingsProgressContent( progressState = SavingsProgressState.SUCCESS, ) } @@ -322,8 +345,18 @@ private fun PreviewSuccess() { @Composable private fun PreviewInterrupted() { AppThemeSurface { - Content( + SavingsProgressContent( progressState = SavingsProgressState.INTERRUPTED, ) } } + +@Preview(showSystemUi = true) +@Composable +private fun PreviewSparkFailed() { + AppThemeSurface { + SavingsProgressContent( + progressState = SavingsProgressState.SPARK_FAILED_PARTIAL, + ) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a136dc2216..1937f71245 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -372,8 +372,9 @@ Funds\n<accent>in transfer</accent> Your transfer has been initiated and is <accent>settling on-chain</accent>. Your savings balance will update automatically once it completes. Transfer\n<accent>on the way</accent> - Your Spark balance couldn\'t move to savings and stays in your spending balance. - Your Spark balance couldn\'t move to savings and stays in your spending balance. Your connections are moving to savings. + Your Spark balance could not move to savings and stays in your spending balance. + Transfer\n<accent>failed</accent> + Your channel funds are moving to savings, but your Spark balance could not move and stays in your spending balance. Pathfinding Scores Sync Time Spark hasn\'t seen your transfer yet. It\'s added after 3 confirmations; you can leave this screen. Pay ₿ {amount} diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt new file mode 100644 index 0000000000..82d6ae3f39 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt @@ -0,0 +1,40 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.ui.theme.AppThemeSurface + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class SavingsProgressScreenTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `a spark failure shows the failed state with an ok button`() { + setContent(SavingsProgressState.SPARK_FAILED) + + composeRule.onNodeWithTag("SavingsSparkFailed").assertExists() + composeRule.onNodeWithText("failed", substring = true, ignoreCase = true).assertExists() + composeRule.onNodeWithText("Your Spark balance could not move to savings", substring = true).assertExists() + composeRule.onNodeWithTag("SavingsSparkFailed-button").assertExists() + } + + @Test + fun `a spark failure while channels move says the channel funds still move`() { + setContent(SavingsProgressState.SPARK_FAILED_PARTIAL) + + composeRule.onNodeWithText("Your channel funds are moving to savings", substring = true).assertExists() + composeRule.onNodeWithTag("SavingsSparkFailed-button").assertExists() + } + + private fun setContent(state: SavingsProgressState) { + composeRule.setContent { AppThemeSurface { SavingsProgressContent(progressState = state) } } + } +} From acdd57d31010def83f3a1e186cc631504cf90a11 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:34:59 +0100 Subject: [PATCH 071/135] fix: put the lightning connections buttons side by side --- .../lightning/LightningConnectionsScreen.kt | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) 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 e1f37f26b3..4f0d4c0691 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 @@ -270,21 +270,25 @@ private fun Content( // Bottom Section FillHeight() VerticalSpacer(16.dp) - SecondaryButton( - text = stringResource(R.string.lightning__conn_button_export_logs), - onClick = onClickExportLogs, - modifier = Modifier - .fillMaxWidth() - .testTag(LightningConnectionsTestTags.EXPORT_LOGS_BUTTON) - ) - VerticalSpacer(16.dp) - PrimaryButton( - text = stringResource(R.string.lightning__conn_button_add), - onClick = onClickAddConnection, - modifier = Modifier - .fillMaxWidth() - .testTag(LightningConnectionsTestTags.ADD_CONNECTION_BUTTON) - ) + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.fillMaxWidth(), + ) { + SecondaryButton( + text = stringResource(R.string.lightning__conn_button_export_logs), + onClick = onClickExportLogs, + modifier = Modifier + .weight(1f) + .testTag(LightningConnectionsTestTags.EXPORT_LOGS_BUTTON) + ) + PrimaryButton( + text = stringResource(R.string.lightning__conn_button_add), + onClick = onClickAddConnection, + modifier = Modifier + .weight(1f) + .testTag(LightningConnectionsTestTags.ADD_CONNECTION_BUTTON) + ) + } VerticalSpacer(16.dp) } } From 74b5e4ebccc00d2567477efccaa56ca2eeffbbbe Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:35:12 +0100 Subject: [PATCH 072/135] fix: capitalise the spending wallet transfer button --- app/src/main/res/values/strings.xml | 2 +- journeys/amount-limits/transfer-spending-over-max.xml | 2 +- journeys/transfer/spark-transfer-to-spending.xml | 6 +++--- journeys/transfer/transfer-unavailable-sheet.xml | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1937f71245..d7af43fcdd 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -308,7 +308,7 @@ Force Transfer Could not initiate transfer. Do you want to force this transfer? You won’t be able to use these funds for ±14 days (!) Force\n<accent>Transfer</accent> - Transfer from Savings + Transfer From Savings Use Other Wallet Transfer from HW wallet Spending Balance diff --git a/journeys/amount-limits/transfer-spending-over-max.xml b/journeys/amount-limits/transfer-spending-over-max.xml index 931e1cc86c..d435bdc0ce 100644 --- a/journeys/amount-limits/transfer-spending-over-max.xml +++ b/journeys/amount-limits/transfer-spending-over-max.xml @@ -11,7 +11,7 @@ Tap the Spending balance card on the home screen - Tap "Transfer from Savings" + Tap "Transfer From Savings" If a transfer intro screen appears, tap "Get Started" Verify the spending amount screen (testTag "SpendingAmount") is visible Wait until the available/maximum amount (testTag "SpendingAmountAvailable") finishes loading and shows a positive value diff --git a/journeys/transfer/spark-transfer-to-spending.xml b/journeys/transfer/spark-transfer-to-spending.xml index b22360b9be..7d3712dccf 100644 --- a/journeys/transfer/spark-transfer-to-spending.xml +++ b/journeys/transfer/spark-transfer-to-spending.xml @@ -1,7 +1,7 @@ Verifies the transfer to spending flow on Spark. With Spark ready, the Spending suggestion card opens the - "Spending Balance" intro once, then Funding, which leads with "Transfer from Savings" (testTag "FundTransfer") + "Spending Balance" intro once, then Funding, which leads with "Transfer From Savings" (testTag "FundTransfer") and "Use Other Wallet" (testTag "FundReceive") above "Manual Setup" (testTag "FundManual"). Transfer from Savings opens the "Transfer to spending" intro once, then the amount screen (testTag "SpendingAmount"). The confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", and the Instant and Later rows: @@ -16,8 +16,8 @@ Tap the Spending suggestion card and verify the "Spending Balance" intro opens; tap "Get Started" (testTag "TransferIntro-button") - Verify "Transfer from Savings" (testTag "FundTransfer") and "Use Other Wallet" (testTag "FundReceive") are enabled above "Manual Setup" (testTag "FundManual") - Tap "Transfer from Savings" and verify the "Transfer to spending" intro opens; tap "Get Started" (testTag "SpendingIntro-button") + Verify "Transfer From Savings" (testTag "FundTransfer") and "Use Other Wallet" (testTag "FundReceive") are enabled above "Manual Setup" (testTag "FundManual") + Tap "Transfer From Savings" and verify the "Transfer to spending" intro opens; tap "Get Started" (testTag "SpendingIntro-button") Verify the amount screen (testTag "SpendingAmount") opens and wait until the available amount (testTag "SpendingAmountAvailable") shows a positive value Tap "25%" (testTag "SpendingAmountQuarter") and verify the amount is a quarter of the available amount; tap "Max" (testTag "SpendingAmountMax") and verify it equals the available amount Tap "Continue" (testTag "SpendingAmountContinue") and verify the confirm screen shows "Network fees", "Spending fee", "To spending" and "Total", with "Instant" (testTag "SpendingConfirmInstant") selected and its fee shown as "±" diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index a4fc33336c..60d44c4ddd 100644 --- a/journeys/transfer/transfer-unavailable-sheet.xml +++ b/journeys/transfer/transfer-unavailable-sheet.xml @@ -21,7 +21,7 @@ Tap "Continue" and verify the sheet closes and the "MANUAL SETUP" screen shows the node id (testTag "NodeIdInput"), host (testTag "HostInput") and port (testTag "PortInput") fields Go back to the wallet home, tap the Spending balance card (testTag "ActivitySpending"), tap the transfer button (testTag "TransferFromSavings") and verify the same sheet opens; close it Open Settings › Advanced › Lightning Connections, tap add connection (testTag "add_connection_button") and verify the screen text reads "Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider." - Verify "Manual Setup" (testTag "FundManual") is the first option and enabled, and "Transfer from Savings" (testTag "FundTransfer"), "Transfer from HW wallet" (testTag "FundHardware") and "Use Other Wallet" (testTag "FundReceive") below it are disabled; tap "Transfer from Savings" and verify nothing opens + Verify "Manual Setup" (testTag "FundManual") is the first option and enabled, and "Transfer From Savings" (testTag "FundTransfer"), "Transfer from HW wallet" (testTag "FundHardware") and "Use Other Wallet" (testTag "FundReceive") below it are disabled; tap "Transfer From Savings" and verify nothing opens Tap "Learn More" (testTag "FundLearnMore") at the bottom and verify the browser opens blog.bitkit.to, then return to Bitkit and go back to the wallet home Tap "Receive" (testTag "Receive"), select the Spending tab (testTag "Tab-spending") and tap "Receive Lightning funds" Verify the screen titled "Transfer Unavailable" shows "MANUAL SETUP REQUIRED" and "Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider.", with a back button From 13d6c3389906ab2a4e63cd2fc63e7510e486005f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:35:36 +0100 Subject: [PATCH 073/135] fix: match the spending receive onboarding to figma and ios --- .../wallets/receive/ReceiveQrScreen.kt | 6 +- app/src/main/res/values/strings.xml | 4 +- .../wallets/receive/ReceiveQrScreenTest.kt | 61 +++++++++++++++++++ .../transfer/transfer-unavailable-sheet.xml | 2 +- 4 files changed, 67 insertions(+), 6 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt index e7855cca87..c477fa965b 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt @@ -296,9 +296,8 @@ fun ReceiveQrScreen( } } - val showingCjitOnboarding = remember(lightningState, canCreateLightningInvoice) { - !canCreateLightningInvoice && lightningState.nodeLifecycleState.isRunning() - } + // Shown while the node starts too, with its button disabled until the node runs. + val showingCjitOnboarding = !canCreateLightningInvoice fun selectReceiveTab(tab: ReceiveTab) { val wrapsToFirst = selectedTab == visibleTabs.last() && tab == visibleTabs.first() @@ -519,6 +518,7 @@ fun ReceiveQrScreen( onClickReceiveCjit() showDetails = false }, + enabled = lightningState.nodeLifecycleState.isRunning(), fullWidth = true, modifier = Modifier .padding(horizontal = 16.dp) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d7af43fcdd..052f71cca7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1546,13 +1546,13 @@ This Lightning invoice uses features Bitkit does not support yet. Peer disconnected. Receive - Receive Lightning funds + Receive Lightning Funds Receive Bitcoin Bitcoin invoice Invoice copied to clipboard Lightning invoice Optional note to payer - Enjoy instant and cheap bitcoin payments on the Lightning Network. + Enjoy instant and cheap transactions with friends, family, and merchants. Receive on <accent>spending balance</accent> Show Details QR Code diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt new file mode 100644 index 0000000000..afdcacea34 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt @@ -0,0 +1,61 @@ +package to.bitkit.ui.screens.wallets.receive + +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +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.models.NodeLifecycleState +import to.bitkit.repositories.LightningState +import to.bitkit.repositories.WalletState +import to.bitkit.ui.theme.AppThemeSurface +import kotlin.time.Duration.Companion.seconds +import kotlin.time.toJavaDuration + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class ReceiveQrScreenTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `the spending onboarding shows while the node starts with its button disabled`() { + setContent(NodeLifecycleState.Starting) + + composeRule.onNodeWithText("Enjoy instant and cheap transactions", substring = true).assertExists() + composeRule.onNodeWithText("Receive Lightning Funds").assertExists() + composeRule.onNodeWithTag("ShowDetails").assertIsNotEnabled() + } + + @Test + fun `the spending onboarding button is enabled once the node runs`() { + setContent(NodeLifecycleState.Running) + + composeRule.onNodeWithTag("ShowDetails").assertIsEnabled() + } + + /** Opens the Spending tab, as the screen starts on Savings while Lightning can't receive. */ + private fun setContent(nodeState: NodeLifecycleState) { + composeRule.setContent { + AppThemeSurface { + ReceiveQrScreen( + walletState = WalletState(), + lightningState = LightningState(nodeLifecycleState = nodeState), + onClickReceiveCjit = {}, + onClickEditInvoice = {}, + initialTab = ReceiveTab.SPENDING, + ) + } + } + ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) + composeRule.onNodeWithTag("Tab-spending").performClick() + composeRule.waitForIdle() + } +} diff --git a/journeys/transfer/transfer-unavailable-sheet.xml b/journeys/transfer/transfer-unavailable-sheet.xml index 60d44c4ddd..e8160a993f 100644 --- a/journeys/transfer/transfer-unavailable-sheet.xml +++ b/journeys/transfer/transfer-unavailable-sheet.xml @@ -23,7 +23,7 @@ Open Settings › Advanced › Lightning Connections, tap add connection (testTag "add_connection_button") and verify the screen text reads "Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider." Verify "Manual Setup" (testTag "FundManual") is the first option and enabled, and "Transfer From Savings" (testTag "FundTransfer"), "Transfer from HW wallet" (testTag "FundHardware") and "Use Other Wallet" (testTag "FundReceive") below it are disabled; tap "Transfer From Savings" and verify nothing opens Tap "Learn More" (testTag "FundLearnMore") at the bottom and verify the browser opens blog.bitkit.to, then return to Bitkit and go back to the wallet home - Tap "Receive" (testTag "Receive"), select the Spending tab (testTag "Tab-spending") and tap "Receive Lightning funds" + Tap "Receive" (testTag "Receive"), select the Spending tab (testTag "Tab-spending") and tap "Receive Lightning Funds" Verify the screen titled "Transfer Unavailable" shows "MANUAL SETUP REQUIRED" and "Automatic transfers to your spending balance are no longer available. Use your own node, or set up a connection with another provider.", with a back button Tap "Continue" and verify the sheet closes and the "MANUAL SETUP" screen opens From 97951b8fbe6a0dfd70901209a8da77ab897829e9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:38:53 +0100 Subject: [PATCH 074/135] fix: use the master copy for the transfer minimum toast --- .../to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt | 3 ++- app/src/main/res/values/strings.xml | 4 ++-- .../bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt | 5 +++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 6f39e3fd2c..ac9953ea2f 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 @@ -183,10 +183,11 @@ class SparkFundingViewModel @Inject constructor( } } + /** Names the smallest amount that passes, as an amount equal to the claim fee is refused. */ private fun toastBelowClaimFee(quote: Quote) = toast( title = R.string.lightning__spending_amount__error_min__title, description = context.getString(R.string.lightning__spending_amount__error_min__description) - .replace("{amount}", quote.instantFeeSats.formatToModernDisplay()), + .replace("{amount}", (quote.instantFeeSats + 1).formatToModernDisplay()), ) /** Re-prices the confirm screen, so it never shows a stale quote. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 052f71cca7..908ee9f2a2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -405,8 +405,8 @@ Insufficient Savings The amount you can transfer to your spending balance is currently limited to ₿ {amount}. Spending Balance Maximum - Transfer more than ₿ {amount}, so it covers the fees to add it to your spending balance. - Amount Too Small + A minimum of ₿ {amount} is needed to set up your spending balance. + Savings Balance Minimum 25% Transfer\n<accent>to spending</accent> ± 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 26a9229bf4..74d63cebc4 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,6 +26,7 @@ import to.bitkit.models.BalanceState import to.bitkit.models.Toast import to.bitkit.models.TransactionSpeed import to.bitkit.models.WalletScope +import to.bitkit.models.formatToModernDisplay import to.bitkit.repositories.CurrencyRepo import to.bitkit.repositories.CurrencyState import to.bitkit.repositories.HwWalletRepo @@ -100,6 +101,8 @@ class SparkFundingViewModelTest : BaseUnitTest() { @Test fun `continue refuses an amount that does not cover the instant fee`() = test { + whenever(context.getString(R.string.lightning__spending_amount__error_min__description)) + .thenReturn("Minimum {amount}") val sut = createSut() advanceUntilIdle() sut.onAmountChange(1_000) @@ -107,6 +110,8 @@ class SparkFundingViewModelTest : BaseUnitTest() { val toasts = collectToasts { sut.onAmountContinue() } assertEquals("Too small", toasts.single().title) + // An amount equal to the 1,350 sat claim fee is refused, so the smallest that passes is one more. + assertEquals("Minimum ${1_351L.formatToModernDisplay()}", toasts.single().description) assertEquals(null, sut.uiState.value.quote) } From f3c47bed084f509807a2b2957dff72484194e1ca Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:53:09 +0100 Subject: [PATCH 075/135] fix: end a restore whose gate lapses by its timeout --- .../java/to/bitkit/repositories/BackupRepo.kt | 21 +++++++++++++++---- .../to/bitkit/repositories/BackupRepoTest.kt | 16 ++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 6bac538a35..4945114a10 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -5,6 +5,7 @@ import com.synonym.bitkitcore.UsdtException import com.synonym.vssclient.VssException import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable @@ -24,6 +25,7 @@ import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.transformLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @@ -190,10 +192,21 @@ class BackupRepo @Inject constructor( private val restorePendingUntil = MutableStateFlow(0L) - /** Whether a restore is announced and its backup not applied yet, as [isRestoreInProgress], as it changes. */ - val restoreInProgress: Flow = combine(_isRestoring, restorePendingUntil) { isRestoring, pendingUntil -> - isRestoring || currentTimeMillis() < pendingUntil - }.distinctUntilChanged() + /** + * Whether a restore is announced and its backup not applied yet, as [isRestoreInProgress], as it changes; a gate + * that lapses by its timeout ends it then, too. + */ + @OptIn(ExperimentalCoroutinesApi::class) + val restoreInProgress: Flow = combine(_isRestoring, restorePendingUntil, ::Pair) + .transformLatest { (isRestoring, pendingUntil) -> + val remainingMillis = pendingUntil - currentTimeMillis() + emit(isRestoring || remainingMillis > 0) + if (!isRestoring && remainingMillis > 0) { + delay(remainingMillis) + emit(false) + } + } + .distinctUntilChanged() fun reset() { stopObservingBackups() diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 60a4f2d62b..a21e8842bd 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1588,6 +1588,22 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `a restore gate that lapses by its timeout ends the restore in progress`() = test { + val startedAt = currentTime + whenever(clock.now()).thenAnswer { Instant.fromEpochMilliseconds(3_000 + currentTime - startedAt) } + val states = mutableListOf() + backgroundScope.launch { sut.restoreInProgress.collect { states += it } } + runCurrent() + + sut.setRestorePending(true) + runCurrent() + advanceTimeBy(10.minutes + 1.seconds) + runCurrent() + + assertEquals(listOf(false, true, false), states) + } + @Test fun `pending public address restore blocks metadata uploads after the transient gate clears`() = test { val reservationStore = stubPublicAddressRestore( From df7c06118e4d7dfa39b7a4ef33110b08f5deb64a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:53:09 +0100 Subject: [PATCH 076/135] chore: move the spark chain service kdoc back to its function --- app/src/main/java/to/bitkit/env/Env.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 261caadb91..d211f9d4bc 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -129,7 +129,6 @@ internal object Env { Network.REGTEST -> "https://mempool.bitkit.stag0.blocktank.to/" } - /** Esplora REST that Spark reads the chain from; null keeps the SDK's default, on staging and regtest. */ /** * Whether the node's chain is the one Spark watches, so an on-chain funding of Spark from Savings or a hardware * wallet reaches it. On regtest Spark runs on Lightspark's own chain, which the node joins only through the @@ -140,6 +139,7 @@ internal object Env { val sparkSharesNodeChain: Boolean get() = sparkSharesNodeChain(network, regtestEsploraUrl) + /** Esplora REST that Spark reads the chain from; null keeps the SDK's default, on staging and regtest. */ fun sparkChainServiceUrl(network: Network): String? = when (network) { Network.BITCOIN -> bitkitEsploraUrl else -> null From a87c393a65feaf67f2aec2f3e6880f007934729e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 14:09:02 +0100 Subject: [PATCH 077/135] fix: leave a spark balance too small to move out of savings --- .../ui/screens/transfer/SavingsConfirmScreen.kt | 15 +++++++++------ .../to/bitkit/viewmodels/TransferViewModel.kt | 4 +++- .../to/bitkit/viewmodels/TransferViewModelTest.kt | 8 ++++++++ 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 0fc23e52e0..2957a503ce 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -94,8 +94,12 @@ fun SavingsConfirmScreen( val selection by transfer.savingsSelection.collectAsStateWithLifecycle() val hasSelected = !selection.isAll + val isSparkTooSmall by transfer.isSparkWithdrawTooSmall.collectAsStateWithLifecycle() val channels = selection.channels(openChannels) - val withdrawsSpark = selection.withdrawsSpark(sparkSats) + // A Spark balance too small to move is left out, so the channels picked with it still move. + val pricesSpark = selection.withdrawsSpark(sparkSats) + val withdrawsSpark = selection.withdrawsSpark(sparkSats, isSparkTooSmall) + val isOnlySparkTooSmall = pricesSpark && isSparkTooSmall && channels.isEmpty() val channelsAmount = channels.sumOf { it.amountOnClose } val sparkAmount = if (withdrawsSpark) sparkSats else 0uL @@ -103,7 +107,6 @@ fun SavingsConfirmScreen( val swapState by transfer.savingsSwapState.collectAsStateWithLifecycle() val sparkFeeSats by transfer.sparkWithdrawFeeSats.collectAsStateWithLifecycle() val isSparkFeePricing by transfer.isSparkFeePricing.collectAsStateWithLifecycle() - val isSparkTooSmall by transfer.isSparkWithdrawTooSmall.collectAsStateWithLifecycle() // Pull the latest node balances so a just-received payment is reflected in the amounts below. LaunchedEffect(Unit) { @@ -116,8 +119,8 @@ fun SavingsConfirmScreen( transfer.loadSavingsSwapQuote(channelsAmount, channels.totalNextOutboundHtlcLimitSats()) } - LaunchedEffect(withdrawsSpark, sparkSats) { - if (withdrawsSpark) transfer.loadSparkWithdrawFee(sparkSats) + LaunchedEffect(pricesSpark, sparkSats) { + if (pricesSpark) transfer.loadSparkWithdrawFee(sparkSats) } Box { @@ -127,9 +130,9 @@ fun SavingsConfirmScreen( sparkFeeSats = sparkFeeSats.takeIf { withdrawsSpark }, // Spark's part moves only at the fee shown, so nothing is confirmed before it is priced. isSparkFeePricing = withdrawsSpark && isSparkFeePricing, - isSparkUnpriced = withdrawsSpark && sparkFeeSats == null, + isSparkUnpriced = withdrawsSpark && sparkFeeSats == null || isOnlySparkTooSmall, isNothingSelected = channels.isEmpty() && !withdrawsSpark, - isSparkTooSmall = withdrawsSpark && isSparkTooSmall, + isSparkTooSmall = isOnlySparkTooSmall, isSwapEnabled = swapState.isSwapEnabled, quote = swapState.quote, isQuoteLoading = swapState.isLoading, diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 0d4fc6d384..83816dbc78 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -597,7 +597,9 @@ data class SavingsSelection( fun channels(openChannels: List): List = channelIds?.let { ids -> openChannels.filter { it.channelId in ids } } ?: openChannels - fun withdrawsSpark(sparkSats: ULong): Boolean = includesSpark && sparkSats > 0uL + /** Spark moves when picked and holding a balance its withdrawal fee leaves something of ([isSparkTooSmall]). */ + fun withdrawsSpark(sparkSats: ULong, isSparkTooSmall: Boolean = false): Boolean = + includesSpark && sparkSats > 0uL && !isSparkTooSmall } /** Whether a transfer to savings swaps funds out or closes a channel (default). */ diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 65c5098e52..7b8f01ea45 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -100,6 +100,14 @@ class TransferViewModelTest : BaseUnitTest() { assertFalse(selection.withdrawsSpark(0uL)) } + @Test + fun `savings selection leaves a spark balance too small to move, so the channels still move`() { + val selection = SavingsSelection() + + assertFalse(selection.withdrawsSpark(SPARK_SATS, isSparkTooSmall = true)) + assertEquals(listOf(CHANNEL_A), selection.channels(listOf(CHANNEL_A))) + } + @Test fun `savings selection moves only the picked channels and spark`() { val channelsOnly = SavingsSelection(channelIds = persistentSetOf(CHANNEL_B.channelId), includesSpark = false) From e5a85a86ac4013f243e713769bbb7e8dd426d2f8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 14:09:02 +0100 Subject: [PATCH 078/135] fix: trim unlisted expired send hashes and keep spark retries --- .../main/java/to/bitkit/data/CacheStore.kt | 59 +++++++++++++------ .../to/bitkit/repositories/LightningRepo.kt | 8 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 30 ++++++++-- .../java/to/bitkit/data/CacheStoreTest.kt | 53 +++++++++++++++-- .../bitkit/repositories/LightningRepoTest.kt | 9 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 38 +++++++++++- 6 files changed, 161 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index ad85ac4a36..0e7becb9b8 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -25,11 +25,19 @@ import kotlin.time.Clock /** * A listing drops a rail's send hashes it shows failed only, or paid once the invoice has expired, so the other rail - * cannot pay it again. Paid sends with no known expiry (kept before expiries were, or whose invoice can't be parsed) - * are dropped oldest first only past this many hashes. Pending sends and ones no listing has shown yet always stay. + * cannot pay it again, and ones it doesn't show once the invoice expired [UNLISTED_SEND_SETTLE_SECS] ago. Paid or + * unlisted sends with no known expiry (kept before expiries were, or whose invoice can't be parsed) are dropped oldest + * first only past this many hashes. A send that may be pending always stays. */ internal const val MAX_SPARK_SEND_HASHES = 100 +/** + * How long past its invoice's expiry a send no listing shows may still be pending: no send starts after the expiry, + * and one settles within its HTLC timeout, which LDK caps at 1008 blocks (about a week) and Spark's routes keep + * shorter, so twice that cap leaves room for slow blocks. + */ +internal const val UNLISTED_SEND_SETTLE_SECS = 14L * 24 * 60 * 60 + private val Context.appCacheDataStore: DataStore by dataStore( fileName = "app_cache.json", serializer = AppCacheSerializer @@ -192,40 +200,53 @@ class CacheStore internal constructor( } /** - * Drops the node's sends a listing showed as [failed] only, or as [paid] with an expired invoice, and past the cap - * the oldest paid ones with no known expiry; a send that may be pending is never passed in, so it stays. + * Drops the node's sends a listing showed as [failed] only, or as [paid] with an expired invoice, ones it didn't + * show ([listed] is every hash it shows) whose invoice expired past [UNLISTED_SEND_SETTLE_SECS], and past the cap + * the oldest paid or unlisted ones with no known expiry. A send that may be pending ([live]) always stays. */ - suspend fun trimLdkSendHashes(paid: Set, failed: Set) { + suspend fun trimLdkSendHashes(paid: Set, failed: Set, listed: Set, live: Set) { store.updateData { - val (hashes, expiries) = withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, paid, failed) + val (hashes, expiries) = + withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, SendListing(paid, failed, listed, live)) it.copy(ldkSendHashes = hashes, ldkSendExpiries = expiries) } } /** Drops Spark's sends as [trimLdkSendHashes] drops the node's. */ - suspend fun trimSparkSendHashes(paid: Set, failed: Set) { + suspend fun trimSparkSendHashes(paid: Set, failed: Set, listed: Set, live: Set) { store.updateData { - val (hashes, expiries) = withoutSettled(it.sparkSendHashes, it.sparkSendExpiries, paid, failed) + val (hashes, expiries) = + withoutSettled(it.sparkSendHashes, it.sparkSendExpiries, SendListing(paid, failed, listed, live)) it.copy(sparkSendHashes = hashes, sparkSendExpiries = expiries) } } + private class SendListing(paid: Set, failed: Set, listed: Set, live: Set) { + val paid = paid.lowercased() + val failed = failed.lowercased() + val listed = listed.lowercased() + val live = live.lowercased() + + private fun Set.lowercased() = mapTo(mutableSetOf()) { it.lowercase() } + } + private fun withoutSettled( hashes: List, expiries: Map, - paid: Set, - failed: Set, + listing: SendListing, ): Pair, Map> { val now = clock.now().epochSeconds - val paidHashes = paid.mapTo(mutableSetOf()) { it.lowercase() } - val failedHashes = failed.mapTo(mutableSetOf()) { it.lowercase() } - val listed = hashes.filterNot { hash -> - hash in failedHashes || hash in paidHashes && expiries[hash]?.let { it <= now } == true - } - var excess = listed.size - MAX_SPARK_SEND_HASHES - val kept = listed.filterNot { hash -> - (excess > 0 && hash in paidHashes && hash !in expiries).also { if (it) excess-- } - } + fun isExpired(hash: String, settleSecs: Long = 0) = expiries[hash]?.let { it + settleSecs <= now } == true + fun isSettled(hash: String) = hash !in listing.live && ( + hash in listing.failed || + hash in listing.paid && isExpired(hash) || + hash !in listing.listed && isExpired(hash, UNLISTED_SEND_SETTLE_SECS) + ) + fun isAged(hash: String) = + hash !in listing.live && hash !in expiries && (hash in listing.paid || hash !in listing.listed) + val unsettled = hashes.filterNot(::isSettled) + var excess = unsettled.size - MAX_SPARK_SEND_HASHES + val kept = unsettled.filterNot { hash -> (excess > 0 && isAged(hash)).also { if (it) excess-- } } return kept to expiries.filterKeys { it in kept } } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index ddf5b253f7..2c15b770ee 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1613,10 +1613,12 @@ class LightningRepo @Inject constructor( outbound.filter { it.status == status } .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } } + val recordedSince = ldkSendRecordedAt.filterValues { it > recordsBefore }.keys + val live = hashes(PaymentStatus.PENDING) + ldkSendsInFlight + recordedSince val paid = hashes(PaymentStatus.SUCCEEDED) - val failed = (hashes(PaymentStatus.FAILED) - paid - hashes(PaymentStatus.PENDING) - ldkSendsInFlight) - .filterTo(mutableSetOf()) { (ldkSendRecordedAt[it] ?: 0) <= recordsBefore } - cacheStore.trimLdkSendHashes(paid = paid, failed = failed) + val failed = hashes(PaymentStatus.FAILED) - paid - live + val listed = outbound.mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } + cacheStore.trimLdkSendHashes(paid = paid - live, failed = failed, listed = listed, live = live) failed.forEach { ldkSendRecordedAt.remove(it) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 824c4fb366..3e1d1c4552 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -57,6 +57,7 @@ import to.bitkit.utils.ServiceError import java.io.File import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @@ -129,6 +130,10 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() + /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ + private val sendRecords = AtomicLong() + private val sendRecordedAt = ConcurrentHashMap() + @Volatile private var hasSyncedActivities = false @@ -289,6 +294,7 @@ class SparkRepo @Inject constructor( val sent = try { val invoice = method.invoiceDetails val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() + sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) runSuspendCatching { sparkService.send(prepared) } } finally { @@ -818,31 +824,43 @@ class SparkRepo @Inject constructor( /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ private suspend fun syncActivities(): Boolean { + val recordsBefore = sendRecords.get() val payments = sparkService.listPayments() val isSaved = payments.map { recordActivity(it) }.all { it } val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } - // A send in flight may be missing from this list, or show only its earlier failed attempt, so it stays. - val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + // A send in flight, or recorded after this list was read while the activities were recorded, may be missing + // from it or show only its earlier failed attempt, so it stays. + val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + recordedSince(recordsBefore) val paid = sendHashes(PaymentStatus.COMPLETED) - live - cacheStore.trimSparkSendHashes(paid = paid, failed = sendHashes(PaymentStatus.FAILED) - paid - live) + cacheStore.trimSparkSendHashes( + paid = paid, + failed = sendHashes(PaymentStatus.FAILED) - paid - live, + listed = payments.mapNotNullTo(mutableSetOf()) { it.sendHash()?.lowercase() }, + live = live, + ) // A send that failed, also while the app was closed, no longer holds the node off its invoice, unless a // retry of it is still live. val failed = payments.mapNotNull { it.sendHash(PaymentStatus.FAILED) }.distinct() .filter { payments.latestSend(it)?.status == PaymentStatus.FAILED } if (failed.isEmpty()) return isSaved // A retry can start while the list is recorded, so the release reads Spark's sends again first. + val recordsBeforeCurrent = sendRecords.get() val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return isSaved + val recordedSinceCurrent = recordedSince(recordsBeforeCurrent) failed - .filter { !sendsInFlight.containsKey(it.lowercase()) } + .filter { !sendsInFlight.containsKey(it.lowercase()) && it.lowercase() !in recordedSinceCurrent } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } .forEach { cacheStore.removeSparkSendHash(it) } return isSaved } - private fun Payment.sendHash(status: PaymentStatus): String? = (details as? PaymentDetails.Lightning) - ?.takeIf { paymentType == SparkPaymentType.SEND && this.status == status } + private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys + + /** The payment hash of this send, at [status] when given. */ + private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) + ?.takeIf { paymentType == SparkPaymentType.SEND && (status == null || this.status == status) } ?.htlcDetails?.paymentHash private suspend fun onSdkEvent(event: SdkEvent) { diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index ae0c71bc8e..7db479fb34 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -100,7 +100,12 @@ class CacheStoreTest : BaseUnitTest() { val paid = settledHashes() sut.seedLdkSendHashes(listOf("pending") + paid) - sut.trimLdkSendHashes(paid = paid.toSet(), failed = emptySet()) + sut.trimLdkSendHashes( + paid = paid.toSet(), + failed = emptySet(), + listed = paid.toSet() + "pending", + live = setOf("pending"), + ) val kept = sut.data.first().ldkSendHashes assertTrue("pending" in kept) @@ -122,7 +127,12 @@ class CacheStoreTest : BaseUnitTest() { val paid = settledHashes() paid.forEach { sut.addSparkSendHash(it) } - sut.trimSparkSendHashes(paid = paid.toSet(), failed = emptySet()) + sut.trimSparkSendHashes( + paid = paid.toSet(), + failed = emptySet(), + listed = paid.toSet() + "pending", + live = setOf("pending"), + ) val kept = sut.data.first().sparkSendHashes assertTrue("pending" in kept) @@ -134,7 +144,12 @@ class CacheStoreTest : BaseUnitTest() { sut.addLdkSendHash("pending") sut.addLdkSendHash("failed") - sut.trimLdkSendHashes(paid = emptySet(), failed = setOf("failed")) + sut.trimLdkSendHashes( + paid = emptySet(), + failed = setOf("failed"), + listed = setOf("pending", "failed"), + live = setOf("pending"), + ) assertEquals(listOf("pending"), sut.data.first().ldkSendHashes) } @@ -146,7 +161,8 @@ class CacheStoreTest : BaseUnitTest() { store.addSparkSendHash("unexpired", expiresAt = NOW + 1) store.addSparkSendHash("unknown") - store.trimSparkSendHashes(paid = setOf("expired", "unexpired", "unknown"), failed = emptySet()) + val paid = setOf("expired", "unexpired", "unknown") + store.trimSparkSendHashes(paid = paid, failed = emptySet(), listed = paid, live = emptySet()) val data = store.data.first() assertEquals(listOf("unexpired", "unknown"), data.sparkSendHashes) @@ -160,7 +176,8 @@ class CacheStoreTest : BaseUnitTest() { val paid = settledHashes() paid.forEach { store.addLdkSendHash(it, expiresAt = NOW - 1) } - store.trimLdkSendHashes(paid = paid.toSet() + "unexpired", failed = emptySet()) + val listed = paid.toSet() + "unexpired" + store.trimLdkSendHashes(paid = listed, failed = emptySet(), listed = listed, live = emptySet()) val data = store.data.first() assertEquals(listOf("unexpired"), data.ldkSendHashes, "The unexpired paid send was dropped") @@ -174,13 +191,37 @@ class CacheStoreTest : BaseUnitTest() { val paid = settledHashes() paid.forEach { store.addSparkSendHash(it, expiresAt = NOW + 3_600) } - store.trimSparkSendHashes(paid = paid.toSet() + "expired", failed = emptySet()) + val listed = paid.toSet() + "expired" + store.trimSparkSendHashes(paid = listed, failed = emptySet(), listed = listed, live = emptySet()) val data = store.data.first() assertFalse("expired" in data.sparkSendHashes, "The expired paid send stayed past the cap") assertFalse("expired" in data.sparkSendExpiries) } + @Test + fun `a send no listing shows is dropped once its invoice expired past the settle window`() = test { + val store = expiringStore() + store.addSparkSendHash("stale", expiresAt = NOW - UNLISTED_SEND_SETTLE_SECS) + store.addSparkSendHash("settling", expiresAt = NOW - UNLISTED_SEND_SETTLE_SECS + 1) + store.addSparkSendHash("unknown") + store.addSparkSendHash("live", expiresAt = NOW - UNLISTED_SEND_SETTLE_SECS) + + store.trimSparkSendHashes(paid = emptySet(), failed = emptySet(), listed = emptySet(), live = setOf("live")) + + assertEquals(listOf("settling", "unknown", "live"), store.data.first().sparkSendHashes) + } + + @Test + fun `sends no listing shows with no known expiry are dropped oldest first past the cap`() = test { + val unlisted = (0..MAX_SPARK_SEND_HASHES).map { "unlisted$it" } + unlisted.forEach { sut.addLdkSendHash(it) } + + sut.trimLdkSendHashes(paid = emptySet(), failed = emptySet(), listed = emptySet(), live = emptySet()) + + assertEquals(unlisted.drop(1), sut.data.first().ldkSendHashes) + } + private fun expiringStore() = CacheStore( InMemoryDataStore(AppCacheData()), object : Clock { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a1d27d5cc9..62a66af0d5 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1516,7 +1516,14 @@ class LightningRepoTest : BaseUnitTest() { sut.payInvoice("bolt11", 1_000uL) - verifyBlocking(cacheStore) { trimLdkSendHashes(paid = setOf("paid"), failed = setOf("failed")) } + verifyBlocking(cacheStore) { + trimLdkSendHashes( + paid = setOf("paid"), + failed = setOf("failed"), + listed = setOf("pending", "paid", "failed"), + live = setOf("pending"), + ) + } } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 940826a306..89442df92e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy @@ -292,7 +293,42 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() - verifyBlocking(cacheStore) { trimSparkSendHashes(paid = setOf("hash"), failed = setOf("failed")) } + verifyBlocking(cacheStore) { + trimSparkSendHashes( + paid = setOf("hash"), + failed = setOf("failed"), + listed = setOf("hash", "failed", "pending"), + live = setOf("pending"), + ) + } + } + + @Test + fun `a retry that starts and returns while the activity sync runs keeps its hash`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendHashes = listOf("hash"))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed), listOf(failed, retry)) + val recording = CompletableDeferred() + whenever { activityRepo.getActivity(any(), any()) }.doSuspendableAnswer { + recording.await() + Result.success(null) + } + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(retry) + val sut = createSut(store) + val starting = async { sut.start(0) } + runCurrent() + // The listing read before the activity loop shows the invoice failed; its retry starts and returns meanwhile. + val paying = async { sut.payInvoice("lnbc1280n1send", 128uL) } + runCurrent() + recording.complete(Unit) + starting.await().getOrThrow() + paying.await() + + assertTrue("hash" in store.data.first().sparkSendHashes, "A stale listing dropped a live retry's hash") } @Test From 282360e9c4e874f20854854e8121b22552938e9d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 14:46:24 +0100 Subject: [PATCH 079/135] fix: keep the spark balance shown after a failed withdrawal --- .../java/to/bitkit/repositories/SparkRepo.kt | 13 ++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 35 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 3e1d1c4552..bb5423a4bb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -114,6 +114,12 @@ class SparkRepo @Inject constructor( /** Withdrawals this app sent, by txid, known before Spark lists them so their arrival reads as a transfer. */ private val withdrawalTxids = ConcurrentHashMap.newKeySet() + /** + * Set by a failed withdrawal until Spark reads a balance again: while its operators stay down, Spark can read 0 + * with the funds still there, so the last known balance stays shown. + */ + private val withdrawalFailed = AtomicBoolean(false) + /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ private val broadcastDeposits = ConcurrentHashMap() @@ -200,6 +206,7 @@ class SparkRepo @Inject constructor( earlyClaimVouts.clear() preparedWithdrawal = null withdrawalTxids.clear() + withdrawalFailed.set(false) broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() @@ -490,9 +497,11 @@ class SparkRepo @Inject constructor( (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } Unit }.onSuccess { + withdrawalFailed.set(false) runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after its withdrawal", it, context = TAG) } }.onFailure { + withdrawalFailed.set(true) Logger.error("Failed to withdraw from Spark", it, context = TAG) } } @@ -633,10 +642,12 @@ class SparkRepo @Inject constructor( ) } (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } + if (info.balanceSats > 0uL) withdrawalFailed.set(false) + val isStale = withdrawalFailed.get() || info.lastSyncError != null _state.update { it.copy( isReady = true, - balanceSats = info.balanceSats, + balanceSats = if (info.balanceSats == 0uL && isStale) it.balanceSats else info.balanceSats, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), withdrawals = payments.toWithdrawals(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 89442df92e..2067d54e87 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -23,6 +23,7 @@ import breez_sdk_spark.SendOnchainSpeedFeeQuote import breez_sdk_spark.SendPaymentMethod import breez_sdk_spark.SparkHtlcDetails import breez_sdk_spark.SparkHtlcStatus +import breez_sdk_spark.SyncError import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity @@ -827,6 +828,40 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `a failed withdrawal keeps the balance shown while spark reads zero`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("operators unreachable") } + val sut = createSut() + sut.refreshState().getOrThrow() + + assertTrue(sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isFailure) + whenever { sparkService.getInfo() }.thenReturn(info(0uL)) + sut.refreshState().getOrThrow() + + assertEquals(10_000uL, sut.state.value.balanceSats, "the balance read 0 after the failed withdrawal") + } + + @Test + fun `a failed sync keeps the balance shown while spark reads zero`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + val sut = createSut() + sut.refreshState().getOrThrow() + + val syncFailed = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + whenever { sparkService.getInfo() }.thenReturn(syncFailed) + sut.refreshState().getOrThrow() + assertEquals(10_000uL, sut.state.value.balanceSats, "the balance read 0 while the sync failed") + + whenever { sparkService.getInfo() }.thenReturn(info(0uL)) + sut.refreshState().getOrThrow() + assertEquals(0uL, sut.state.value.balanceSats) + } + @Test fun `a sent withdrawal succeeds even when the refresh after it fails`() = test { whenever(sparkService.isConnected).thenReturn(true) From e6c7395dd22a243d8f6f9f459377d295a692baea Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 14:46:24 +0100 Subject: [PATCH 080/135] fix: list a spark deposit claimed early only once --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 9 ++++++--- .../java/to/bitkit/repositories/SparkRepoTest.kt | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index bb5423a4bb..a4080b8ac4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -625,9 +625,7 @@ class SparkRepo @Inject constructor( private suspend fun refresh() = refreshMutex.withLock { val info = sparkService.getInfo() info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } - val pending = sparkService.listUnclaimedDeposits().map { - SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) - } + val unclaimed = sparkService.listUnclaimedDeposits() val payments = sparkService.listPayments() val claimed = payments .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } @@ -641,6 +639,11 @@ class SparkRepo @Inject constructor( claimedAt = payment.timestamp, ) } + // Spark can still list a deposit it already claimed early as unclaimed, so a claimed one is listed only once. + val claimedTxids = claimed.map { it.txid.lowercase() }.toSet() + val pending = unclaimed + .filter { it.txid.lowercase() !in claimedTxids } + .map { SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) } (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } if (info.balanceSats > 0uL) withdrawalFailed.set(false) val isStale = withdrawalFailed.get() || info.lastSyncError != null diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2067d54e87..98820c0ad6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -862,6 +862,20 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0uL, sut.state.value.balanceSats) } + @Test + fun `a deposit claimed early is listed only as claimed`() = test { + whenever(sparkService.isConnected).thenReturn(true) + listDeposit() + whenever { sparkService.listPayments() }.thenReturn(listOf(depositPayment())) + val sut = createSut() + + sut.refreshState().getOrThrow() + + val claimed = sut.state.value.deposits.map { it.isClaimed } + assertEquals(listOf(true), claimed, "the claimed deposit is in progress too") + assertEquals(0uL, sut.state.value.pendingDepositSats) + } + @Test fun `a sent withdrawal succeeds even when the refresh after it fails`() = test { whenever(sparkService.isConnected).thenReturn(true) From 93a045dcc48f6c51470e66aaff56be3905a49bb4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 15:17:50 +0100 Subject: [PATCH 081/135] fix: bind a fixed spark funding to its confirmed fee --- .../to/bitkit/repositories/LightningRepo.kt | 2 +- .../repositories/OnchainSendAttemptStore.kt | 4 +- .../screens/transfer/SparkFundingViewModel.kt | 18 +++++-- .../bitkit/repositories/LightningRepoTest.kt | 3 +- .../transfer/SparkFundingViewModelTest.kt | 47 +++++++++++++++++++ 5 files changed, 67 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 2c15b770ee..0792f5380e 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1831,7 +1831,7 @@ class LightningRepo @Inject constructor( if (prepared.receipt.amountSats != sats || miningFee == null || miningFee > approvedMiningFeeSats ) { - throw OnchainSendChangedError() + throw OnchainSendChangedError(miningFee) } } onchainSendAttemptStore.retainPreparedReceipt( diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt index 8a05368c13..83238e04ba 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt @@ -191,7 +191,9 @@ class OnchainSendAttemptUnreadableError(cause: Throwable) : AppError("Failed to class OnchainSendNotDispatchedError(cause: Throwable) : AppError("On-chain send did not reach the backend", cause) /** A send refused before broadcast because it would send another amount, or pay more mining fee, than approved. */ -class OnchainSendChangedError : AppError("On-chain send changed after it was approved") +/** [preparedFeeSats] is the mining fee of the refused prepared send, null when it was unknown. */ +class OnchainSendChangedError(val preparedFeeSats: ULong? = null) : + AppError("On-chain send changed after it was approved") class OnchainSendPendingError(cause: Throwable, val txid: String? = null) : AppError("On-chain send outcome is unknown; do not send again", cause) 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 ac9953ea2f..8e481224c4 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 @@ -90,6 +90,9 @@ class SparkFundingViewModel @Inject constructor( /** The fee rates the shown quote was priced at, so the transfer pays exactly what the screen shows. */ private var quotedFeeRates: FeeRates? = null + /** The mining fee a refused fixed-amount funding needed, which this transfer's quotes show at least. */ + private var fixedFeeFloorSats: ULong? = null + init { viewModelScope.launch { lightningRepo.lightningState.map { it.nodeStatus?.isRunning ?: false }.distinctUntilChanged() @@ -110,6 +113,7 @@ class SparkFundingViewModel @Inject constructor( /** Sends from the hardware wallet [walletId] instead of Savings. */ fun useHardwareWallet(walletId: String) { if (_uiState.value.hwWalletId == walletId) return + fixedFeeFloorSats = null _uiState.update { it.copy(hwWalletId = walletId, isMaxLoading = true) } refreshMax() } @@ -142,6 +146,8 @@ class SparkFundingViewModel @Inject constructor( } fun onAmountChange(sats: Long) { + val state = _uiState.value + if (sats != state.amountSats || (sats > 0 && sats == state.maxSats) != state.isMax) fixedFeeFloorSats = null _uiState.update { it.copy(amountSats = sats, isMax = sats > 0 && sats == it.maxSats) } } @@ -296,8 +302,8 @@ class SparkFundingViewModel @Inject constructor( feeRates = quotedFeeRates, isTransfer = true, isMaxAmount = state.isMax, - // A send-all spends every coin, so its fee is bound; a fixed amount's coin selection can vary. - approvedMiningFeeSats = quote.networkFeeSats.toULong().takeIf { state.isMax }, + // Savings never pay more than the Total the user confirmed, so a higher fee asks for another swipe. + approvedMiningFeeSats = quote.networkFeeSats.toULong(), ).getOrThrow() if (outcome !is OnchainSendOutcome.Accepted) { Logger.warn("Spark funding was not accepted: '$outcome'", context = TAG) @@ -311,8 +317,12 @@ class SparkFundingViewModel @Inject constructor( } onFundingAccepted(outcome.txid, outcome.amountSats ?: quote.amountSats.toULong(), quote) }.onFailure { - if (it.cause is OnchainSendChangedError) { + val changed = it.cause as? OnchainSendChangedError + if (changed != null) { Logger.info("Asking for another swipe, the funding changed since approved", context = TAG) + // A fixed amount's coin selection can need more fee than its quote, + // so this transfer's quotes show at least that, and the next swipe approves it. + if (!state.isMax) fixedFeeFloorSats = changed.preparedFeeSats quote().onSuccess { repriced -> showQuote(repriced) toastFeesChanged(repriced.increaseOver(quote, state.speed)) @@ -407,7 +417,7 @@ class SparkFundingViewModel @Inject constructor( address = address, speed = SPEED, feeRates = feeRates, - ).getOrThrow() + ).getOrThrow().coerceAtLeast(fixedFeeFloorSats ?: 0uL) } val amount = if (state.isMax) (spendable.safe() - networkFee.safe()) else state.amountSats.toULong() val instantFee = sparkRepo.estimateDepositClaimFeeSats(amount).getOrThrow() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 62a66af0d5..fa31e46704 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2894,7 +2894,8 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(1, broadcasts) } else { val error = assertIs(result.exceptionOrNull(), "Sent $amount for $fee") - assertIs(error.cause) + val changed = assertIs(error.cause) + assertEquals(fee, changed.preparedFeeSats, "Sent $amount for $fee") assertEquals(0, broadcasts) } } 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 74d63cebc4..b9665cad2d 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 @@ -34,7 +34,9 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.OnchainSendBlockedError +import to.bitkit.repositories.OnchainSendChangedError import to.bitkit.repositories.OnchainSendEvidence +import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim @@ -158,6 +160,51 @@ class SparkFundingViewModelTest : BaseUnitTest() { ) } + @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)) + .thenReturn("rose {amount}") + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + }.thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 700uL)))) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + + val toasts = collectToasts { sut.onConfirm() } + + verify(lightningRepo).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = eq(500uL), + ) + assertEquals("Changed", toasts.single().title) + assertTrue(toasts.single().description.orEmpty().startsWith("rose "), "${toasts.single().description}") + assertEquals(50_700L, sut.uiState.value.quote?.totalSats, "the new quote shows the fee that was refused") + assertEquals(false, sut.uiState.value.isSending) + + sut.onConfirm() + advanceUntilIdle() + + verify(lightningRepo).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = eq(700uL), + ) + } + @Test fun `swipe refuses with real copy when savings no longer cover the transfer`() = test { val sut = createSut() From 81e1f8f29af1488138b93368d35fbe195ad353c3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 15:17:51 +0100 Subject: [PATCH 082/135] fix: clear the kept spark balance once spark syncs --- .../java/to/bitkit/repositories/SparkRepo.kt | 33 ++++++++++++++----- .../java/to/bitkit/repositories/WalletRepo.kt | 2 +- app/src/main/java/to/bitkit/ui/ContentView.kt | 2 +- .../LightningConnectionsViewModel.kt | 6 ++-- .../usecases/DeriveBalanceStateUseCase.kt | 2 +- .../to/bitkit/repositories/SparkRepoTest.kt | 29 ++++++++++++++-- 6 files changed, 56 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index a4080b8ac4..c4e93c966c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -115,10 +115,11 @@ class SparkRepo @Inject constructor( private val withdrawalTxids = ConcurrentHashMap.newKeySet() /** - * Set by a failed withdrawal until Spark reads a balance again: while its operators stay down, Spark can read 0 - * with the funds still there, so the last known balance stays shown. + * When a withdrawal last failed, in seconds since 1970, until Spark reads a balance again or syncs after it: while + * its operators stay down, Spark can read 0 with the funds still there, so the last balance stays shown. */ - private val withdrawalFailed = AtomicBoolean(false) + @Volatile + private var withdrawalFailedAtSecs: ULong? = null /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ private val broadcastDeposits = ConcurrentHashMap() @@ -206,7 +207,7 @@ class SparkRepo @Inject constructor( earlyClaimVouts.clear() preparedWithdrawal = null withdrawalTxids.clear() - withdrawalFailed.set(false) + withdrawalFailedAtSecs = null broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() @@ -497,11 +498,11 @@ class SparkRepo @Inject constructor( (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } Unit }.onSuccess { - withdrawalFailed.set(false) + withdrawalFailedAtSecs = null runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after its withdrawal", it, context = TAG) } }.onFailure { - withdrawalFailed.set(true) + withdrawalFailedAtSecs = clock.now().epochSeconds.toULong() Logger.error("Failed to withdraw from Spark", it, context = TAG) } } @@ -645,12 +646,17 @@ class SparkRepo @Inject constructor( .filter { it.txid.lowercase() !in claimedTxids } .map { SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) } (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } - if (info.balanceSats > 0uL) withdrawalFailed.set(false) - val isStale = withdrawalFailed.get() || info.lastSyncError != null + val failedAt = withdrawalFailedAtSecs + val hasSyncedSince = failedAt != null && info.lastSyncError == null && (info.lastSyncedAt ?: 0uL) > failedAt + if (info.balanceSats > 0uL || hasSyncedSince) withdrawalFailedAtSecs = null + val isStale = withdrawalFailedAtSecs != null || info.lastSyncError != null _state.update { it.copy( isReady = true, - balanceSats = if (info.balanceSats == 0uL && isStale) it.balanceSats else info.balanceSats, + balanceSats = info.balanceSats, + keptBalanceSats = it.shownBalanceSats.takeIf { kept -> + info.balanceSats == 0uL && isStale && kept > 0uL + }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), withdrawals = payments.toWithdrawals(), @@ -1009,7 +1015,13 @@ 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, + /** What Spark read, which sends and withdrawals use. */ val balanceSats: ULong = 0uL, + /** + * The balance shown while Spark reads 0 after a failed withdrawal or a failed sync, with the funds likely still + * there; null once Spark reads a balance again or syncs after the failure. Never offered to a send. + */ + val keptBalanceSats: ULong? = null, /** Deposits seen on-chain that Spark claims into [balanceSats] after 3 confirmations. */ val pendingDepositSats: ULong = 0uL, val deposits: ImmutableList = persistentListOf(), @@ -1017,6 +1029,9 @@ data class SparkState( ) { /** The most Spark can send once its service fee is paid, so a payment near the full balance isn't offered. */ val sendableSats: ULong get() = SparkFees.sendableSats(balanceSats) + + /** The balance shown in Spending and on the Spark connection, which [keptBalanceSats] stands in for. */ + val shownBalanceSats: ULong get() = keptBalanceSats ?: balanceSats } object SparkFees { diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index db5445e6e5..e45bf2b573 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -135,7 +135,7 @@ class WalletRepo @Inject constructor( } } repoScope.launch { - sparkRepo.state.map { it.balanceSats to it.pendingDepositSats }.distinctUntilChanged().collect { + sparkRepo.state.map { it.shownBalanceSats to it.pendingDepositSats }.distinctUntilChanged().collect { if (walletExists()) syncBalances() } } diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 9aee983b5f..1f46fe73fe 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -1381,7 +1381,7 @@ private fun NavGraphBuilder.home( SpendingWalletScreen( channels = lightningState.channels, - hasSparkBalance = sparkState.balanceSats > 0uL, + hasSparkBalance = sparkState.shownBalanceSats > 0uL, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { 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 2687b39880..b90294382a 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 @@ -115,7 +115,7 @@ class LightningConnectionsViewModel @Inject constructor( pendingConnections = channels.filterPending() .map { it.mapToUiModel(channels, connectionText) } .reversed().toImmutableList(), - localBalance = calculateLocalBalance(channels).safe() + sparkState.balanceSats.safe(), + localBalance = calculateLocalBalance(channels).safe() + sparkState.shownBalanceSats.safe(), remoteBalance = channels.calculateRemoteBalance(), spark = sparkState.toUi(lightningRepo), isSparkReceiving = sparkState.isReady, @@ -252,9 +252,9 @@ data class SparkDepositUi( internal suspend fun SparkState.toUi(lightningRepo: LightningRepo): SparkUi? { if (!isReady) return null // On regtest Spark always shows, so testers reach its deposit address to fund it from the faucet. - if (balanceSats == 0uL && deposits.isEmpty() && Env.network != Network.REGTEST) return null + if (shownBalanceSats == 0uL && deposits.isEmpty() && Env.network != Network.REGTEST) return null return SparkUi( - balanceSats = balanceSats, + balanceSats = shownBalanceSats, deposits = deposits.map { SparkDepositUi(it, if (it.isClaimed) null else lightningRepo.onchainConfirmations(it.txid)) }.toImmutableList(), diff --git a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt index 56c740e63f..eab2df0941 100644 --- a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt @@ -52,7 +52,7 @@ class DeriveBalanceStateUseCase @Inject constructor( val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance()) val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe() val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe() - val sparkSats = sparkRepo.state.value.balanceSats + val sparkSats = sparkRepo.state.value.shownBalanceSats val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 98820c0ad6..00109c0d96 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -842,7 +842,29 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(0uL)) sut.refreshState().getOrThrow() - assertEquals(10_000uL, sut.state.value.balanceSats, "the balance read 0 after the failed withdrawal") + assertEquals(10_000uL, sut.state.value.shownBalanceSats, "the balance read 0 after the failed withdrawal") + assertEquals(0uL, sut.state.value.sendableSats, "a send was offered from the kept balance") + } + + @Test + fun `a synced read after a failed withdrawal clears the kept balance even when it reads zero`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("operators unreachable") } + val sut = createSut() + sut.refreshState().getOrThrow() + assertTrue(sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isFailure) + + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() - 60uL)) + sut.refreshState().getOrThrow() + val kept = sut.state.value.shownBalanceSats + assertEquals(10_000uL, kept, "a sync from before the failure cleared the kept balance") + + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) + sut.refreshState().getOrThrow() + assertEquals(0uL, sut.state.value.shownBalanceSats, "a sync after the failure kept the old balance") } @Test @@ -855,11 +877,12 @@ class SparkRepoTest : BaseUnitTest() { val syncFailed = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) whenever { sparkService.getInfo() }.thenReturn(syncFailed) sut.refreshState().getOrThrow() - assertEquals(10_000uL, sut.state.value.balanceSats, "the balance read 0 while the sync failed") + assertEquals(10_000uL, sut.state.value.shownBalanceSats, "the balance read 0 while the sync failed") + assertEquals(0uL, sut.state.value.sendableSats, "a send was offered from the kept balance") whenever { sparkService.getInfo() }.thenReturn(info(0uL)) sut.refreshState().getOrThrow() - assertEquals(0uL, sut.state.value.balanceSats) + assertEquals(0uL, sut.state.value.shownBalanceSats) } @Test From 41a63529f8296d0ff01c0de6dc8edb2611cf191c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 15:17:51 +0100 Subject: [PATCH 083/135] fix: keep a node retry's hold through an older listing --- .../to/bitkit/repositories/LightningRepo.kt | 5 +++- .../bitkit/repositories/LightningRepoTest.kt | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 0792f5380e..5241f82854 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1540,6 +1540,7 @@ class LightningRepo @Inject constructor( */ private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) + val recordsBefore = ldkSendRecords.get() val payments = listPaymentsKeepingSendHashes() if (payments == null) { val cache = cacheStore.data.first() @@ -1555,7 +1556,9 @@ class LightningRepo @Inject constructor( it.direction == PaymentDirection.OUTBOUND && (kind.bolt11.equals(bolt11, ignoreCase = true) || kind.hash.equals(paymentHash, ignoreCase = true)) } - if (send == null || send.status == PaymentStatus.FAILED) cacheStore.removeLdkSendHash(key) + // A retry in flight, or one recorded while the listing was read, holds the invoice again. + val isRetried = key in ldkSendsInFlight || (ldkSendRecordedAt[key] ?: 0L) > recordsBefore + if ((send == null || send.status == PaymentStatus.FAILED) && !isRetried) cacheStore.removeLdkSendHash(key) if (send == null) return null val hash = (send.kind as PaymentKind.Bolt11).hash return when (send.status) { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index fa31e46704..6f23cd93a9 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1456,6 +1456,32 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(listOf("h"), store.data.first().ldkSendHashes) } + @Test + fun `a node retry of the same invoice that ends while an older listing is read keeps its hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + var isRetried = false + // The node retries the invoice Spark is about to pay, and its send returns, while this listing is read. + whenever(lightningService.listPayments()).doSuspendableAnswer { + val listed = listOf(nodeSend("h", PaymentStatus.FAILED)) + if (!isRetried) { + isRetried = true + sut.payInvoiceWithNode("h") + } + listed + } + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("h")) + + sut.payInvoice("h", 1_000uL) + + assertEquals(listOf("h"), store.data.first().ldkSendHashes, "an older listing released the node retry's hold") + } + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( id = hash, kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), From bc2513f4804c86d166a5939349fa43f1c53411ff Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:51:20 +0100 Subject: [PATCH 084/135] fix: fit the spending amount number pad to the screen --- .../java/to/bitkit/ui/components/NumberPad.kt | 19 ++- .../screens/transfer/SpendingAmountScreen.kt | 125 ++++++++++-------- .../java/to/bitkit/ui/utils/ScreenSize.kt | 17 +++ .../transfer/SpendingAmountScreenTest.kt | 86 ++++++++++++ 4 files changed, 186 insertions(+), 61 deletions(-) create mode 100644 app/src/main/java/to/bitkit/ui/utils/ScreenSize.kt create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SpendingAmountScreenTest.kt diff --git a/app/src/main/java/to/bitkit/ui/components/NumberPad.kt b/app/src/main/java/to/bitkit/ui/components/NumberPad.kt index 1c7b4f2993..491e8fed01 100644 --- a/app/src/main/java/to/bitkit/ui/components/NumberPad.kt +++ b/app/src/main/java/to/bitkit/ui/components/NumberPad.kt @@ -37,6 +37,7 @@ import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.min import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay @@ -57,7 +58,6 @@ import kotlin.time.Duration.Companion.milliseconds const val KEY_DELETE = "delete" const val KEY_000 = "000" const val KEY_DECIMAL = "." -private val defaultHeight = 300.dp private const val FOCUS_RETRY_COUNT = 10 private val FOCUS_RETRY_DELAY = 50.milliseconds private val idealButtonHeight = 75.dp @@ -75,13 +75,18 @@ private const val DISABLED_ALPHA = 0.64f /** * Numeric keyboard. + * + * Rows take [idealRowHeight] when there is room. A fixed height splits evenly into the rows; a bounded one + * shrinks them to fit, down to [minRowHeight]. */ @Composable fun NumberPad( onPress: OnKeyPress, modifier: Modifier = Modifier, type: NumberPadType = NumberPadType.SIMPLE, - availableHeight: Dp = defaultHeight, + idealRowHeight: Dp = idealButtonHeight, + minRowHeight: Dp = minButtonHeight, + availableHeight: Dp = idealRowHeight * ROWS, decimalSeparator: String = KEY_DECIMAL, errorKey: String? = null, enabled: Boolean = true, @@ -115,7 +120,9 @@ fun NumberPad( ) { val buttonHeight = when { constraints.hasFixedHeight -> maxHeight / ROWS - else -> (availableHeight / ROWS).coerceIn(minButtonHeight, idealButtonHeight) + constraints.hasBoundedHeight -> (min(maxHeight, availableHeight) / ROWS) + .coerceIn(minRowHeight, idealRowHeight) + else -> (availableHeight / ROWS).coerceIn(minRowHeight, idealRowHeight) } val totalKeyboardHeight = buttonHeight * ROWS @@ -190,7 +197,9 @@ fun NumberPad( currencies: CurrencyState = LocalCurrencies.current, enabled: Boolean = true, type: NumberPadType = viewModel.getNumberPadType(currencies), - availableHeight: Dp = defaultHeight, + idealRowHeight: Dp = idealButtonHeight, + minRowHeight: Dp = minButtonHeight, + availableHeight: Dp = idealRowHeight * ROWS, decimalSeparator: String = KEY_DECIMAL, includeNavigationBarsPadding: Boolean = false, ) { @@ -200,6 +209,8 @@ fun NumberPad( modifier = modifier, enabled = enabled, type = type, + idealRowHeight = idealRowHeight, + minRowHeight = minRowHeight, availableHeight = availableHeight, decimalSeparator = decimalSeparator, errorKey = uiState.errorKey, diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt index 68a2bc498d..68d08a0fec 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt @@ -30,7 +30,6 @@ import to.bitkit.repositories.CurrencyState import to.bitkit.ui.LocalCurrencies import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.Display -import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.FillWidth import to.bitkit.ui.components.MoneySSB import to.bitkit.ui.components.NumberPad @@ -53,6 +52,12 @@ import to.bitkit.viewmodels.AmountInputEffect import to.bitkit.viewmodels.AmountInputViewModel import to.bitkit.viewmodels.previewAmountInputViewModel +/** Number pad row height when the screen has room, as iOS and Figma draw it; rows shrink to fit below that. */ +private val PAD_ROW_HEIGHT = 78.dp + +/** Shortest number pad row, reached only when four 50 dp rows don't fit, as on a 640 dp tall phone. */ +private val PAD_ROW_MIN_HEIGHT = 40.dp + @Suppress("ViewModelForwarding") @Composable fun SpendingAmountScreen( @@ -118,7 +123,7 @@ fun SpendingAmountScreen( @Suppress("ViewModelForwarding") @Composable -private fun Content( +internal fun Content( uiState: UiState, amountInputViewModel: AmountInputViewModel, onBackClick: () -> Unit, @@ -198,69 +203,75 @@ private fun SpendingAmountNodeRunning( .testTag("${tag}NumberField") ) - FillHeight() - - Row( - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.testTag( - if (isHardware) "HardwareTransferAmountNumberPad" else "SendAmountNumberPad" - ) + Column( + verticalArrangement = Arrangement.Bottom, + modifier = Modifier.weight(1f) ) { - Column { - Text13Up( - text = stringResource(R.string.wallet__send_available), - color = Colors.White64, - modifier = Modifier.testTag("${tag}Available") + Row( + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.testTag( + if (isHardware) "HardwareTransferAmountNumberPad" else "SendAmountNumberPad" ) - VerticalSpacer(8.dp) - MoneySSB( - sats = uiState.maxSats, - showSymbol = true, - modifier = Modifier.testTag("${tag}Unit") + ) { + Column { + Text13Up( + text = stringResource(R.string.wallet__send_available), + color = Colors.White64, + modifier = Modifier.testTag("${tag}Available") + ) + VerticalSpacer(8.dp) + MoneySSB( + sats = uiState.maxSats, + showSymbol = true, + modifier = Modifier.testTag("${tag}Unit") + ) + } + FillWidth() + UnitButton( + color = Colors.Purple, + onClick = { amountInputViewModel.switchUnit(currencies) }, + modifier = Modifier.testTag( + if (isHardware) "HardwareTransferAmountUnitButton" else "SpendingNumberPadUnit" + ) ) - } - FillWidth() - UnitButton( - color = Colors.Purple, - onClick = { amountInputViewModel.switchUnit(currencies) }, - modifier = Modifier.testTag( - if (isHardware) "HardwareTransferAmountUnitButton" else "SpendingNumberPadUnit" + NumberPadActionButton( + text = stringResource(R.string.lightning__spending_amount__quarter), + color = Colors.Purple, + enabled = isReady && hasFunds, + onClick = onClickQuarter, + modifier = Modifier.testTag("${tag}Quarter") ) - ) - NumberPadActionButton( - text = stringResource(R.string.lightning__spending_amount__quarter), - color = Colors.Purple, - enabled = isReady && hasFunds, - onClick = onClickQuarter, - modifier = Modifier.testTag("${tag}Quarter") - ) - NumberPadActionButton( - text = stringResource(R.string.common__max), - color = Colors.Purple, - enabled = isReady && hasFunds, - onClick = onClickMaxAmount, - modifier = Modifier.testTag("${tag}Max") - ) - } + NumberPadActionButton( + text = stringResource(R.string.common__max), + color = Colors.Purple, + enabled = isReady && hasFunds, + onClick = onClickMaxAmount, + modifier = Modifier.testTag("${tag}Max") + ) + } - HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) + HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) - NumberPad( - viewModel = amountInputViewModel, - currencies = currencies, - enabled = isReady && hasFunds, - ) + NumberPad( + viewModel = amountInputViewModel, + currencies = currencies, + enabled = isReady && hasFunds, + idealRowHeight = PAD_ROW_HEIGHT, + minRowHeight = PAD_ROW_MIN_HEIGHT, + modifier = Modifier.weight(1f, fill = false) + ) - PrimaryButton( - text = stringResource(R.string.common__continue), - onClick = onConfirmAmount, - enabled = isReady && amountUiState.sats > 0 && amountUiState.sats <= uiState.maxSats, - isLoading = uiState.isLoading, - modifier = Modifier.testTag("${tag}Continue") - ) + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onConfirmAmount, + enabled = isReady && amountUiState.sats > 0 && amountUiState.sats <= uiState.maxSats, + isLoading = uiState.isLoading, + modifier = Modifier.testTag("${tag}Continue") + ) - VerticalSpacer(16.dp) + VerticalSpacer(16.dp) + } } } diff --git a/app/src/main/java/to/bitkit/ui/utils/ScreenSize.kt b/app/src/main/java/to/bitkit/ui/utils/ScreenSize.kt new file mode 100644 index 0000000000..0757f5e7fa --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/utils/ScreenSize.kt @@ -0,0 +1,17 @@ +package to.bitkit.ui.utils + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.Dp + +/** The window's width, for sizes set as a share of the screen. */ +@ReadOnlyComposable +@Composable +fun screenWidth(): Dp = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.width.toDp() } + +/** The window's height, for sizes set as a share of the screen. */ +@ReadOnlyComposable +@Composable +fun screenHeight(): Dp = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingAmountScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingAmountScreenTest.kt new file mode 100644 index 0000000000..aadb4526fb --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingAmountScreenTest.kt @@ -0,0 +1,86 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.height +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.repositories.CurrencyState +import to.bitkit.ui.screens.transfer.SparkFundingContract.UiState +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.previewAmountInputViewModel +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@RunWith(RobolectricTestRunner::class) +class SpendingAmountScreenTest { + @get:Rule + val composeRule = createComposeRule() + + @Config(sdk = [34], qualifiers = "w448dp-h997dp") + @Test + fun `number pad rows are 78 dp when the screen has room`() { + setContent() + + val row = composeRule.onNodeWithTag("N1").getUnclippedBoundsInRoot() + + assertEquals(78f, row.height.value, 0.5f) + } + + @Config(sdk = [34], qualifiers = "w360dp-h640dp") + @Test + fun `the amount screen fits a small screen with the continue button above the system bars`() { + setContent(statusBar = STATUS_BAR, navigationBar = NAVIGATION_BAR) + + val row = composeRule.onNodeWithTag("N1").getUnclippedBoundsInRoot() + val button = composeRule.onNodeWithTag("SpendingAmountContinue").getUnclippedBoundsInRoot() + val root = composeRule.onRoot().getUnclippedBoundsInRoot() + + val lastRow = composeRule.onNodeWithTag("N0").getUnclippedBoundsInRoot() + assertTrue(row.height.value in 40f..50f, "row is ${row.height}") + assertTrue(lastRow.bottom <= button.top, "last row ends at ${lastRow.bottom}, continue at ${button.top}") + assertTrue( + button.bottom <= root.bottom - NAVIGATION_BAR, + "continue ends at ${button.bottom}, navigation bar starts at ${root.bottom - NAVIGATION_BAR}", + ) + } + + /** Pads the screen as the system bars do on a device, since Robolectric reports no insets. */ + private fun setContent(statusBar: Dp = 0.dp, navigationBar: Dp = 0.dp) { + composeRule.setContent { + // Inspection mode formats amounts without the currency view model, as previews do. + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { + Box(Modifier.padding(top = statusBar, bottom = navigationBar)) { + Content( + uiState = UiState(isNodeRunning = true, isMaxLoading = false, maxSats = 158_234), + amountInputViewModel = previewAmountInputViewModel(currencies = CurrencyState()), + currencies = CurrencyState(), + onBackClick = {}, + onClickQuarter = {}, + onClickMaxAmount = {}, + onConfirmAmount = {}, + ) + } + } + } + } + } + + private companion object { + val STATUS_BAR = 24.dp + val NAVIGATION_BAR = 48.dp + } +} From 918279a448f0b023a6b280d0bf034666a9cfc2ef Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:54:19 +0100 Subject: [PATCH 085/135] fix: size the funds in transfer rings and arrows like ios --- .../screens/transfer/SavingsProgressScreen.kt | 13 +++ .../components/TransferAnimationView.kt | 91 +++++++++++-------- .../transfer/SavingsProgressScreenTest.kt | 13 +++ .../screens/transfer/SettingUpScreenTest.kt | 28 +++++- 4 files changed, 107 insertions(+), 38 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt index 3fdd132cc7..dc07ec1c48 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt @@ -39,6 +39,7 @@ import to.bitkit.ui.screens.transfer.components.TransferAnimationView import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.removeAccentTags +import to.bitkit.ui.utils.screenWidth import to.bitkit.ui.utils.withAccent import to.bitkit.ui.utils.withAccentBoldBright import to.bitkit.viewmodels.AppViewModel @@ -157,6 +158,15 @@ fun SavingsProgressScreen( ) } +/** Outer ring against the screen width, as iOS draws its 311 pt ring on a 402 pt screen. */ +private const val RING_SCREEN_SHARE = 311f / 402f + +/** Inner ring against the outer one, iOS's 207 of 311 pt. */ +private const val INNER_RING_SHARE = 207f / 311f + +/** The figure's square against the outer ring, iOS's 256 of 311 pt. */ +private const val FIGURE_SHARE = 256f / 311f + /** Legacy path: cooperatively close the selected channel(s), retrying on failure. */ private suspend fun runChannelClose( transfer: TransferViewModel, @@ -235,6 +245,9 @@ internal fun SavingsProgressContent( largeCircleRes = R.drawable.onchain_sync_large, smallCircleRes = R.drawable.onchain_sync_small, keepAssetRatios = true, + innerRingShare = INNER_RING_SHARE, + figureShare = FIGURE_SHARE, + maxSize = screenWidth() * RING_SCREEN_SHARE, ) } else { Box( diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt index 097f76eb43..84fcfd8820 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/components/TransferAnimationView.kt @@ -10,25 +10,34 @@ import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.rotate import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.min import to.bitkit.R import to.bitkit.ui.theme.AppThemeSurface +/** Inner ring size against the outer ring, as iOS's `EllipseLoader` draws it. */ +const val ELLIPSE_INNER_SHARE = 0.70f + +/** Side of the square the figure fits in, against the outer ring, as iOS's `EllipseLoader` `centerScale`. */ +const val ELLIPSE_FIGURE_SHARE = 0.85f + @Composable fun TransferAnimationView( @DrawableRes largeCircleRes: Int, @@ -38,6 +47,9 @@ fun TransferAnimationView( rotateContent: Boolean = true, contentWidthFraction: Float = 1f, keepAssetRatios: Boolean = false, + innerRingShare: Float = ELLIPSE_INNER_SHARE, + figureShare: Float = ELLIPSE_FIGURE_SHARE, + maxSize: Dp = Dp.Infinity, ) { val animationSpec: InfiniteRepeatableSpec = infiniteRepeatable( animation = tween(durationMillis = 3000, easing = EaseInOut), @@ -76,6 +88,9 @@ fun TransferAnimationView( rotationLarge = rotationLarge, rotationSmall = rotationSmall, rotationContent = if (rotateContent) rotationArrows else 0f, + innerRingShare = innerRingShare, + figureShare = figureShare, + maxSize = maxSize, ) return@Box } @@ -116,8 +131,8 @@ fun TransferAnimationView( } /** - * Draws the rings and figure at their sizes relative to the large ring, as the design sets them, at any density: - * the assets are `nodpi`, so drawn at their own pixel size the small ring grows against the clamped large one. + * Draws the rings and figure as iOS's `EllipseLoader` does: the outer ring fills the largest square that fits, up to + * [maxSize], the inner ring takes [innerRingShare] of it and the figure fits a square of [figureShare] of it. */ @Composable private fun ScaledLayers( @@ -127,40 +142,42 @@ private fun ScaledLayers( rotationLarge: Float, rotationSmall: Float, rotationContent: Float, + innerRingShare: Float, + figureShare: Float, + maxSize: Dp, ) { - val large = painterResource(largeCircleRes) - val small = painterResource(smallCircleRes) - val content = painterResource(contentRes) - val largeWidth = large.intrinsicSize.width - val maxSize = with(LocalDensity.current) { largeWidth.toDp() } - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .widthIn(max = maxSize) - .aspectRatio(1f), - ) { - Image( - painter = large, - contentDescription = null, - modifier = Modifier - .fillMaxSize() - .rotate(rotationLarge), - ) - Image( - painter = small, - contentDescription = null, + BoxWithConstraints(contentAlignment = Alignment.Center) { + val container = min(min(maxWidth, maxHeight), maxSize) + Box( + contentAlignment = Alignment.Center, modifier = Modifier - .fillMaxSize(small.intrinsicSize.width / largeWidth) - .rotate(rotationSmall), - ) - Image( - painter = content, - contentDescription = null, - contentScale = ContentScale.Fit, - modifier = Modifier - .fillMaxSize(content.intrinsicSize.width / largeWidth) - .rotate(rotationContent), - ) + .size(container) + .clipToBounds() + .testTag("TransferAnimation"), + ) { + Image( + painter = painterResource(largeCircleRes), + contentDescription = null, + modifier = Modifier + .fillMaxSize() + .rotate(rotationLarge), + ) + Image( + painter = painterResource(smallCircleRes), + contentDescription = null, + modifier = Modifier + .size(container * innerRingShare) + .rotate(rotationSmall), + ) + Image( + painter = painterResource(contentRes), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .size(container * figureShare) + .rotate(rotationContent), + ) + } } } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt index 82d6ae3f39..3d68a78d7c 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsProgressScreenTest.kt @@ -1,14 +1,17 @@ package to.bitkit.ui.screens.transfer +import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.width import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertEquals @Config(sdk = [34]) @RunWith(RobolectricTestRunner::class) @@ -34,6 +37,16 @@ class SavingsProgressScreenTest { composeRule.onNodeWithTag("SavingsSparkFailed-button").assertExists() } + @Config(sdk = [34], qualifiers = "w448dp-h997dp") + @Test + fun `the rings take the share of the screen width ios gives them`() { + setContent(SavingsProgressState.PROGRESS) + + val rings = composeRule.onNodeWithTag("TransferAnimation").getUnclippedBoundsInRoot() + + assertEquals(448f * 311f / 402f, rings.width.value, 0.5f) + } + private fun setContent(state: SavingsProgressState) { composeRule.setContent { AppThemeSurface { SavingsProgressContent(progressState = state) } } } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt index 85ef74c17d..71af5897d7 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt @@ -1,9 +1,13 @@ package to.bitkit.ui.screens.transfer +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.width import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -13,6 +17,7 @@ import to.bitkit.repositories.SparkClaimOffer import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertEquals import kotlin.test.assertTrue @Config(sdk = [34], qualifiers = "w320dp-h568dp") @@ -59,8 +64,29 @@ class SettingUpScreenTest { composeRule.onNodeWithText("SPEED: LATER").assertExists() } + @Config(sdk = [34], qualifiers = "w448dp-h997dp") + @Test + fun `the rings fill the width less 16 per side and keep their size when repriced`() { + setContent(SparkDepositClaim.Looking, SparkClaimSpeed.Instant) + val looking = composeRule.onNodeWithTag("TransferAnimation").getUnclippedBoundsInRoot() + + setContent(repriced, SparkClaimSpeed.Instant) + val repricedRings = composeRule.onNodeWithTag("TransferAnimation").getUnclippedBoundsInRoot() + + assertEquals(448f - 4 * 16f, looking.width.value, 0.5f) + assertEquals(looking.width.value, repricedRings.width.value, 0.5f) + } + + private var claimState by mutableStateOf?>(null) + private fun setContent(claim: SparkDepositClaim, speed: SparkClaimSpeed) { - composeRule.setContent { AppThemeSurface { Content(claim = claim, speed = speed) } } + val isFirst = claimState == null + claimState = claim to speed + if (!isFirst) return composeRule.waitForIdle() + composeRule.setContent { + val (shownClaim, shownSpeed) = requireNotNull(claimState) + AppThemeSurface { Content(claim = shownClaim, speed = shownSpeed) } + } } private val repriced = SparkDepositClaim.Repriced( From 18cad43868ba5fa40a0519d4849de22d1d7e0401 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:55:52 +0100 Subject: [PATCH 086/135] fix: size the funds moved check to the screen width --- .../to/bitkit/ui/screens/transfer/SettingUpScreen.kt | 12 ++++++++++-- .../ui/screens/transfer/SettingUpScreenTest.kt | 12 ++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt index a6f91b1bf7..66ce211857 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SettingUpScreen.kt @@ -5,9 +5,10 @@ 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.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue @@ -42,12 +43,16 @@ import to.bitkit.ui.screens.transfer.components.TransferAnimationView import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.localizedRandom +import to.bitkit.ui.utils.screenWidth import to.bitkit.ui.utils.withAccent import to.bitkit.ui.utils.withAccentBoldBright /** Confirmations Spark waits for before it adds a deposit by itself. */ private const val MATURE_CONFIRMATIONS = 3 +/** The success check's width against the screen's, as iOS draws its 256 pt check on a 402 pt screen. */ +private const val CHECK_SCREEN_SHARE = 256f / 402f + /** About how long [MATURE_CONFIRMATIONS] take. */ private const val MATURE_MINUTES = 30 @@ -170,7 +175,10 @@ internal fun Content( painter = painterResource(id = R.drawable.check), contentDescription = null, contentScale = ContentScale.Fit, - modifier = Modifier.size(256.dp) + modifier = Modifier + .width(screenWidth() * CHECK_SCREEN_SHARE) + .aspectRatio(1f) + .testTag("TransferSuccessCheck") ) } } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt index 71af5897d7..867f8a8e18 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt @@ -7,6 +7,7 @@ import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.height import androidx.compose.ui.unit.width import org.junit.Rule import org.junit.Test @@ -77,6 +78,17 @@ class SettingUpScreenTest { assertEquals(looking.width.value, repricedRings.width.value, 0.5f) } + @Config(sdk = [34], qualifiers = "w448dp-h997dp") + @Test + fun `the funds moved check takes the share of the screen width ios gives it`() { + setContent(SparkDepositClaim.Claimed, SparkClaimSpeed.Instant) + + val check = composeRule.onNodeWithTag("TransferSuccessCheck").getUnclippedBoundsInRoot() + + assertEquals(448f * 256f / 402f, check.width.value, 0.5f) + assertEquals(check.width.value, check.height.value, 0.5f) + } + private var claimState by mutableStateOf?>(null) private fun setContent(claim: SparkDepositClaim, speed: SparkClaimSpeed) { From fb3de0b8a1885647e350cf2488ed3a7db560831c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:56:35 +0100 Subject: [PATCH 087/135] fix: use the ios copy for the repriced instant transfer --- app/src/main/res/values/strings.xml | 2 +- .../java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 908ee9f2a2..b2f08e9418 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -378,7 +378,7 @@ Pathfinding Scores Sync Time Spark hasn\'t seen your transfer yet. It\'s added after 3 confirmations; you can leave this screen. Pay ₿ {amount} - Instant now costs <accent>₿ {amount}</accent>. Pay it, or wait for 3 confirmations, about 30 minutes, at a lower fee. + Instant now costs <accent>₿ {amount}</accent>. Pay it to add your transfer now, or wait for 3 confirmations, about 30 minutes. Speed: {speed} Adding To Spending Instant isn\'t available for this transfer. Spark adds it to your spending balance after 3 confirmations, about 30 minutes. diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt index 867f8a8e18..96d6b34116 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SettingUpScreenTest.kt @@ -38,6 +38,10 @@ class SettingUpScreenTest { assertTrue(label.bottom <= wait.top) assertTrue(wait.top == pay.top && wait.right < pay.left) composeRule.onNodeWithText("SPEED: INSTANT").assertExists() + composeRule.onNodeWithText( + "Pay it to add your transfer now, or wait for 3 confirmations, about 30 minutes.", + substring = true, + ).assertExists() } @Test From 63e668dee694955c94872d0ec296b0ee4b120b09 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:58:05 +0100 Subject: [PATCH 088/135] fix: mark to spending as an estimate at both speeds --- .../screens/transfer/SpendingConfirmScreen.kt | 11 +-- .../screens/transfer/SpendingFeeGridTest.kt | 68 +++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/transfer/SpendingFeeGridTest.kt 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 9b60b5df7b..f47aa68a52 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 @@ -208,11 +208,14 @@ private fun Content( } } -/** The four fee tiles of a transfer to spending, at the selected claim [speed]. */ +/** + * The four fee tiles of a transfer to spending, at the selected claim [speed]. The claim fee is an estimate at either + * speed, so the tiles that come from it, Spending fee and To spending, show `±`; Network fees and Total are exact. + */ @Composable internal fun SpendingFeeGrid(quote: Quote?, speed: SparkClaimSpeed, modifier: Modifier = Modifier) { Column(modifier = modifier) { - val claimPrefix = stringResource(R.string.lightning__spending_confirm__about) + val estimatePrefix = stringResource(R.string.lightning__spending_confirm__about) Row( horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.height(IntrinsicSize.Min) @@ -225,7 +228,7 @@ internal fun SpendingFeeGrid(quote: Quote?, speed: SparkClaimSpeed, modifier: Mo FeeInfo( label = stringResource(R.string.lightning__spending_confirm__spending_fee), amount = quote?.claimFeeSats(speed) ?: 0, - prefix = claimPrefix, + prefix = estimatePrefix, modifier = Modifier.testTag("SpendingConfirmSpendingFee") ) } @@ -236,7 +239,7 @@ internal fun SpendingFeeGrid(quote: Quote?, speed: SparkClaimSpeed, modifier: Mo FeeInfo( label = stringResource(R.string.lightning__spending_confirm__amount), amount = quote?.toSpendingSats(speed) ?: 0, - prefix = claimPrefix.takeIf { speed == SparkClaimSpeed.Later }, + prefix = estimatePrefix, modifier = Modifier.testTag("SpendingConfirmAmount") ) FeeInfo( diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingFeeGridTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingFeeGridTest.kt new file mode 100644 index 0000000000..dd633ecc95 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SpendingFeeGridTest.kt @@ -0,0 +1,68 @@ +package to.bitkit.ui.screens.transfer + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.createComposeRule +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.repositories.SparkClaimSpeed +import to.bitkit.ui.screens.transfer.SparkFundingContract.Quote +import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class SpendingFeeGridTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun `instant marks only the claim fee tiles as estimates`() { + setContent(SparkClaimSpeed.Instant) + + assertEstimates() + } + + @Test + fun `later marks only the claim fee tiles as estimates`() { + setContent(SparkClaimSpeed.Later) + + assertEstimates() + } + + private fun assertEstimates() { + assertTrue(hasEstimate("SpendingConfirmSpendingFee")) + assertTrue(hasEstimate("SpendingConfirmAmount")) + assertFalse(hasEstimate("SpendingConfirmNetworkFee")) + assertFalse(hasEstimate("SpendingConfirmTotal")) + } + + private fun hasEstimate(tag: String): Boolean = composeRule + .onAllNodes(hasText("±", substring = true) and hasAnyAncestor(hasTestTag(tag)), useUnmergedTree = true) + .fetchSemanticsNodes() + .isNotEmpty() + + private fun setContent(speed: SparkClaimSpeed) { + val quote = Quote( + address = "bcrt1q", + amountSats = 50_000, + networkFeeSats = 577, + instantFeeSats = 1_093, + laterFeeSats = 198, + spendableSats = 158_234, + ) + composeRule.setContent { + // Inspection mode formats amounts without the currency view model, as previews do. + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { SpendingFeeGrid(quote = quote, speed = speed) } + } + } + } +} From d5d3489de66120d4fea6c7d34c63e1f57f57cb8f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:59:30 +0100 Subject: [PATCH 089/135] fix: keep the savings confirm piggybank at full size --- .../screens/transfer/SavingsConfirmScreen.kt | 32 +++++++++------ .../transfer/SavingsConfirmScreenTest.kt | 39 +++++++++++++++++++ 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 2957a503ce..c5048860ba 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -16,7 +16,6 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -52,6 +51,7 @@ import to.bitkit.ui.components.Caption13Up import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.Display import to.bitkit.ui.components.FeeInfo +import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.GradientCircularProgressIndicator import to.bitkit.ui.components.MoneyDisplay import to.bitkit.ui.components.PrimaryButton @@ -65,12 +65,16 @@ import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.transferViewModel +import to.bitkit.ui.utils.screenWidth import to.bitkit.ui.utils.withAccent import to.bitkit.ui.walletViewModel import to.bitkit.viewmodels.SavingsSelection import to.bitkit.viewmodels.SavingsSwapQuote import to.bitkit.viewmodels.SavingsTransferMode +/** The piggybank's width against the screen's, as iOS draws its 256 pt piggybank on a 402 pt screen. */ +private const val PIGGY_SCREEN_SHARE = 256f / 402f + @Composable fun SavingsConfirmScreen( isOffline: Boolean, @@ -319,32 +323,36 @@ internal fun SavingsConfirmContent( } } - // Flexible middle: the piggybank fills the remaining space, so it shrinks when the - // fees/slider are shown (no squished buttons) and fills the gap while the quote loads. + // The piggybank keeps its size: when the fees, slider and Spark row make the content tall, + // it scrolls above the swipe instead of shrinking. + FillHeight() Box( + contentAlignment = Alignment.Center, modifier = Modifier - .weight(1f) .fillMaxWidth() .padding(vertical = 16.dp), - contentAlignment = Alignment.Center, ) { + val piggySize = screenWidth() * PIGGY_SCREEN_SHARE if (isPricingSwap) { - GradientCircularProgressIndicator( - modifier = Modifier.size(48.dp), - strokeWidth = 3.dp, - ) + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(piggySize)) { + GradientCircularProgressIndicator( + modifier = Modifier.size(48.dp), + strokeWidth = 3.dp, + ) + } } else { Image( painter = painterResource(R.drawable.piggybank), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier - .sizeIn(maxWidth = 256.dp, maxHeight = 256.dp) - .fillMaxSize() - .graphicsLayer(scaleX = -1f), + .size(piggySize) + .graphicsLayer(scaleX = -1f) + .testTag("SavingsConfirmPiggybank"), ) } } + FillHeight() } } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt index 824c9acc2c..cd866894a5 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt @@ -1,10 +1,13 @@ package to.bitkit.ui.screens.transfer +import androidx.compose.ui.test.getUnclippedBoundsInRoot 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 androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.unit.height +import androidx.compose.ui.unit.width import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -12,6 +15,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowSystemClock import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.SavingsSwapQuote import kotlin.test.assertEquals import kotlin.time.Duration.Companion.seconds import kotlin.time.toJavaDuration @@ -50,6 +54,41 @@ class SavingsConfirmScreenTest { composeRule.onNodeWithTag("SavingsSparkFeeRetry").assertDoesNotExist() } + @Config(sdk = [34], qualifiers = "w360dp-h640dp") + @Test + fun `the piggybank keeps its size when the fees slider and spark row make the content tall`() { + composeRule.setContent { + AppThemeSurface { + SavingsConfirmContent( + fallbackAmount = 69_000u, + sparkAmount = 12_000u, + sparkFeeSats = 1_470u, + isSparkFeePricing = false, + isSparkUnpriced = false, + isSparkTooSmall = false, + isSwapEnabled = true, + quote = SavingsSwapQuote( + amountSat = 69_000u, + networkFeeSat = 520u, + swapFeeSat = 245u, + receiveSat = 68_235u, + ), + isQuoteLoading = false, + minSat = 25_000u, + maxSat = 69_000u, + onAmountChange = {}, + hasMultiple = true, + hasSelected = false, + ) + } + } + + val piggy = composeRule.onNodeWithTag("SavingsConfirmPiggybank").getUnclippedBoundsInRoot() + + assertEquals(360f * 256f / 402f, piggy.width.value, 0.5f) + assertEquals(piggy.width.value, piggy.height.value, 0.5f) + } + private fun setContent( isSparkFeePricing: Boolean = false, isSparkUnpriced: Boolean = false, From fee40c785b27bea82d9d2c1dd86621fac98acc27 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 14:03:00 +0100 Subject: [PATCH 090/135] fix: size the receive on spending card to figma --- .../wallets/receive/ReceiveQrScreen.kt | 92 +++++++++++++------ .../wallets/receive/ReceiveQrScreenTest.kt | 17 ++++ 2 files changed, 80 insertions(+), 29 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt index c477fa965b..8b894f7d9a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt @@ -11,10 +11,11 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxHeight 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.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow @@ -77,6 +78,7 @@ import to.bitkit.ui.components.BottomSheetPreview import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Caption13Up import to.bitkit.ui.components.Display +import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.GradientCircularProgressIndicator import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.QrCodeImage @@ -96,8 +98,31 @@ import to.bitkit.ui.shared.util.shareText import to.bitkit.ui.theme.AppShapes import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.screenHeight +import to.bitkit.ui.utils.screenWidth import to.bitkit.ui.utils.withAccent +/** The Spending onboarding card's height against the screen's, as Figma draws it 343 pt tall on an 812 pt screen. */ +private const val CJIT_CARD_SCREEN_SHARE = 343f / 812f + +/** The gap from the onboarding card's bottom to the button's top, as Figma's 122 pt on an 812 pt screen. */ +private const val CJIT_CARD_BOTTOM_GAP_SHARE = 122f / 812f + +/** The spacing the screen already keeps above its bottom button. */ +private val BUTTON_TOP_SPACING = 24.dp + +/** The arrow under the onboarding card, as iOS draws it: 210 pt tall on an 874 pt screen. */ +private const val CJIT_ARROW_HEIGHT_SHARE = 210f / 874f + +/** The arrow's offset from the card's bottom left, as iOS's 70 pt on a 402 pt wide screen. */ +private const val CJIT_ARROW_X_SHARE = 70f / 402f + +/** The arrow's drop below the card's bottom, as iOS's 110 pt on an 874 pt screen. */ +private const val CJIT_ARROW_Y_SHARE = 110f / 874f + +/** Screens shorter than this leave out the arrow, as iOS does on its small screens. */ +private val CJIT_ARROW_MIN_SCREEN_HEIGHT = 800.dp + @OptIn(FlowPreview::class) @Composable @Suppress("CyclomaticComplexMethod") @@ -423,9 +448,19 @@ fun ReceiveQrScreen( ) { when { showingCjitOnboarding && tab == ReceiveTab.SPENDING -> { - CjitOnBoardingView( - modifier = Modifier.weight(1f) - ) + Box( + contentAlignment = Alignment.BottomCenter, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + CjitOnBoardingView( + modifier = Modifier + .fillMaxWidth() + .height(screenHeight() * CJIT_CARD_SCREEN_SHARE) + ) + } + VerticalSpacer(screenHeight() * CJIT_CARD_BOTTOM_GAP_SHARE - BUTTON_TOP_SPACING) } tab == ReceiveTab.HARDWARE && hardwareReceiveState.address == null -> { @@ -492,7 +527,7 @@ fun ReceiveQrScreen( } } - VerticalSpacer(24.dp) + VerticalSpacer(BUTTON_TOP_SPACING) val showCjitButton = showingCjitOnboarding && selectedTab == ReceiveTab.SPENDING val buttonVariant = when { @@ -704,42 +739,41 @@ fun ReceiveQrView( @Composable fun CjitOnBoardingView(modifier: Modifier = Modifier) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - modifier = modifier - .clip(AppShapes.small) - .background(color = Colors.Black) - .padding(32.dp) - ) { - Display(stringResource(R.string.wallet__receive_onboarding_title).withAccent(accentColor = Colors.Purple)) - VerticalSpacer(8.dp) - BodyM( - stringResource(R.string.wallet__receive_onboarding_description), - color = Colors.White64, - modifier = Modifier.fillMaxWidth() - ) - VerticalSpacer(32.dp) - Box( + val screenHeight = screenHeight() + Box(modifier = modifier) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier - .fillMaxWidth() - .weight(1f) + .fillMaxSize() + .testTag("ReceiveSpendingCard") + .clip(AppShapes.small) + .background(color = Colors.Black) + .padding(32.dp) ) { + Display(stringResource(R.string.wallet__receive_onboarding_title).withAccent(accentColor = Colors.Purple)) + VerticalSpacer(8.dp) + BodyM( + stringResource(R.string.wallet__receive_onboarding_description), + color = Colors.White64, + modifier = Modifier.fillMaxWidth() + ) + FillHeight() Icon( painter = painterResource(R.drawable.ic_lightning_alt), tint = Colors.Purple, contentDescription = null, - modifier = Modifier - .size(64.dp) - .align(Alignment.TopCenter) + modifier = Modifier.size(64.dp) ) + } + if (screenHeight >= CJIT_ARROW_MIN_SCREEN_HEIGHT) { Icon( painter = painterResource(R.drawable.arrow), tint = Colors.Purple, contentDescription = null, modifier = Modifier - .align(Alignment.CenterStart) - .padding(start = 32.dp) - .fillMaxHeight() + .align(Alignment.BottomStart) + .offset(x = screenWidth() * CJIT_ARROW_X_SHARE, y = screenHeight * CJIT_ARROW_Y_SHARE) + .height(screenHeight * CJIT_ARROW_HEIGHT_SHARE) ) } } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt index afdcacea34..e7d74e0549 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreenTest.kt @@ -2,10 +2,13 @@ package to.bitkit.ui.screens.wallets.receive import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.getUnclippedBoundsInRoot 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 androidx.compose.ui.unit.height +import androidx.compose.ui.unit.width import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -16,6 +19,7 @@ import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.LightningState import to.bitkit.repositories.WalletState import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertEquals import kotlin.time.Duration.Companion.seconds import kotlin.time.toJavaDuration @@ -41,6 +45,19 @@ class ReceiveQrScreenTest { composeRule.onNodeWithTag("ShowDetails").assertIsEnabled() } + @Config(sdk = [34], qualifiers = "w448dp-h997dp") + @Test + fun `the spending onboarding card takes figma's share of the screen height and gap`() { + setContent(NodeLifecycleState.Running) + + val card = composeRule.onNodeWithTag("ReceiveSpendingCard").getUnclippedBoundsInRoot() + val button = composeRule.onNodeWithTag("ShowDetails").getUnclippedBoundsInRoot() + + assertEquals(997f * 343f / 812f, card.height.value, 0.5f) + assertEquals(448f - 2 * 16f, card.width.value, 0.5f) + assertEquals(997f * 122f / 812f, (button.top - card.bottom).value, 0.5f) + } + /** Opens the Spending tab, as the screen starts on Savings while Lightning can't receive. */ private fun setContent(nodeState: NodeLifecycleState) { composeRule.setContent { From f7bb9c4fd369f3bd44836434e0b5f371bd7689a4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 15:23:40 +0100 Subject: [PATCH 091/135] fix: drop a pending transfer quote when the amount screen leaves --- .../screens/transfer/SparkFundingViewModel.kt | 9 ++++++- .../screens/transfer/SpendingAmountScreen.kt | 5 ++++ .../transfer/SparkFundingViewModelTest.kt | 27 +++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) 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 8e481224c4..94a8e3aca9 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 @@ -82,6 +82,7 @@ class SparkFundingViewModel @Inject constructor( private var maxJob: Job? = null private var quoteJob: Job? = null + private var amountJob: Job? = null private var retainedFundingJob: Job? = null /** The kept funding this screen settles, held until the screen closes so its recovery never takes over. */ @@ -161,11 +162,17 @@ class SparkFundingViewModel @Inject constructor( ) } + /** Drops a pricing still running when the amount screen leaves, so its quote never opens confirm. */ + fun onAmountLeave() { + amountJob?.cancel() + _uiState.update { it.copy(isLoading = false) } + } + /** Prices the transfer and moves on to the confirm screen when Savings can cover it and Spark can add it. */ fun onAmountContinue() { if (_uiState.value.isLoading) return _uiState.update { it.copy(isLoading = true) } - viewModelScope.launch { + amountJob = viewModelScope.launch { val quote = quote().getOrElse { Logger.error("Failed to price Spark funding", it, context = TAG) toastQuoteError() diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt index 68d08a0fec..6c51e3de91 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SpendingAmountScreen.kt @@ -24,6 +24,8 @@ import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R import to.bitkit.repositories.CurrencyState @@ -81,6 +83,9 @@ fun SpendingAmountScreen( viewModel.onAmountChange(amountUiState.sats) } + // A pricing that lands after the screen starts leaving must not open confirm over the screen behind it. + LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.onAmountLeave() } + LaunchedEffect(viewModel, onQuoteReady) { viewModel.effects.collect { if (it == SideEffect.AmountReady) onQuoteReady() 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 b9665cad2d..22fd8439fc 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 @@ -6,6 +6,7 @@ import androidx.lifecycle.ViewModelStore import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.synonym.bitkitcore.FeeRates +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch @@ -16,6 +17,7 @@ import org.junit.Test import org.lightningdevkit.ldknode.BalanceDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -136,6 +138,31 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals(49_802L, quote.toSpendingSats(SparkClaimSpeed.Later)) } + @Test + fun `leaving the amount screen while pricing never opens confirm`() = test { + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + val gate = CompletableDeferred() + whenever(lightningRepo.getFeeRates()).doSuspendableAnswer { + gate.await() + Result.success(feeRates) + } + val effects = mutableListOf() + val job = launch { sut.effects.collect { effects.add(it) } } + + sut.onAmountContinue() + advanceUntilIdle() + sut.onAmountLeave() + gate.complete(Unit) + advanceUntilIdle() + job.cancel() + + assertEquals(emptyList(), effects) + assertEquals(false, sut.uiState.value.isLoading) + assertEquals(null, sut.uiState.value.quote) + } + @Test fun `swipe asks again when the network fee rose since shown`() = test { val sut = createSut() From 7c8b0eeb5ca3680f5db3584702e84d23579fb756 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 15:27:35 +0100 Subject: [PATCH 092/135] fix: name the new amount when a max transfer changes at swipe --- .../screens/transfer/SparkFundingViewModel.kt | 17 ++++++++-- app/src/main/res/values/strings.xml | 2 ++ .../transfer/SparkFundingViewModelTest.kt | 34 +++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 94a8e3aca9..218a8e1bfd 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 @@ -258,8 +258,14 @@ class SparkFundingViewModel @Inject constructor( } val increase = quote.increaseOver(shownQuote, shown.speed) if (increase > 0) { - Logger.info("Asking for another swipe, fees rose since shown", context = TAG) - toastFeesChanged(increase) + // A max transfer sends what Savings can afford, so its amount moves with the fee rates and balance. + if (shown.isMax && quote.amountSats != shownQuote.amountSats) { + Logger.info("Asking for another swipe, the max amount changed since shown", context = TAG) + toastMaxChanged(quote.toSpendingSats(shown.speed)) + } else { + Logger.info("Asking for another swipe, fees rose since shown", context = TAG) + toastFeesChanged(increase) + } _uiState.update { it.copy(isSending = false) } return@launch } @@ -475,6 +481,13 @@ class SparkFundingViewModel @Inject constructor( type = Toast.ToastType.INFO, ) + private fun toastMaxChanged(toSpendingSats: Long) = toast( + title = R.string.lightning__spending_confirm__max_changed_title, + description = context.getString(R.string.lightning__spending_confirm__max_changed) + .replace("{amount}", formatPrimaryAmount(toSpendingSats)), + type = Toast.ToastType.INFO, + ) + private fun toastQuoteError() = toast( title = R.string.lightning__spending_confirm__quote_error_title, description = context.getString(R.string.lightning__spending_confirm__quote_error_text), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b2f08e9418..4e2c0fd628 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -417,6 +417,8 @@ Ready in a few minutes After 3 confirmations, about 30 minutes Service fees + The most you can transfer is now {amount}, because fee rates or your savings balance changed while you were on this screen. Swipe again to confirm. + Amount changed Network fees Bitkit couldn\'t get the current fees for this transfer. Check your connection and try again. Fees Unavailable 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 22fd8439fc..aa38406839 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 @@ -232,6 +232,40 @@ class SparkFundingViewModelTest : BaseUnitTest() { ) } + @Test + fun `swipe on a max transfer whose amount fell names the new amount instead of a fee rise`() = test { + whenever(context.getString(R.string.lightning__spending_confirm__max_changed_title)) + .thenReturn("Amount changed") + whenever(context.getString(R.string.lightning__spending_confirm__max_changed)).thenReturn("Max {amount}") + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(sut.uiState.value.maxSats) + sut.onAmountContinue() + advanceUntilIdle() + whenever { lightningRepo.estimateSendAllFee(any(), any(), any()) }.thenReturn(Result.success(800uL)) + + val toasts = collectToasts { sut.onConfirm() } + + assertEquals("Amount changed", toasts.single().title) + // 100,000 savings less the 800 sat network fee and the 1,350 sat claim fee. + assertEquals("Max ₿ ${97_850L.formatToModernDisplay()}", toasts.single().description) + assertEquals(false, sut.uiState.value.isSending) + } + + @Test + fun `swipe on a max transfer whose claim fee alone rose still names the fee rise`() = test { + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(sut.uiState.value.maxSats) + sut.onAmountContinue() + advanceUntilIdle() + whenever { sparkRepo.estimateDepositClaimFeeSats(any()) }.thenReturn(Result.success(1_500uL)) + + val toasts = collectToasts { sut.onConfirm() } + + assertEquals("Changed", toasts.single().title) + } + @Test fun `swipe refuses with real copy when savings no longer cover the transfer`() = test { val sut = createSut() From ebb1e18f481177e2bd55a032c724e3d56645e07c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:48:01 +0100 Subject: [PATCH 093/135] fix: keep a send that ends during a listing held --- .../to/bitkit/repositories/LightningRepo.kt | 21 ++++-- .../java/to/bitkit/repositories/SparkRepo.kt | 14 ++-- .../bitkit/repositories/LightningRepoTest.kt | 30 ++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 70 +++++++++++++++++++ 4 files changed, 124 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 5241f82854..8d6ac676f5 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1541,6 +1541,7 @@ class LightningRepo @Inject constructor( private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) val recordsBefore = ldkSendRecords.get() + val inFlightBefore = ldkSendsInFlight.toSet() val payments = listPaymentsKeepingSendHashes() if (payments == null) { val cache = cacheStore.data.first() @@ -1556,8 +1557,9 @@ class LightningRepo @Inject constructor( it.direction == PaymentDirection.OUTBOUND && (kind.bolt11.equals(bolt11, ignoreCase = true) || kind.hash.equals(paymentHash, ignoreCase = true)) } - // A retry in flight, or one recorded while the listing was read, holds the invoice again. - val isRetried = key in ldkSendsInFlight || (ldkSendRecordedAt[key] ?: 0L) > recordsBefore + // A retry in flight, also one that ended while the listing was read, or recorded meanwhile, holds the invoice. + val isRetried = key in ldkSendsInFlight || key in inFlightBefore || + (ldkSendRecordedAt[key] ?: 0L) > recordsBefore if ((send == null || send.status == PaymentStatus.FAILED) && !isRetried) cacheStore.removeLdkSendHash(key) if (send == null) return null val hash = (send.kind as PaymentKind.Bolt11).hash @@ -1599,16 +1601,23 @@ class LightningRepo @Inject constructor( /** The node's payments after keeping its send hashes from them, or null while it can't list them. */ private suspend fun listPaymentsKeepingSendHashes(): List? { + // Read after the records, as a send counts as in flight before it is recorded, so one of the two shows it. val recordsBefore = ldkSendRecords.get() - return listPaymentsOrNull()?.also { keepLdkSendHashes(it, recordsBefore) } + val inFlightBefore = ldkSendsInFlight.toSet() + return listPaymentsOrNull()?.also { keepLdkSendHashes(it, recordsBefore, inFlightBefore) } } /** * Keeps the node's pending and paid sends once, so those made before sends were kept hold Spark too, then trims * the ones listed failed only or paid with an expired invoice. A send that may still be pending always holds Spark: - * one in flight, or recorded after [recordsBefore] while the listing was read, can show an earlier failed attempt. + * one in flight, also one in flight before the listing ([inFlightBefore]) that ended while it was read, or recorded + * after [recordsBefore] meanwhile, can show an earlier failed attempt. */ - private suspend fun keepLdkSendHashes(payments: List, recordsBefore: Long) { + private suspend fun keepLdkSendHashes( + payments: List, + recordsBefore: Long, + inFlightBefore: Set, + ) { val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND } val sends = outbound.filter { it.status != PaymentStatus.FAILED }.sortedBy { it.latestUpdateTimestamp } cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }) @@ -1617,7 +1626,7 @@ class LightningRepo @Inject constructor( .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } } val recordedSince = ldkSendRecordedAt.filterValues { it > recordsBefore }.keys - val live = hashes(PaymentStatus.PENDING) + ldkSendsInFlight + recordedSince + val live = hashes(PaymentStatus.PENDING) + ldkSendsInFlight + inFlightBefore + recordedSince val paid = hashes(PaymentStatus.SUCCEEDED) val failed = hashes(PaymentStatus.FAILED) - paid - live val listed = outbound.mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c4e93c966c..9b399f25a3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -844,15 +844,18 @@ class SparkRepo @Inject constructor( /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ private suspend fun syncActivities(): Boolean { + // Read after the records, as a send counts as in flight before it is recorded, so one of the two shows it. val recordsBefore = sendRecords.get() + val inFlightBefore = sendsInFlight.keys.toSet() val payments = sparkService.listPayments() val isSaved = payments.map { recordActivity(it) }.all { it } val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } - // A send in flight, or recorded after this list was read while the activities were recorded, may be missing - // from it or show only its earlier failed attempt, so it stays. - val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + recordedSince(recordsBefore) + // A send in flight, also one that ended while this list was read, or recorded after it was read while the + // activities were recorded, may be missing from it or show only its earlier failed attempt, so it stays. + val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + inFlightBefore + + recordedSince(recordsBefore) val paid = sendHashes(PaymentStatus.COMPLETED) - live cacheStore.trimSparkSendHashes( paid = paid, @@ -867,10 +870,11 @@ class SparkRepo @Inject constructor( if (failed.isEmpty()) return isSaved // A retry can start while the list is recorded, so the release reads Spark's sends again first. val recordsBeforeCurrent = sendRecords.get() + val inFlightBeforeCurrent = sendsInFlight.keys.toSet() val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return isSaved - val recordedSinceCurrent = recordedSince(recordsBeforeCurrent) + val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) failed - .filter { !sendsInFlight.containsKey(it.lowercase()) && it.lowercase() !in recordedSinceCurrent } + .filter { it.lowercase() !in liveCurrent } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } .forEach { cacheStore.removeSparkSendHash(it) } return isSaved diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 6f23cd93a9..ec93c27861 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1456,6 +1456,36 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(listOf("h"), store.data.first().ldkSendHashes) } + @Test + fun `a node retry in flight when an older listing is read keeps its hash after it ends`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + val sent = CompletableDeferred() + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .doSuspendableAnswer { sent.await() } + val retry = async { sut.payInvoiceWithNode("h") } + runCurrent() + var isEnded = false + // The retry recorded before this listing ends while the listing, which still shows it failed, is read. + whenever(lightningService.listPayments()).doSuspendableAnswer { + if (!isEnded) { + isEnded = true + sent.complete("h") + retry.await() + } + listOf(nodeSend("h", PaymentStatus.FAILED)) + } + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("other")) + + sut.payInvoice("other", 1_000uL) + + assertEquals(listOf("h"), store.data.first().ldkSendHashes, "an older listing dropped a retry that ended") + } + @Test fun `a node retry of the same invoice that ends while an older listing is read keeps its hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 00109c0d96..143eed8f7d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -29,6 +29,7 @@ import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity import com.synonym.bitkitcore.PaymentState import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow @@ -332,6 +333,75 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkSendHashes, "A stale listing dropped a live retry's hash") } + @Test + fun `a retry in flight when the activity sync reads spark's list keeps its hash after it ends`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendHashes = listOf("hash"))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sending = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { + sending.await() + retry + } + var paying: Deferred>? = null + var lists = 0 + // The retry recorded before this list ends while the list, which still shows it failed, is read. + whenever { sparkService.listPayments() }.doSuspendableAnswer { + // The refresh reads the list first, then the activity sync. + val list = paying?.let { ++lists } ?: 0 + if (list == 2) { + sending.complete(Unit) + paying?.await() + } + if (list <= 2) listOf(failed) else listOf(failed, retry) + } + val sut = createSut(store) + paying = backgroundScope.async { sut.payInvoice("lnbc1280n1send", 128uL) } + runCurrent() + + sut.start(0).getOrThrow() + + assertTrue("hash" in store.data.first().sparkSendHashes, "A stale listing dropped a retry that ended") + } + + @Test + fun `a retry in flight when the release reads spark's list again keeps its hash after it ends`() = test { + cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) + whenever { cacheStore.removeSparkSendHash(any()) }.thenAnswer { call -> + cacheData.update { it.copy(sparkSendHashes = it.sparkSendHashes - call.getArgument(0)) } + } + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sending = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { + sending.await() + sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) + } + var paying: Deferred>? = null + var lists = 0 + // The retry ends while the release's second read, which still shows it failed, is read. + whenever { sparkService.listPayments() }.doSuspendableAnswer { + // The refresh and the activity sync read the list first, then the release reads it again. + if (paying != null && ++lists == 3) { + sending.complete(Unit) + paying?.await() + } + listOf(failed) + } + val sut = createSut() + paying = backgroundScope.async { sut.payInvoice("lnbc1280n1send", 128uL) } + runCurrent() + + sut.start(0).getOrThrow() + + assertTrue("hash" in cacheData.value.sparkSendHashes, "The release dropped a retry that ended while it read") + } + @Test fun `a failed send does not release a hash its retry still holds pending`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) From ec59119176fb0f807bdb7cf0832d378e1e418495 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:49:54 +0100 Subject: [PATCH 094/135] fix: keep a send whose invoice never expires held --- app/src/main/java/to/bitkit/data/CacheStore.kt | 4 +++- app/src/test/java/to/bitkit/data/CacheStoreTest.kt | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 0e7becb9b8..dbe0ebd3c0 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -236,7 +236,9 @@ class CacheStore internal constructor( listing: SendListing, ): Pair, Map> { val now = clock.now().epochSeconds - fun isExpired(hash: String, settleSecs: Long = 0) = expiries[hash]?.let { it + settleSecs <= now } == true + + // Compared against now minus the window, as an invoice that never expires is kept at Long.MAX_VALUE. + fun isExpired(hash: String, settleSecs: Long = 0) = expiries[hash]?.let { it <= now - settleSecs } == true fun isSettled(hash: String) = hash !in listing.live && ( hash in listing.failed || hash in listing.paid && isExpired(hash) || diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 7db479fb34..ac07d41885 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -212,6 +212,19 @@ class CacheStoreTest : BaseUnitTest() { assertEquals(listOf("settling", "unknown", "live"), store.data.first().sparkSendHashes) } + @Test + fun `a send whose invoice never expires keeps its hold`() = test { + val store = expiringStore() + store.addSparkSendHash("forever", expiresAt = Long.MAX_VALUE) + store.addLdkSendHash("forever", expiresAt = Long.MAX_VALUE) + + store.trimSparkSendHashes(paid = emptySet(), failed = emptySet(), listed = emptySet(), live = emptySet()) + store.trimLdkSendHashes(paid = emptySet(), failed = emptySet(), listed = emptySet(), live = emptySet()) + + assertEquals(listOf("forever"), store.data.first().sparkSendHashes, "the settle window overflowed") + assertEquals(listOf("forever"), store.data.first().ldkSendHashes, "the settle window overflowed") + } + @Test fun `sends no listing shows with no known expiry are dropped oldest first past the cap`() = test { val unlisted = (0..MAX_SPARK_SEND_HASHES).map { "unlisted$it" } From c4b60bcb3f3ec688079b8d74ddc878359a3a473e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:49:55 +0100 Subject: [PATCH 095/135] docs: say a fixed spark funding's fee is bound too --- .../java/to/bitkit/repositories/OnchainSendAttemptStore.kt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt index 83238e04ba..8f1c55b0ac 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt @@ -190,8 +190,11 @@ class OnchainSendAttemptUnreadableError(cause: Throwable) : AppError("Failed to class OnchainSendNotDispatchedError(cause: Throwable) : AppError("On-chain send did not reach the backend", cause) -/** A send refused before broadcast because it would send another amount, or pay more mining fee, than approved. */ -/** [preparedFeeSats] is the mining fee of the refused prepared send, null when it was unknown. */ +/** + * A send refused before broadcast because it would send another amount, or pay more mining fee, than approved, a + * fixed amount as well as a max one. [preparedFeeSats] is the mining fee of the refused prepared send, null when it + * was unknown. + */ class OnchainSendChangedError(val preparedFeeSats: ULong? = null) : AppError("On-chain send changed after it was approved") From 3006dbaa0443db22e64196a20531235e09f5836b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:49:55 +0100 Subject: [PATCH 096/135] fix: hide only the claimed output of a deposit tx --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 10 +++++++--- .../java/to/bitkit/repositories/SparkRepoTest.kt | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9b399f25a3..6629094d23 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -628,8 +628,9 @@ class SparkRepo @Inject constructor( info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val unclaimed = sparkService.listUnclaimedDeposits() val payments = sparkService.listPayments() - val claimed = payments + val claimedPayments = payments .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } + val claimed = claimedPayments .mapNotNull { payment -> val deposit = payment.details as? PaymentDetails.Deposit ?: return@mapNotNull null SparkDeposit( @@ -641,9 +642,12 @@ class SparkRepo @Inject constructor( ) } // Spark can still list a deposit it already claimed early as unclaimed, so a claimed one is listed only once. - val claimedTxids = claimed.map { it.txid.lowercase() }.toSet() + // Keyed by output, as one transaction can hold several deposits. + val claimedOutputs = claimedPayments.mapNotNullTo(mutableSetOf()) { payment -> + (payment.details as? PaymentDetails.Deposit)?.let { it.txId.lowercase() to it.vout } + } val pending = unclaimed - .filter { it.txid.lowercase() !in claimedTxids } + .filter { (it.txid.lowercase() to it.vout) !in claimedOutputs } .map { SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) } (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } val failedAt = withdrawalFailedAtSecs diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 143eed8f7d..9f6296d9f3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -402,6 +402,20 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in cacheData.value.sparkSendHashes, "The release dropped a retry that ended while it read") } + @Test + fun `a claimed deposit hides only its own output of the transaction`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listUnclaimedDeposits() }.thenReturn( + listOf(0u, 1u).map { DepositInfo("txid", it, 50_000uL, false, null, null, null, null, null, null) } + ) + whenever { sparkService.listPayments() }.thenReturn(listOf(depositPayment())) + val sut = createSut() + + sut.refreshState().getOrThrow() + + assertEquals(50_000uL, sut.state.value.pendingDepositSats, "another output of the claimed tx was hidden") + } + @Test fun `a failed send does not release a hash its retry still holds pending`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) From 8694e2f5edf1d0bd17844c2308544fca31158fea Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:49:55 +0100 Subject: [PATCH 097/135] fix: sync balances when the read spark balance recovers --- .../java/to/bitkit/repositories/WalletRepo.kt | 8 +++++--- .../java/to/bitkit/repositories/WalletRepoTest.kt | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index e45bf2b573..71d527ef98 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -135,9 +135,11 @@ class WalletRepo @Inject constructor( } } repoScope.launch { - sparkRepo.state.map { it.shownBalanceSats to it.pendingDepositSats }.distinctUntilChanged().collect { - if (walletExists()) syncBalances() - } + // The read balance too, as sends use it: it can come back to the shown one while that stays the same. + sparkRepo.state.map { Triple(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) } + .distinctUntilChanged().collect { + if (walletExists()) syncBalances() + } } } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index b95b2f870b..8af155152b 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -35,6 +35,7 @@ import org.lightningdevkit.ldknode.TransactionDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq @@ -261,6 +262,20 @@ class WalletRepoTest : BaseUnitTest() { assertEquals(INVOICE, sut.walletState.value.bolt11) } + @Test + fun `a read spark balance that recovers to the shown one syncs balances`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + val sparkState = MutableStateFlow(SparkState(isReady = true, balanceSats = 0uL, keptBalanceSats = 9_000uL)) + sut = createSut(spark = sparkRepoWith(sparkState)) + testScheduler.runCurrent() + clearInvocations(deriveBalanceStateUseCase) + + sparkState.update { it.copy(balanceSats = 9_000uL, keptBalanceSats = null) } + testScheduler.runCurrent() + + verify(deriveBalanceStateUseCase).invoke() + } + private fun sparkRepoWith(state: MutableStateFlow): SparkRepo = mock { on { this.state } doReturn state on { nodeEvents } doReturn MutableSharedFlow() From bdf3584d88ec80e77e69e49601d8240a378bf228 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 17:05:16 +0100 Subject: [PATCH 098/135] fix: treat spark's below-minimum quote refusal as too small --- .../java/to/bitkit/repositories/SparkRepo.kt | 11 +++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6629094d23..8dec03b20a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -522,7 +522,13 @@ class SparkRepo @Inject constructor( ?.takeIf { it.address == address && it.balanceSats == balanceSats } ?.takeIf { it.response.withdrawalQuote().expiresAt > nowSecs.safe() + QUOTE_EXPIRY_MARGIN_SECS.safe() } ?.let { return it } - val response = sparkService.prepareSend(address, balanceSats, FeePolicy.FEES_INCLUDED) + val response = try { + sparkService.prepareSend(address, balanceSats, FeePolicy.FEES_INCLUDED) + } catch (e: SdkException.InvalidInput) { + // Spark refuses to quote a balance that even its cheapest fee leaves as dust. + if (e.isBelowMinimum()) throw SparkError.WithdrawalTooSmall() + throw e + } return PreparedWithdrawal(address, balanceSats, response).also { preparedWithdrawal = it } } @@ -1233,6 +1239,9 @@ sealed interface SparkClaimStep { } /** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ +internal fun SdkException.InvalidInput.isBelowMinimum(): Boolean = + v1.startsWith("Amount is below the minimum", ignoreCase = true) + internal fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 9f6296d9f3..9f90028dd0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1295,6 +1295,27 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a balance spark refuses to quote as below the minimum is too small to withdraw`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(500uL)) + // What the SDK answers when even its cheapest fee would leave dust. + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { + throw SdkException.InvalidInput( + "Amount is below the minimum of 330 sats required for this address after lowest fees of 1093 sats" + ) + } + val sut = createSut() + + assertIs(sut.estimateWithdrawAllFeeSats(ADDRESS).exceptionOrNull()) + assertIs(sut.withdrawAll(ADDRESS, confirmedFeeSats = 1_093uL).exceptionOrNull()) + + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { + throw SdkException.InvalidInput("Invalid address: bad") + } + assertIs(sut.estimateWithdrawAllFeeSats(ADDRESS).exceptionOrNull()) + } + @Test fun `exit backup waits for spark's first sync`() = test { whenever(sparkService.isConnected).thenReturn(true) From 77d5affd66b888ceea0c6e937c95efa0d1c1db9d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 18:50:26 +0100 Subject: [PATCH 099/135] test: run the amount change journey on the local spark regtest Its deposits and mines now go through bitkit-docker's ./spark on the chain Spark and Savings share, where ./lsp funded Blocktank staging's chain instead. --- .../transfer/spending-confirm-amount-change.xml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/journeys/transfer/spending-confirm-amount-change.xml b/journeys/transfer/spending-confirm-amount-change.xml index 2b570a189c..7b10a63ee8 100644 --- a/journeys/transfer/spending-confirm-amount-change.xml +++ b/journeys/transfer/spending-confirm-amount-change.xml @@ -13,9 +13,16 @@ same fee, or spend the new UTXO alone at a lower fee; either way the fresh price costs no more than the one shown, so the swipe pays at once. - Precondition: a freshly onboarded dev wallet with Spark connected on its regtest, built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), no channel and - exactly two confirmed on-chain UTXOs of 150 000 sats each (two ./lsp deposits to the wallet's - savings address, each followed by a mine). Start on the wallet home screen. + The wallet's UTXOs and Spark's deposit must be on one chain the run can fund and mine, so it runs on + bitkit-docker's local Spark regtest (docs/spark-regtest.md in synonymdev/bitkit-docker), where Savings, the + Spark operators and the SSP share bitkit-docker's chain. Lightspark's hosted regtest can't be mined on demand. + + Precondition: `./spark up` running in bitkit-docker; a dev build connected to it as that doc's "Point a + Bitkit dev build at it" section says (the local Spark config and chain URL, patched in where the build + doesn't read them yet, and the `adb reverse` ports), with Savings on bitkit-docker's Electrum + (`tcp://127.0.0.1:60001`); a freshly onboarded wallet with no channel + and exactly two confirmed on-chain UTXOs of 150 000 sats each (in bitkit-docker, `./spark send + <savings address> 150000` twice, each mining a block). Start on the wallet home screen. Tap Receive (testTag "Receive"), tap the "Savings" receive tab (the tab row carries no test tag), tap "Show Details" (testTag "ShowDetails"), read the address from testTag "ReceiveOnchainAddress", then press back to the home screen @@ -24,7 +31,7 @@ Enter 200 000 on the number pad (testTags "N2", "N0", "N0", "N0", "N0", "N0") and tap "Continue" (testTag "SpendingAmountContinue") Verify the confirm screen is visible (testTag "SpendingConfirmMore") and wait until its network fee is shown Note the amounts under "Network Fees" (testTag "SpendingConfirmNetworkFee") and "Total" (testTag "SpendingConfirmTotal") - Run in one command: ./lsp POST /regtest/chain/deposit '{"address":"<savings addr>","amountSat":500000}' && ./lsp POST /regtest/chain/mine '{"count":1}' + In bitkit-docker, run ./spark send <savings addr> 500000, which pays the address and mines a block Wait 30s for the wallet to sync the new UTXO If the received sheet (testTag "ReceivedTransaction") is visible, tap its button (testTag "ReceivedTransactionButton") Verify the confirm screen still shows the amounts noted before the deposit From 66131bff257b4118a390e5e41c6b923be5fa1571 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:07 +0100 Subject: [PATCH 100/135] fix: admit one rail's send of an invoice at a time --- .../to/bitkit/repositories/LightningRepo.kt | 84 +++++++++++++++---- .../java/to/bitkit/repositories/SparkRepo.kt | 23 ++++- .../bitkit/repositories/LightningRepoTest.kt | 29 ++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 23 +++++ 4 files changed, 140 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 8d6ac676f5..50edaca6a7 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -177,6 +177,9 @@ class LightningRepo @Inject constructor( private val ldkSendRecords = AtomicLong() private val ldkSendRecordedAt = ConcurrentHashMap() + /** The rail holding each invoice's admitted sends and their count, by send key, guarded by itself. */ + private val admittedSends = HashMap>() + @Volatile private var lastKnownNodeId: String? = null @@ -1507,22 +1510,41 @@ class LightningRepo @Inject constructor( val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() if (shouldPayWithSpark(bolt11, sats)) { runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } + val key = ldkSendKey(bolt11, paymentHash) + // Read before the checks, so a node send admitted after them refuses this one at submission. + val ldkRecordsBefore = ldkSendRecords.get() runSuspendCatching { earlierNodeSend(bolt11, paymentHash) } .getOrElse { return Result.failure(it) } ?.let { return it.toResult() } + var isAdmitted = false + var isRefused = false val authorizeSend: suspend () -> Boolean = { - onBeforeSend().also { if (it) requireWalletRestoreComplete() } + val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() } + if (isAuthorized) { + isAdmitted = admitSend(key, LightningRail.Spark) { + (ldkSendRecordedAt[key] ?: 0L) > ldkRecordsBefore + } + isRefused = !isAdmitted + if (isRefused) throw PaymentPendingException(paymentHash ?: key) + } + isAuthorized } // Without a caller's limit Spark keeps to the node's default, so a re-quote cannot raise the fee past it. val maxTotalFeeMsat = maxTotalRoutingFeeMsat ?: invoiceAmountSats(bolt11, sats)?.let { (it.safe() * MSATS_PER_SAT.safe() / DEFAULT_ROUTING_FEE_DIVISOR).safe() + DEFAULT_ROUTING_FEE_BASE_MSAT.safe() } - return sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalFeeMsat, authorizeSend) - .onSuccess { recordSendRail(it, LightningRail.Spark) } - .onFailure { - if (it is PaymentPendingException) recordSendRail(it.paymentHash, LightningRail.Spark) - } + return try { + sparkRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalFeeMsat, authorizeSend) + .onSuccess { recordSendRail(it, LightningRail.Spark) } + .onFailure { + if (it is PaymentPendingException && !isRefused) { + recordSendRail(it.paymentHash, LightningRail.Spark) + } + } + } finally { + if (isAdmitted) releaseSend(key) + } } return payInvoiceWithLdk(bolt11, sats, paymentHash, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) } @@ -1560,7 +1582,10 @@ class LightningRepo @Inject constructor( // A retry in flight, also one that ended while the listing was read, or recorded meanwhile, holds the invoice. val isRetried = key in ldkSendsInFlight || key in inFlightBefore || (ldkSendRecordedAt[key] ?: 0L) > recordsBefore - if ((send == null || send.status == PaymentStatus.FAILED) && !isRetried) cacheStore.removeLdkSendHash(key) + if (send == null || send.status == PaymentStatus.FAILED) { + if (isRetried) return EarlierSend.Pending(key) + cacheStore.removeLdkSendHash(key) + } if (send == null) return null val hash = (send.kind as PaymentKind.Bolt11).hash return when (send.status) { @@ -1586,17 +1611,48 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() waitForUsableChannels() requireWalletRestoreComplete() + // Read before the checks, so a Spark send admitted after them refuses this one at submission. + val sparkRecordsBefore = sparkRepo.sendRecordMark() sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() val key = ldkSendKey(bolt11, paymentHash) - ldkSendsInFlight += key - ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet() - cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) - runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } - .also { ldkSendsInFlight -= key } - .onSuccess { recordSendRail(it, LightningRail.Ldk) } - .also { syncState() } + if (!admitSend(key, LightningRail.Ldk) { sparkRepo.hasRecordedSendSince(sparkRecordsBefore, paymentHash) }) { + Logger.warn("Refused a node send of '$key', Spark sent it meanwhile", context = TAG) + return@executeWhenNodeRunning Result.failure(PaymentPendingException(paymentHash ?: key)) + } + try { + ldkSendsInFlight += key + ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet() + cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) + runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } + .also { ldkSendsInFlight -= key } + .onSuccess { recordSendRail(it, LightningRail.Ldk) } + .also { syncState() } + } finally { + releaseSend(key) + } + } + + /** + * The last check before a send of [key] leaves on [rail], so of two sends of one invoice only the first admitted + * goes out: refused while the other rail holds one, or [isSentOnOtherRail] says it recorded one since the checks. + */ + private fun admitSend(key: String, rail: LightningRail, isSentOnOtherRail: () -> Boolean): Boolean = + synchronized(admittedSends) { + val held = admittedSends[key] + val isFree = (held == null || held.first == rail) && !isSentOnOtherRail() + if (isFree) admittedSends[key] = rail to (held?.second ?: 0) + 1 + isFree + } + + private fun releaseSend(key: String) = synchronized(admittedSends) { + val held = admittedSends[key] + when { + held == null -> Unit + held.second <= 1 -> admittedSends.remove(key) + else -> admittedSends[key] = held.first to held.second - 1 + } } /** The node's payments after keeping its send hashes from them, or null while it can't list them. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8dec03b20a..702722dfd5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -787,9 +787,16 @@ class SparkRepo @Inject constructor( */ suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = withContext(bgDispatcher) { - sendsInFlight.entries - .firstOrNull { it.value.equals(bolt11, ignoreCase = true) || it.key == paymentHash?.lowercase() } - ?.let { return@withContext EarlierSend.Pending(it.key) } + val recordsBefore = sendRecords.get() + val isOfInvoice = { send: Map.Entry -> + send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() + } + sendsInFlight.entries.firstOrNull(isOfInvoice)?.let { return@withContext EarlierSend.Pending(it.key) } + // A retry started, or recorded, while the listing below is read may still be pending. + val retried = { + sendsInFlight.entries.firstOrNull(isOfInvoice)?.key + ?: paymentHash?.lowercase()?.takeIf { it in recordedSince(recordsBefore) } + } // Before Spark's first sync its local list can be empty although a restored send is live. val payments = if (sparkService.isSupported && canListPayments()) { runSuspendCatching { sparkService.listPayments() } @@ -804,7 +811,8 @@ class SparkRepo @Inject constructor( it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - ?: return@withContext null + ?: return@withContext retried()?.let { EarlierSend.Pending(it) } + if (send.status == PaymentStatus.FAILED) retried()?.let { return@withContext EarlierSend.Pending(it) } val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash when (send.status) { PaymentStatus.PENDING -> EarlierSend.Pending(hash) @@ -813,6 +821,13 @@ class SparkRepo @Inject constructor( } } + /** The count of sends recorded so far, read before a node send's checks for [hasRecordedSendSince]. */ + fun sendRecordMark(): Long = sendRecords.get() + + /** Whether a send of [paymentHash] was recorded after [sendRecordMark] read [records]. */ + fun hasRecordedSendSince(records: Long, paymentHash: String?): Boolean = + paymentHash != null && (sendRecordedAt[paymentHash.lowercase()] ?: 0L) > records + private suspend fun startedSend(paymentHash: String?): String? { val hash = paymentHash?.lowercase() ?: return null return hash.takeIf { it in cacheStore.data.first().sparkSendHashes } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index ec93c27861..998138ca80 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -48,6 +48,7 @@ import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentFailureReason +import org.lightningdevkit.ldknode.PaymentId import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus import org.lightningdevkit.ldknode.PeerDetails @@ -1507,9 +1508,35 @@ class LightningRepoTest : BaseUnitTest() { whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success("h")) - sut.payInvoice("h", 1_000uL) + val result = sut.payInvoice("h", 1_000uL) assertEquals(listOf("h"), store.data.first().ldkSendHashes, "an older listing released the node retry's hold") + assertIs(result.exceptionOrNull(), "Spark paid an invoice the node is retrying") + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a node send of an invoice spark admitted is refused at submission`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var nodeResult: Result? = null + // The node starts the same invoice after Spark's checks passed, while Spark is sending it. + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + val authorizeSend = it.getArgument Boolean>(4) + check(authorizeSend()) + nodeResult = sut.payInvoiceWithNode("h") + Result.success("h") + } + + sut.payInvoice("h", 1_000uL) + + assertIs(nodeResult?.exceptionOrNull(), "the node paid an invoice Spark is sending") + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) } private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 9f90028dd0..d2f3df8389 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -202,6 +202,29 @@ class SparkRepoTest : BaseUnitTest() { assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a spark retry recorded while an older list is read holds the node off the invoice`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING)) + val sut = createSut() + sut.start(0).getOrThrow() + var isRetried = false + // Spark retries the invoice the node is about to pay, and its send returns, while this list is read. + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (!isRetried) { + isRetried = true + sut.payInvoice("lnbc1280n1send", 128uL) + } + listOf(failed) + } + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + @Test fun `a readable history without a live attempt lets the node pay a recorded invoice`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) From 8ad1b5f2130d3484e3a7bdb516a4200315c7ceec Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:30 +0100 Subject: [PATCH 101/135] fix: keep an uncertain spark send pending until spark syncs --- .../java/to/bitkit/repositories/SparkRepo.kt | 22 ++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 40 ++++++++++++++++++- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 702722dfd5..038af60150 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -184,7 +184,7 @@ class SparkRepo @Inject constructor( importRestoredExitState(walletIndex) // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. runSuspendCatching { sparkService.syncWallet() } - .onSuccess { _state.update { it.copy(hasSynced = true) } } + .onSuccess { if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } } .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } if (connected) _exitStateGeneration.update { it + 1 } refresh() @@ -337,12 +337,16 @@ class SparkRepo @Inject constructor( withTimeoutOrNull(PENDING_TRACK_WAIT) { pendingPaymentRepo.state.first { paymentHash in it.pendingPayments } } + val failedAt = clock.now().epochSeconds.toULong() repeat(SETTLE_ATTEMPTS) { runSuspendCatching { sparkService.syncWallet() } .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } - .onSuccess { _state.update { it.copy(hasSynced = true) } } + // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still + // returns, so only one that completed after the failure shows the send was never made. + val isSynced = hasSyncedSince(failedAt) + if (isSynced) _state.update { it.copy(hasSynced = true) } when (val send = lightningSend(paymentHash)) { - SparkLightningSend.NotFound -> { + SparkLightningSend.NotFound if isSynced -> { cacheStore.removeSparkSendHash(paymentHash) val reason = PaymentFailureReason.UNEXPECTED_ERROR _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, reason)) @@ -355,13 +359,23 @@ class SparkRepo @Inject constructor( settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } return@launch } - SparkLightningSend.Unavailable -> delay(SETTLE_RETRY_INTERVAL) + SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> delay(SETTLE_RETRY_INTERVAL) } } Logger.warn("Stopped settling Spark send '$paymentHash'", context = TAG) } } + /** Whether Spark's last wallet sync reached it, and started after [seconds] when given. */ + private suspend fun hasSyncedSince(seconds: ULong?): Boolean { + val info = runSuspendCatching { sparkService.getInfo() } + .onFailure { Logger.warn("Failed to read Spark's sync state", it, context = TAG) } + .getOrNull() ?: return false + info.lastSyncError?.let { Logger.warn("Spark's last sync failed: '$it'", context = TAG) } + val syncedAt = info.lastSyncedAt + return info.lastSyncError == null && (seconds == null || syncedAt != null && syncedAt > seconds) + } + private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) { if (paymentDeadlineAt != null && clock.now() > paymentDeadlineAt) throw ServiceError.PaymentDeadlineExpired() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index d2f3df8389..2d990a34ba 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -494,6 +494,8 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any()) }.thenAnswer { throw IllegalStateException("lost") } + // Spark's resync reaches it after the send failed, so a send it doesn't list never went out. + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) val sut = createSut() assertIs(sut.payInvoice("lnbc1280n1send", 128uL).exceptionOrNull()) @@ -1231,6 +1233,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) val sut = createSut() val events = mutableListOf() @@ -1241,7 +1244,7 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() assertEquals("hash", assertIs(error).paymentHash) - // Spark synced and holds no such send, so nothing left and the pending send ends as failed. + // Spark synced after the failure and holds no such send, so nothing left and the pending send ends as failed. assertEquals("hash", assertIs(events.single()).paymentHash) } @@ -1389,6 +1392,41 @@ class SparkRepoTest : BaseUnitTest() { } } + @Test + fun `an uncertain spark send is not failed while its resync never reaches spark`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + // The SDK reports a wallet sync that failed in its info, not by throwing. + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) + ) + val sut = createSut() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "a send Spark may still finish was reported failed") + } + + @Test + fun `a first sync that fails leaves spark's payment list unread`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val sut = createSut() + + sut.start(0).getOrThrow() + + assertFalse(sut.canListPayments(), "a restored wallet's unsynced list was read as complete") + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From 5234dc12a7a8e76601169470db03926b0cabbc62 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:30 +0100 Subject: [PATCH 102/135] fix: hold the node retry while a spark send is uncertain --- .../java/to/bitkit/repositories/SparkRepo.kt | 17 ++++++++++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 038af60150..1e071fca8a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -141,6 +141,9 @@ class SparkRepo @Inject constructor( private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() + /** Sends whose outcome Spark didn't report, by lowercase payment hash, pending until a later sync settles them. */ + private val uncertainSends = ConcurrentHashMap.newKeySet() + @Volatile private var hasSyncedActivities = false @@ -212,6 +215,7 @@ class SparkRepo @Inject constructor( sendsRecordedWithoutFee.clear() unsavedPayments.clear() sendsInFlight.clear() + uncertainSends.clear() hasSyncedActivities = false hasMergedRemoteExitState = false _depositClaims.update { emptyMap() } @@ -332,6 +336,7 @@ class SparkRepo @Inject constructor( } private fun settleUncertainSend(paymentHash: String) { + uncertainSends += paymentHash.lowercase() scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -348,13 +353,18 @@ class SparkRepo @Inject constructor( when (val send = lightningSend(paymentHash)) { SparkLightningSend.NotFound if isSynced -> { cacheStore.removeSparkSendHash(paymentHash) + uncertainSends -= paymentHash.lowercase() val reason = PaymentFailureReason.UNEXPECTED_ERROR _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, reason)) return@launch } // A pending send ends with its own payment event. - is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@launch + is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> { + uncertainSends -= paymentHash.lowercase() + return@launch + } is SparkLightningSend.Found -> { + uncertainSends -= paymentHash.lowercase() if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } return@launch @@ -806,10 +816,11 @@ class SparkRepo @Inject constructor( send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() } sendsInFlight.entries.firstOrNull(isOfInvoice)?.let { return@withContext EarlierSend.Pending(it.key) } - // A retry started, or recorded, while the listing below is read may still be pending. + // A retry started, or recorded, while the listing below is read may still be pending, as may a send whose + // outcome Spark didn't report until a sync settles it. val retried = { sendsInFlight.entries.firstOrNull(isOfInvoice)?.key - ?: paymentHash?.lowercase()?.takeIf { it in recordedSince(recordsBefore) } + ?: paymentHash?.lowercase()?.takeIf { it in recordedSince(recordsBefore) || it in uncertainSends } } // Before Spark's first sync its local list can be empty although a restored send is live. val payments = if (sparkService.isSupported && canListPayments()) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2d990a34ba..2c46735f16 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1427,6 +1427,24 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(sut.canListPayments(), "a restored wallet's unsynced list was read as complete") } + @Test + fun `an uncertain spark send keeps holding the node off while spark can't resync`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + // From here every resync fails, so Spark's list stays as it was before the send. + whenever { sparkService.syncWallet() }.thenAnswer { throw SdkException.Generic("operators unreachable") } + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From d4277a6b0ebf5f503796d22a88106bbd3900bb26 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:31 +0100 Subject: [PATCH 103/135] fix: keep the instant claim follower after a failed early claim --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 5 +++-- .../test/java/to/bitkit/repositories/SparkRepoTest.kt | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1e071fca8a..cebee5c94c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -496,10 +496,11 @@ class SparkRepo @Inject constructor( earlyClaimVouts[offer.txid] = offer.vout runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats) } .map { SparkEarlyClaim.from(it) } - .recover { if (it is SdkException.DepositClaimInProgress) SparkEarlyClaim.Claimed else throw it } + .recoverCatching { if (it is SdkException.DepositClaimInProgress) SparkEarlyClaim.Claimed else throw it } .onSuccess { Logger.info("Early claim of Spark deposit '${offer.txid}': '$it'", context = TAG) - refresh() + runSuspendCatching { refresh() } + .onFailure { Logger.warn("Failed to refresh Spark state", it, context = TAG) } } .onFailure { Logger.error("Failed to claim Spark deposit '${offer.txid}' early", it, context = TAG) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2c46735f16..656dff5115 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1445,6 +1445,17 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a failed early claim is a failure the claim follower keeps going on`() = test { + whenever { sparkService.claimDeposit("txid", 0u, 300uL) } + .thenAnswer { throw SdkException.Generic("operators unreachable") } + val choice = SparkClaimOffer.Choice("txid", 0u, earlyFeeSats = 300uL, 0u, 198uL, 3u) + + val result = runCatching { createSut().claimEarly(choice) } + + assertTrue(result.getOrThrow().isFailure, "a failed early claim threw instead of failing") + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From cc8e1c10f8a245e2ba174fd785f2406fff0d2283 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:31 +0100 Subject: [PATCH 104/135] fix: drop the spark send hash when its deadline can't be set --- .../java/to/bitkit/repositories/SparkRepo.kt | 5 +++++ .../to/bitkit/repositories/SparkRepoTest.kt | 22 ++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index cebee5c94c..f6b7054d84 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -308,6 +308,11 @@ class SparkRepo @Inject constructor( val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) + // The checks above and saving the hash suspend, so the deadline is checked last, before the send. + runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { + cacheStore.removeSparkSendHash(paymentHash) + throw it + } runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 656dff5115..902a728689 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -80,6 +80,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import com.synonym.bitkitcore.PaymentType as ActivityPaymentType @@ -96,7 +97,7 @@ class SparkRepoTest : BaseUnitTest() { private val cacheStore = mock { on { data } doReturn cacheData } private val contactResolver = mock() private val pendingPaymentRepo = PendingPaymentRepo() - private val now = Instant.fromEpochSeconds(1_800_000_000) + private var now = Instant.fromEpochSeconds(1_800_000_000) private val clock = object : Clock { override fun now() = this@SparkRepoTest.now } @@ -1456,6 +1457,25 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(result.getOrThrow().isFailure, "a failed early claim threw instead of failing") } + @Test + fun `a spark send whose deadline passes before it goes out is not sent`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val deadline = now + 1.seconds + val sut = createSut() + + // The caller's last check before the send can wait past the deadline, as Paykit's does on its lock. + val result = sut.payInvoice("lnbc1", 100uL, deadline, null) { + now = deadline + 1.seconds + true + } + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From 413ec0ae2569006be05238098ae265b9efa71b3c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:31 +0100 Subject: [PATCH 105/135] docs: move the expired-invoice comment onto its check --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f6b7054d84..8239c35b74 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1284,10 +1284,10 @@ sealed interface SparkClaimStep { } } -/** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ internal fun SdkException.InvalidInput.isBelowMinimum(): Boolean = v1.startsWith("Amount is below the minimum", ignoreCase = true) +/** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ internal fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) From c383c69aba02a317ce4795b28b5bd7803a96789c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:32 +0100 Subject: [PATCH 106/135] fix: resolve a re-paid invoice the node already paid --- .../to/bitkit/repositories/LightningRepo.kt | 25 ++++++++++++++++--- .../bitkit/repositories/LightningRepoTest.kt | 13 ++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 50edaca6a7..75f83eccc9 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1515,7 +1515,11 @@ class LightningRepo @Inject constructor( val ldkRecordsBefore = ldkSendRecords.get() runSuspendCatching { earlierNodeSend(bolt11, paymentHash) } .getOrElse { return Result.failure(it) } - ?.let { return it.toResult() } + ?.let { + // The node paid it, so its caller settles from the node's payment, as its event already fired. + if (it is EarlierSend.Paid) recordSendRail(it.paymentHash, LightningRail.Ldk) + return it.toResult() + } var isAdmitted = false var isRefused = false val authorizeSend: suspend () -> Boolean = { @@ -2599,9 +2603,24 @@ class LightningRepo @Inject constructor( if (state.nodeLifecycleState.isRunning()) state.channels else it } - /** The completion event of a Spark send that settled before its caller started watching for it. */ + /** + * The completion event of a send that settled before its caller started watching for it, read from the rail it + * last went out on: a node send only when it succeeded, as one the node paid earlier gets no new event. + */ suspend fun settledSparkSendEvent(paymentHash: String): Event? = - if (isLdkSend(paymentHash)) null else sparkRepo.settledSendEvent(paymentHash) + if (isLdkSend(paymentHash)) paidNodeSendEvent(paymentHash) else sparkRepo.settledSendEvent(paymentHash) + + private suspend fun paidNodeSendEvent(paymentHash: String): Event? { + val payments = runSuspendCatching { lightningService.listPayments() } + .onFailure { Logger.warn("Failed to list node payments", it, context = TAG) } + .getOrNull() + val payment = payments?.firstOrNull { + it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.SUCCEEDED && + (it.kind as? PaymentKind.Bolt11)?.hash.equals(paymentHash, ignoreCase = true) + } ?: return null + val kind = payment.kind as PaymentKind.Bolt11 + return Event.PaymentSuccessful(payment.id, kind.hash, kind.preimage, payment.feePaidMsat) + } /** Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. */ suspend fun sparkLightningSend(paymentHash: String): SparkLightningSend = sparkRepo.lightningSend(paymentHash) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 998138ca80..c1a964a7af 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1539,6 +1539,19 @@ class LightningRepoTest : BaseUnitTest() { verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + @Test + fun `a spark send of an invoice the node already paid settles as paid`() = test { + startNodeForTesting() + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.SUCCEEDED))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + + // The node's own success event fired before this send, so its caller reads the settled payment instead. + assertEquals("h", assertIs(sut.settledSparkSendEvent("h")).paymentHash) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( id = hash, kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), From b87908e232e8fe9703d3ac1a4873163933129bd1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:32 +0100 Subject: [PATCH 107/135] fix: skip node failure events for a spark send --- .../to/bitkit/repositories/LightningRepo.kt | 5 +++++ .../bitkit/repositories/LightningRepoTest.kt | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 75f83eccc9..31c2aa7313 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -581,6 +581,11 @@ class LightningRepo @Inject constructor( } private suspend fun onEvent(event: Event) { + // An earlier channel attempt's failure never fails a retry Spark is paying. + if (event is Event.PaymentFailed && event.paymentHash?.let { isSparkSend(it) } == true) { + Logger.info("Skipped node failure of '${event.paymentHash}', its retry went over Spark", context = TAG) + return + } val observedTxid = when (event) { is Event.OnchainTransactionReceived -> event.txid is Event.OnchainTransactionConfirmed -> event.txid diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index c1a964a7af..09d081321a 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1552,6 +1552,25 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } + @Test + fun `a late channel failure never fails a spark retry of the invoice`() = test { + val onEvent = startNodeAndCaptureEvents() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.failure(PaymentPendingException("hash"))) + sut.payInvoice("bolt11", 1_000uL) + assertTrue(sut.isSparkSend("hash")) + + // The node's earlier attempt fails only after the retry went out on Spark. + onEvent(Event.PaymentFailed("hash", "hash", PaymentFailureReason.UNEXPECTED_ERROR)) + runCurrent() + + assertTrue(events.none { it is Event.PaymentFailed }) + } + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( id = hash, kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), From 25e4dd91bb46bba6b21bd8a92d65a6edd0cdc4a1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:33 +0100 Subject: [PATCH 108/135] fix: clear the cached spark withdrawal address on a new transfer --- .../to/bitkit/viewmodels/TransferViewModel.kt | 6 +++++- .../viewmodels/TransferViewModelTest.kt | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 83816dbc78..233dabf5e2 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -309,7 +309,11 @@ class TransferViewModel @Inject constructor( } /** Opens Transfer to Savings with nothing left from an earlier visit that ended before the swipe. */ - fun beginSavingsTransfer() = setSavingsSelection(SavingsSelection()) + fun beginSavingsTransfer() { + // A wallet wipe keeps this view model, so an address kept from before may belong to the wiped wallet. + sparkAddress = null + setSavingsSelection(SavingsSelection()) + } fun setSavingsSelection(selection: SavingsSelection) { _savingsSelection.update { selection } diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 7b8f01ea45..83cf938e93 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -21,6 +21,7 @@ import org.lightningdevkit.ldknode.PaymentFailureReason import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -390,6 +391,24 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(expectedMax - expectedSwapFee - SWAP_MINER_FEE, quote.receiveSat) } + @Test + fun `a new transfer to savings withdraws spark to a fresh address`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + // The wallet is wiped and another restored in the same process, so the first address is no longer its own. + whenever { lightningRepo.newAddress() }.thenReturn(Result.success("bcrt1qrestored")) + + sut.beginSavingsTransfer() + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + sut.closeSelectedChannels() + + verify(sparkRepo).withdrawAll(eq("bcrt1qrestored"), any()) + verify(sparkRepo, never()).withdrawAll(eq(CLAIM_ADDRESS), any()) + } + @Test fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) From 4f437dd71a9e8a27412db2a3425d0f8b8a1a102a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:33 +0100 Subject: [PATCH 109/135] fix: re-quote the spark withdrawal fee on a new transfer --- .../java/to/bitkit/viewmodels/TransferViewModel.kt | 4 ++++ .../to/bitkit/viewmodels/TransferViewModelTest.kt | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 233dabf5e2..bfc618fc81 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -312,6 +312,10 @@ class TransferViewModel @Inject constructor( fun beginSavingsTransfer() { // A wallet wipe keeps this view model, so an address kept from before may belong to the wiped wallet. sparkAddress = null + // Spark's withdrawal fee moves, so each transfer prices it again. + sparkFeeJob?.cancel() + sparkFeeBalanceSats = null + _sparkWithdrawFeeSats.update { null } setSavingsSelection(SavingsSelection()) } diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 83cf938e93..f6b720f8b8 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -409,6 +409,19 @@ class TransferViewModelTest : BaseUnitTest() { verify(sparkRepo, never()).withdrawAll(eq(CLAIM_ADDRESS), any()) } + @Test + fun `a new transfer to savings prices spark's withdrawal again`() = test { + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + whenever(sparkRepo.estimateWithdrawAllFeeSats(CLAIM_ADDRESS)).thenReturn(Result.success(SPARK_FEE + 200uL)) + + sut.beginSavingsTransfer() + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + + assertEquals(SPARK_FEE + 200uL, sut.sparkWithdrawFeeSats.value) + } + @Test fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) From 3392b9ea1972e1eb79832de0feca97d93f350e3c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:34 +0100 Subject: [PATCH 110/135] fix: clear the spark withdrawal fee after a refusal --- .../to/bitkit/viewmodels/TransferViewModel.kt | 6 +++++- .../bitkit/viewmodels/TransferViewModelTest.kt | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index bfc618fc81..599ec06a83 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -447,7 +447,11 @@ class TransferViewModel @Inject constructor( sparkAddress = null sparkFeeBalanceSats = null } - .onFailure { _isSparkWithdrawFailed.update { true } } + .onFailure { + // A refused fee is quoted again, so the next visit doesn't show it and fail the same way. + sparkFeeBalanceSats = null + _isSparkWithdrawFailed.update { true } + } } private suspend fun closeChannels(channels: List): List { diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index f6b720f8b8..a2c4152eb1 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -422,6 +422,22 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(SPARK_FEE + 200uL, sut.sparkWithdrawFeeSats.value) } + @Test + fun `a spark withdrawal refused for its fee is priced again`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + whenever { sparkRepo.withdrawAll(any(), any()) }.thenReturn(Result.failure(SparkError.WithdrawalFeeChanged())) + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + sut.closeSelectedChannels() + whenever(sparkRepo.estimateWithdrawAllFeeSats(CLAIM_ADDRESS)).thenReturn(Result.success(SPARK_FEE + 200uL)) + + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + + assertEquals(SPARK_FEE + 200uL, sut.sparkWithdrawFeeSats.value) + } + @Test fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) From 9b245b08ba9628a168de6678e04630f048a9ce15 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:34 +0100 Subject: [PATCH 111/135] fix: finish channel closes after leaving the withdrawal progress --- .../to/bitkit/viewmodels/TransferViewModel.kt | 15 +++++++++++--- .../viewmodels/TransferViewModelTest.kt | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 599ec06a83..328a2ced64 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -11,6 +11,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableSet import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll @@ -82,6 +83,7 @@ class TransferViewModel @Inject constructor( private var sparkFeeJob: Job? = null private var confirmedSparkFeeSats: ULong? = null private var sparkWithdrawJob: Job? = null + private var closeJob: Deferred>? = null private var sparkFeeBalanceSats: ULong? = null private var sparkAddress: String? = null @@ -404,6 +406,7 @@ class TransferViewModel @Inject constructor( _savingsSwapResult.update { null } _isSparkWithdrawFailed.update { false } sparkWithdrawJob = null + closeJob = null _savingsSelection.update { SavingsSelection() } channelsToClose = channels withdrawsSpark = withdrawSpark @@ -420,10 +423,16 @@ class TransferViewModel @Inject constructor( /** Whether Transfer to Savings closes channels, rather than only withdrawing Spark's balance. */ fun hasChannelsToClose(): Boolean = channelsToClose.isNotEmpty() - /** Withdraws Spark's balance when selected, then closes the channels selected earlier, pending closure */ + /** + * Withdraws Spark's balance when selected, then closes the channels selected earlier, pending closure. Once per + * confirmed transfer, in viewModelScope, so leaving the progress screen during the withdrawal skips no close. + */ suspend fun closeSelectedChannels(): List { - if (withdrawsSpark) withdrawSparkToSavings() - return closeChannels(channelsToClose) + val job = closeJob ?: viewModelScope.async { + if (withdrawsSpark) withdrawSparkToSavings() + closeChannels(channelsToClose) + }.also { closeJob = it } + return job.await() } private suspend fun withdrawSparkToSavings() { diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index a2c4152eb1..3acbc427c9 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -6,10 +6,12 @@ import com.synonym.bitkitcore.BoltzPairInfo import com.synonym.bitkitcore.BoltzSwapEvent import com.synonym.bitkitcore.ReverseSwapResponse import kotlinx.collections.immutable.persistentSetOf +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -438,6 +440,24 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(SPARK_FEE + 200uL, sut.sparkWithdrawFeeSats.value) } + @Test + fun `leaving progress during spark's withdrawal still closes the selected channels`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + val withdrawn = CompletableDeferred>() + whenever { sparkRepo.withdrawAll(any(), any()) }.doSuspendableAnswer { withdrawn.await() } + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = true) + val progress = launch { sut.closeSelectedChannels() } + runCurrent() + + progress.cancel() + withdrawn.complete(Result.success(Unit)) + advanceUntilIdle() + + verify(lightningRepo).closeChannel(CHANNEL_A, false, null) + } + @Test fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) From 12e3b6188f29b287c22dbaf2479d1fbd12b6607d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:35 +0100 Subject: [PATCH 112/135] fix: show the recovery for a spark funding with an unknown outcome --- .../screens/transfer/SparkFundingViewModel.kt | 3 ++ .../transfer/SparkFundingViewModelTest.kt | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+) 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 218a8e1bfd..dfe04cbc37 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 @@ -38,6 +38,7 @@ import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.OnchainSendBlockedError import to.bitkit.repositories.OnchainSendChangedError import to.bitkit.repositories.OnchainSendOutcome +import to.bitkit.repositories.OnchainSendPendingError import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim import to.bitkit.repositories.SparkRepo @@ -343,6 +344,8 @@ class SparkFundingViewModel @Inject constructor( return@onFailure } Logger.error("Failed to fund Spark", it, context = TAG) + // Its dispatch started but its outcome is unknown, so it may already be on the network. + if (it is OnchainSendPendingError && showRetainedFunding(quote, isThisSwipes = true)) return@onFailure if (it is OnchainSendBlockedError && showRetainedFunding(quote, isThisSwipes = false)) return@onFailure toast( title = R.string.lightning__close_error, 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 aa38406839..e1b4c8aa32 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 @@ -40,6 +40,7 @@ import to.bitkit.repositories.OnchainSendChangedError import to.bitkit.repositories.OnchainSendEvidence import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.OnchainSendOutcome +import to.bitkit.repositories.OnchainSendPendingError import to.bitkit.repositories.SparkClaimSpeed import to.bitkit.repositories.SparkDepositClaim import to.bitkit.repositories.SparkRepo @@ -465,6 +466,38 @@ class SparkFundingViewModelTest : BaseUnitTest() { verify(lightningRepo).followFundingOnScreen("attempt", false) } + @Test + fun `a funding whose outcome is unknown opens its recovery instead of an error`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + }.thenReturn(Result.failure(OnchainSendPendingError(IllegalStateException("timeout"), "txid"))) + val retained = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "attempt", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(retained) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + val effects = mutableListOf() + backgroundScope.launch { sut.effects.collect { effects += it } } + + val toasts = collectToasts { sut.onConfirm() } + + assertTrue(toasts.isEmpty()) + assertEquals(SideEffect.FundingPending(retained), effects.last()) + } + @Test fun `hardware transfer prices from the device and hands signing a transfer request`() = test { whenever { hwWalletRepo.maxSpendableFunding("trezor", "bcrt1qspark", 5uL) }.thenReturn(Result.success(80_000uL)) From 2c12444984893bfa9e0b4f2b3bbc03db876229b1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:35 +0100 Subject: [PATCH 113/135] fix: follow a kept funding that completes off the confirm screen --- .../screens/transfer/SparkFundingViewModel.kt | 5 ++ .../transfer/SparkFundingViewModelTest.kt | 47 +++++++++++++++++++ 2 files changed, 52 insertions(+) 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 dfe04cbc37..d63ee522cf 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 @@ -230,6 +230,11 @@ class SparkFundingViewModel @Inject constructor( /** Prices again at swipe time, and asks for another swipe when the transfer got worse since it was shown. */ fun onConfirm() { val shown = _uiState.value + // A kept funding that completed while another screen showed missed its Sent, so it leaves now instead. + if (shown.txid != null) { + viewModelScope.launch { _effects.emit(SideEffect.Sent) } + return + } val shownQuote = shown.quote ?: return if (shown.isSending || shown.isQuoting) return quoteJob?.cancel() 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 e1b4c8aa32..00b2ea8e27 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 @@ -21,6 +21,7 @@ import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R @@ -498,6 +499,52 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals(SideEffect.FundingPending(retained), effects.last()) } + @Test + fun `a kept funding that completed off the confirm screen is not sent again`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) + val retained = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "attempt", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(retained) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + sut.onConfirm() + advanceUntilIdle() + // Its Sent effect lands while the Amount screen, which ignores it, is showing. + val confirmed = retained.copy(evidence = OnchainSendEvidence.Observed, localFollowupComplete = true) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(confirmed) + attemptUpdates.value++ + advanceUntilIdle() + val effects = mutableListOf() + backgroundScope.launch { sut.effects.collect { effects += it } } + + sut.onConfirm() + advanceUntilIdle() + + verify(lightningRepo, times(1)).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + assertEquals(SideEffect.Sent, effects.lastOrNull()) + } + @Test fun `hardware transfer prices from the device and hands signing a transfer request`() = test { whenever { hwWalletRepo.maxSpendableFunding("trezor", "bcrt1qspark", 5uL) }.thenReturn(Result.success(80_000uL)) From 2ac83dbff7f91dd649a41321fd19765a576695d6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:36 +0100 Subject: [PATCH 114/135] fix: fail quickpay on a spark refusal --- .../main/java/to/bitkit/repositories/QuickPayRepo.kt | 5 +++++ .../java/to/bitkit/repositories/QuickPayRepoTest.kt | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 0e0e6c61fb..2ef0fc5c7a 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -37,6 +37,7 @@ import to.bitkit.models.QuickPayRecordPhase import to.bitkit.models.USD import to.bitkit.models.msatFloorOf import to.bitkit.models.safe +import to.bitkit.services.SparkError import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.asNodeException @@ -844,6 +845,10 @@ internal data class SpendSnapshot( ) internal fun classifyDispatchError(error: Throwable): QuickPayDispatchClass { + // Spark refuses only before anything leaves the wallet, as PaykitPaymentProofRepo reads it. + if (generateSequence(error) { it.cause }.any { it is SparkError.SendRefused }) { + return QuickPayDispatchClass.PRE_DISPATCH_REJECTION + } return when (error.asNodeException()) { is NodeException.InvalidInvoice, is NodeException.InvalidAmount, diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 5a49472076..13783ec022 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -40,6 +40,7 @@ import to.bitkit.models.QuickPayLedger import to.bitkit.models.QuickPayLedgerRecord import to.bitkit.models.QuickPayRecordPhase import to.bitkit.models.USD +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.AppError @@ -585,6 +586,15 @@ class QuickPayRepoTest : BaseUnitTest() { assertTrue("new" in hashes) } + @Test + fun `a spark refusal is a rejection before dispatch`() { + assertEquals( + QuickPayDispatchClass.PRE_DISPATCH_REJECTION, + classifyDispatchError(SparkError.SendRefused("Spark balance can't cover the payment")), + ) + assertEquals(QuickPayDispatchClass.PRE_DISPATCH_REJECTION, classifyDispatchError(SparkError.InvoiceExpired())) + } + @Test fun `classifies wrapped and unwrapped ldk errors`() { assertEquals( From 4ae1618df5c33d0dbf731bcbcbf8f0e698f49b99 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:13:36 +0100 Subject: [PATCH 115/135] fix: keep the transfer flag on a restored spark funding --- .../bitkit/models/ActiveOnchainAttemptBackup.kt | 5 ++++- .../models/ActiveOnchainAttemptBackupTest.kt | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/models/ActiveOnchainAttemptBackup.kt b/app/src/main/java/to/bitkit/models/ActiveOnchainAttemptBackup.kt index 059e28b267..c319e33353 100644 --- a/app/src/main/java/to/bitkit/models/ActiveOnchainAttemptBackup.kt +++ b/app/src/main/java/to/bitkit/models/ActiveOnchainAttemptBackup.kt @@ -33,6 +33,8 @@ data class ActiveOnchainAttemptBackup( val candidateMiningFees: Map? = null, val followup: Followup? = null, val transfer: Transfer? = null, + // A transfer to Spark's deposit address pays no order, so only this keeps it a transfer through a restore. + val sparkFunding: Boolean? = null, ) { @Serializable data class Wallet(val kind: String = "software", val network: String, val binding: String, val sourceIndex: String) @@ -128,7 +130,7 @@ data class ActiveOnchainAttemptBackup( walletId = walletId, walletIndex = destinationIndex, attemptId = attemptId, requestId = requestId, orderId = orderId, payerIdentity = payerIdentity, address = address, amountSats = unsigned(amountSats), isMaxAmount = isMaxAmount, - feeRateSatsPerVByte = unsigned(feeRateSatsPerVByte), isTransfer = orderId != null, + feeRateSatsPerVByte = unsigned(feeRateSatsPerVByte), isTransfer = orderId != null || sparkFunding == true, channelId = followup.channelId, tags = followup.tags, evidence = evidence, txid = txid, refusalReason = rejectionReason, localFollowupComplete = false, originalInputs = inputs, candidateTxids = candidateTxids, candidateFeeRates = restoredFeeRates, @@ -191,6 +193,7 @@ data class ActiveOnchainAttemptBackup( requireNotNull(it.originalOrderFeeSats).toString(), ) }, + sparkFunding = true.takeIf { attempt.isSparkFunding }, ) wire.restored(network, binding, attempt.walletId, attempt.walletIndex) return wire diff --git a/app/src/test/java/to/bitkit/models/ActiveOnchainAttemptBackupTest.kt b/app/src/test/java/to/bitkit/models/ActiveOnchainAttemptBackupTest.kt index aa97eddbbe..f5c677536f 100644 --- a/app/src/test/java/to/bitkit/models/ActiveOnchainAttemptBackupTest.kt +++ b/app/src/test/java/to/bitkit/models/ActiveOnchainAttemptBackupTest.kt @@ -1,5 +1,6 @@ package to.bitkit.models +import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.junit.Test @@ -10,6 +11,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue private val lenientJson = Json { ignoreUnknownKeys = true } @@ -141,6 +143,20 @@ class ActiveOnchainAttemptBackupTest : BaseUnitTest() { assertEquals(wire.copy(amountSats = "1000"), ActiveOnchainAttemptBackup.from(restored, "regtest", binding)) } + @Test + fun `a spark funding keeps its transfer flag through a backup`() { + val wire = requireNotNull(golden().paykitPaymentState?.activeOnchainAttempt) + .copy(requestId = null, payerIdentity = null, status = "pending") + val funding = wire.restored("regtest", binding, "wallet0", 0).copy(isTransfer = true) + assertTrue(funding.isSparkFunding) + + val backup = json.decodeFromString( + json.encodeToString(ActiveOnchainAttemptBackup.from(funding, "regtest", binding)) + ) + + assertTrue(backup.restored("regtest", binding, "wallet0", 0).isSparkFunding, "a restored funding lost its flag") + } + @Test fun `send-all funding backup retains actual recipient amount and original order terms`() { val wire = requireNotNull(golden().paykitPaymentState?.activeOnchainAttempt).copy( From c11e5ca9ce4d239b948d13a3607758538681737a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:23:41 +0100 Subject: [PATCH 116/135] fix: keep an uncertain spark send pending past an older failed row --- .../java/to/bitkit/repositories/SparkRepo.kt | 5 ++-- .../to/bitkit/repositories/SparkRepoTest.kt | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8239c35b74..ec751d880d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -368,13 +368,14 @@ class SparkRepo @Inject constructor( uncertainSends -= paymentHash.lowercase() return@launch } - is SparkLightningSend.Found -> { + // A failed row may be an earlier attempt's, so it is final only after a sync since the failure. + is SparkLightningSend.Found if send.status != PaymentStatus.FAILED || isSynced -> { uncertainSends -= paymentHash.lowercase() if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } return@launch } - SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> delay(SETTLE_RETRY_INTERVAL) + else -> delay(SETTLE_RETRY_INTERVAL) } } Logger.warn("Stopped settling Spark send '$paymentHash'", context = TAG) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 902a728689..8521997a09 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1476,6 +1476,32 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `an older failed row never ends an uncertain spark send while spark can't resync`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + // An earlier attempt of the invoice failed, and from here every wallet sync fails without throwing. + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) + ) + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From 990d76dfeb4b30c0d46f07a5c6d04ba7cd1ac5cd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:23:42 +0100 Subject: [PATCH 117/135] fix: settle an uncertain spark send on spark's next sync --- .../java/to/bitkit/repositories/SparkRepo.kt | 78 +++++++++++-------- .../to/bitkit/repositories/SparkRepoTest.kt | 51 ++++++++++++ 2 files changed, 98 insertions(+), 31 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ec751d880d..f4f023ebeb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -142,7 +142,8 @@ class SparkRepo @Inject constructor( private val sendRecordedAt = ConcurrentHashMap() /** Sends whose outcome Spark didn't report, by lowercase payment hash, pending until a later sync settles them. */ - private val uncertainSends = ConcurrentHashMap.newKeySet() + /** Sends whose outcome Spark didn't report, by payment hash, with when they failed in epoch seconds. */ + private val uncertainSends = ConcurrentHashMap() @Volatile private var hasSyncedActivities = false @@ -341,45 +342,54 @@ class SparkRepo @Inject constructor( } private fun settleUncertainSend(paymentHash: String) { - uncertainSends += paymentHash.lowercase() + uncertainSends[paymentHash.lowercase()] = clock.now().epochSeconds.toULong() scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { pendingPaymentRepo.state.first { paymentHash in it.pendingPayments } } - val failedAt = clock.now().epochSeconds.toULong() repeat(SETTLE_ATTEMPTS) { runSuspendCatching { sparkService.syncWallet() } .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } - // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still - // returns, so only one that completed after the failure shows the send was never made. - val isSynced = hasSyncedSince(failedAt) - if (isSynced) _state.update { it.copy(hasSynced = true) } - when (val send = lightningSend(paymentHash)) { - SparkLightningSend.NotFound if isSynced -> { - cacheStore.removeSparkSendHash(paymentHash) - uncertainSends -= paymentHash.lowercase() - val reason = PaymentFailureReason.UNEXPECTED_ERROR - _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, reason)) - return@launch - } - // A pending send ends with its own payment event. - is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> { - uncertainSends -= paymentHash.lowercase() - return@launch - } - // A failed row may be an earlier attempt's, so it is final only after a sync since the failure. - is SparkLightningSend.Found if send.status != PaymentStatus.FAILED || isSynced -> { - uncertainSends -= paymentHash.lowercase() - if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) - settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } - return@launch - } - else -> delay(SETTLE_RETRY_INTERVAL) - } + if (trySettleUncertainSend(paymentHash)) return@launch + delay(SETTLE_RETRY_INTERVAL) + } + // Spark's next sync settles it, as a send it resumes then ends with its own payment event. + Logger.warn("Stopped polling Spark send '$paymentHash' until Spark syncs again", context = TAG) + } + } + + /** Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. */ + private suspend fun trySettleUncertainSend(paymentHash: String): Boolean { + val key = paymentHash.lowercase() + val failedAt = uncertainSends[key] ?: return true + // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns, + // so only one that completed after the failure shows the send was never made. + val isSynced = hasSyncedSince(failedAt) + if (isSynced) _state.update { it.copy(hasSynced = true) } + val send = lightningSend(paymentHash) + val isSettled = when (send) { + SparkLightningSend.NotFound -> isSynced + // A failed row may be an earlier attempt's, so it is final only after a sync since the failure. + is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isSynced + SparkLightningSend.Unavailable -> false + } + // Only the caller that takes the hash off settles it, so its outcome is reported once. + if (!isSettled || !uncertainSends.remove(key, failedAt)) return isSettled + when (send) { + SparkLightningSend.NotFound -> { + cacheStore.removeSparkSendHash(paymentHash) + _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR)) } - Logger.warn("Stopped settling Spark send '$paymentHash'", context = TAG) + // A pending send ends with its own payment event. + is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit + is SparkLightningSend.Found -> { + if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) + settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + } + SparkLightningSend.Unavailable -> Unit } + return true } /** Whether Spark's last wallet sync reached it, and started after [seconds] when given. */ @@ -827,7 +837,9 @@ class SparkRepo @Inject constructor( // outcome Spark didn't report until a sync settles it. val retried = { sendsInFlight.entries.firstOrNull(isOfInvoice)?.key - ?: paymentHash?.lowercase()?.takeIf { it in recordedSince(recordsBefore) || it in uncertainSends } + ?: paymentHash?.lowercase()?.takeIf { + it in recordedSince(recordsBefore) || uncertainSends.containsKey(it) + } } // Before Spark's first sync its local list can be empty although a restored send is live. val payments = if (sparkService.isSupported && canListPayments()) { @@ -950,6 +962,8 @@ class SparkRepo @Inject constructor( is SdkEvent.Synced -> { _state.update { it.copy(hasSynced = true) } refresh() + // A send whose outcome stayed unknown past its polling settles on a later sync. + uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } } is SdkEvent.PaymentSucceeded -> onPayment(event.payment) is SdkEvent.PaymentFailed -> onPayment(event.payment) @@ -973,6 +987,8 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. + payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) } payment.sendHash(PaymentStatus.FAILED)?.let { hash -> val latest = lightningSend(hash) val isReleased = latest == SparkLightningSend.NotFound || diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8521997a09..0a26ca3c2a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1502,6 +1502,57 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `an uncertain spark send is settled when spark syncs after its polling stopped`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + // Back online after every poll gave up, Spark syncs and holds no such send. + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a spark send that fails after its polling stopped no longer holds the node off`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + // Spark resumes the send later and it fails. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertNull(sut.earlierLightningSend("lnbc1", "hash"), "a failed send still held the node's retry") + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From cc942e70aed7ddea07c857996cef88abd16fe4dd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:23:42 +0100 Subject: [PATCH 118/135] fix: record the spark rail when its send is admitted --- .../to/bitkit/repositories/LightningRepo.kt | 7 +++++++ .../bitkit/repositories/LightningRepoTest.kt | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 31c2aa7313..f02974aa2f 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1527,6 +1527,7 @@ class LightningRepo @Inject constructor( } var isAdmitted = false var isRefused = false + var railBefore: LightningRail? = null val authorizeSend: suspend () -> Boolean = { val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() } if (isAuthorized) { @@ -1535,6 +1536,9 @@ class LightningRepo @Inject constructor( } isRefused = !isAdmitted if (isRefused) throw PaymentPendingException(paymentHash ?: key) + // Recorded at admission, so a node failure arriving while Spark sends reads as an older attempt's. + railBefore = sendRails[key] + recordSendRail(key, LightningRail.Spark) } isAuthorized } @@ -1549,6 +1553,9 @@ class LightningRepo @Inject constructor( .onFailure { if (it is PaymentPendingException && !isRefused) { recordSendRail(it.paymentHash, LightningRail.Spark) + } else if (isAdmitted) { + // Spark sent nothing, so the node's attempt stays the latest. + railBefore?.let { rail -> recordSendRail(key, rail) } ?: sendRails.remove(key) } } } finally { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 09d081321a..f1d2689884 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1571,6 +1571,26 @@ class LightningRepoTest : BaseUnitTest() { assertTrue(events.none { it is Event.PaymentFailed }) } + @Test + fun `a node failure arriving while spark sends the retry never fails it`() = test { + val onEvent = startNodeAndCaptureEvents() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + // The node's earlier attempt fails while Spark is sending the retry, before Spark returns. + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + check(it.getArgument Boolean>(4)()) + onEvent(Event.PaymentFailed("h", "h", PaymentFailureReason.UNEXPECTED_ERROR)) + Result.success("h") + } + + sut.payInvoice("h", 1_000uL) + runCurrent() + + assertTrue(events.none { it is Event.PaymentFailed }, "an older node failure failed the Spark retry") + } + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( id = hash, kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), From d33ff512de6e484c751d58e5587c417130183d99 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:23:42 +0100 Subject: [PATCH 119/135] fix: fail a spark send while the node can't confirm its earlier send --- .../main/java/to/bitkit/repositories/LightningRepo.kt | 10 +++++++--- .../java/to/bitkit/repositories/LightningRepoTest.kt | 6 ++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index f02974aa2f..eba95ee092 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1573,8 +1573,9 @@ class LightningRepo @Inject constructor( /** * The node's pending or paid send of [bolt11]. While the node can't list its payments (stopped or not started yet), - * a send it started for the invoice counts as pending, since it may be live. Before the node first listed its - * payments, the sends it made earlier are unknown, so the node not started yet is thrown. + * a send it started for the invoice may be live or paid, and its event may never come, so the node not started yet + * is thrown rather than a Pending nothing resolves. Before the node first listed its payments, the sends it made + * earlier are unknown, so the same is thrown. */ private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) @@ -1583,7 +1584,10 @@ class LightningRepo @Inject constructor( val payments = listPaymentsKeepingSendHashes() if (payments == null) { val cache = cacheStore.data.first() - if (key in cache.ldkSendHashes) return EarlierSend.Pending(key) + if (key in cache.ldkSendHashes) { + Logger.warn("Refused a Spark send of '$key' until the node lists its earlier send", context = TAG) + throw ServiceError.NodeNotStarted() + } if (!cache.ldkSendHashesSeeded) { Logger.warn("Refused a Spark send until the node lists its earlier payments once", context = TAG) throw ServiceError.NodeNotStarted() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index f1d2689884..b916a6ae05 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -105,6 +105,7 @@ import to.bitkit.test.connectionRecoveryFixture import to.bitkit.test.idleSparkRepo import to.bitkit.utils.AppError import to.bitkit.utils.LdkError +import to.bitkit.utils.ServiceError import to.bitkit.utils.UrlValidator import java.math.BigInteger import kotlin.coroutines.cancellation.CancellationException @@ -1320,7 +1321,7 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `an invoice the node sent is not sent through spark while the node can't list it`() = test { + fun `an invoice the node sent fails rather than pends through spark while the node can't list it`() = test { startNodeForTesting() whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) whenever(lightningService.listPayments()).thenReturn(null) @@ -1331,7 +1332,8 @@ class LightningRepoTest : BaseUnitTest() { val retry = sut.payInvoice("bolt11", 1_000uL) verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) - assertIs(retry.exceptionOrNull()) + // A Pending would wait on a node event that may never come, so it fails until the node can list again. + assertIs(retry.exceptionOrNull()) } @Test From b1595fe8f8dc17d56a397ac8dff2e57eb529af1e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:23:43 +0100 Subject: [PATCH 120/135] fix: keep each savings transfer's own channels to close --- .../to/bitkit/viewmodels/TransferViewModel.kt | 7 ++++-- .../viewmodels/TransferViewModelTest.kt | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 328a2ced64..f8c87e866c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -428,9 +428,12 @@ class TransferViewModel @Inject constructor( * confirmed transfer, in viewModelScope, so leaving the progress screen during the withdrawal skips no close. */ suspend fun closeSelectedChannels(): List { + // Read when the job starts, so a transfer confirmed while it runs never changes what it closes. + val channels = channelsToClose + val withdraws = withdrawsSpark val job = closeJob ?: viewModelScope.async { - if (withdrawsSpark) withdrawSparkToSavings() - closeChannels(channelsToClose) + if (withdraws) withdrawSparkToSavings() + closeChannels(channels) }.also { closeJob = it } return job.await() } diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 3acbc427c9..92c23574a1 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -458,6 +458,28 @@ class TransferViewModelTest : BaseUnitTest() { verify(lightningRepo).closeChannel(CHANNEL_A, false, null) } + @Test + fun `a new savings transfer leaves an earlier one's channels to close`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + val withdrawn = CompletableDeferred>() + whenever { sparkRepo.withdrawAll(any(), any()) }.doSuspendableAnswer { withdrawn.await() } + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = true) + val first = launch { sut.closeSelectedChannels() } + runCurrent() + first.cancel() + + // A second transfer is confirmed while the first still waits on Spark's withdrawal. + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_B), withdrawSpark = false) + sut.closeSelectedChannels() + withdrawn.complete(Result.success(Unit)) + advanceUntilIdle() + + verify(lightningRepo).closeChannel(CHANNEL_A, false, null) + verify(lightningRepo, times(1)).closeChannel(CHANNEL_B, false, null) + } + @Test fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) From b01dee5c8e54f3557d37225256fe44e516ca21be Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:23:43 +0100 Subject: [PATCH 121/135] test: pin the amount change journey to bitkit-docker's spark regtest docs --- .../transfer/spending-confirm-amount-change.xml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/journeys/transfer/spending-confirm-amount-change.xml b/journeys/transfer/spending-confirm-amount-change.xml index 7b10a63ee8..0b9cbcd530 100644 --- a/journeys/transfer/spending-confirm-amount-change.xml +++ b/journeys/transfer/spending-confirm-amount-change.xml @@ -14,12 +14,17 @@ one shown, so the swipe pays at once. The wallet's UTXOs and Spark's deposit must be on one chain the run can fund and mine, so it runs on - bitkit-docker's local Spark regtest (docs/spark-regtest.md in synonymdev/bitkit-docker), where Savings, the - Spark operators and the SSP share bitkit-docker's chain. Lightspark's hosted regtest can't be mined on demand. + bitkit-docker's local Spark regtest, where Savings, the Spark operators and the SSP share bitkit-docker's + chain. Lightspark's hosted regtest can't be mined on demand. The recipe is docs/spark-regtest.md at + synonymdev/bitkit-docker commit cdd294a5ef7470df11ee9ea64d46f441777fdb49 + (https://github.com/synonymdev/bitkit-docker/blob/cdd294a5ef7470df11ee9ea64d46f441777fdb49/docs/spark-regtest.md). - Precondition: `./spark up` running in bitkit-docker; a dev build connected to it as that doc's "Point a - Bitkit dev build at it" section says (the local Spark config and chain URL, patched in where the build - doesn't read them yet, and the `adb reverse` ports), with Savings on bitkit-docker's Electrum + Not yet in this repository: the build setting that reads `SPARK_LOCAL_CONFIG_B64` and `SPARK_LOCAL_CHAIN_URL` + comes in a follow-up PR. Until it lands, this journey runs only on a build with that setting added. + + Precondition: `./spark up` running in bitkit-docker; a dev build with that setting, built and connected as + the doc's "Point a Bitkit dev build at it" section says (`SPARK_LOCAL_CONFIG_B64` from `./spark config + --base64`, `SPARK_LOCAL_CHAIN_URL`, and the `adb reverse` ports), with Savings on bitkit-docker's Electrum (`tcp://127.0.0.1:60001`); a freshly onboarded wallet with no channel and exactly two confirmed on-chain UTXOs of 150 000 sats each (in bitkit-docker, `./spark send <savings address> 150000` twice, each mining a block). Start on the wallet home screen. From 3435dc883135ec940d9bedd6682cf01c1da0c788 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:55:09 +0100 Subject: [PATCH 122/135] fix: keep a missing spark send pending until its invoice expires --- .../java/to/bitkit/repositories/SparkRepo.kt | 35 +++++++++++-------- .../to/bitkit/repositories/SparkRepoTest.kt | 32 +++++++++++++++++ 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f4f023ebeb..1368b8a964 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -142,8 +142,8 @@ class SparkRepo @Inject constructor( private val sendRecordedAt = ConcurrentHashMap() /** Sends whose outcome Spark didn't report, by lowercase payment hash, pending until a later sync settles them. */ - /** Sends whose outcome Spark didn't report, by payment hash, with when they failed in epoch seconds. */ - private val uncertainSends = ConcurrentHashMap() + /** Sends whose outcome Spark didn't report, by payment hash. */ + private val uncertainSends = ConcurrentHashMap() @Volatile private var hasSyncedActivities = false @@ -304,9 +304,9 @@ class SparkRepo @Inject constructor( if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { throw PaymentPendingException(paymentHash) } + val invoice = method.invoiceDetails + val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() val sent = try { - val invoice = method.invoiceDetails - val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) // The checks above and saving the hash suspend, so the deadline is checked last, before the send. @@ -331,7 +331,7 @@ class SparkRepo @Inject constructor( throw SparkError.SendRefused("Spark balance can't cover the payment", it) } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) - settleUncertainSend(paymentHash) + settleUncertainSend(paymentHash, expiresAt) throw PaymentPendingException(paymentHash) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) @@ -341,8 +341,8 @@ class SparkRepo @Inject constructor( } } - private fun settleUncertainSend(paymentHash: String) { - uncertainSends[paymentHash.lowercase()] = clock.now().epochSeconds.toULong() + private fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { + uncertainSends[paymentHash.lowercase()] = UncertainSend(clock.now().epochSeconds.toULong(), expiresAt) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -362,20 +362,22 @@ class SparkRepo @Inject constructor( /** Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. */ private suspend fun trySettleUncertainSend(paymentHash: String): Boolean { val key = paymentHash.lowercase() - val failedAt = uncertainSends[key] ?: return true - // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns, - // so only one that completed after the failure shows the send was never made. - val isSynced = hasSyncedSince(failedAt) + val uncertain = uncertainSends[key] ?: return true + // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns. + val isSynced = hasSyncedSince(uncertain.failedAt) if (isSynced) _state.update { it.copy(hasSynced = true) } + // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark + // can still fail to resume it, so only an expired invoice shows a missing send will never go out. + val isFinal = isSynced && clock.now().epochSeconds.toULong() >= uncertain.expiresAt val send = lightningSend(paymentHash) val isSettled = when (send) { - SparkLightningSend.NotFound -> isSynced - // A failed row may be an earlier attempt's, so it is final only after a sync since the failure. - is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isSynced + SparkLightningSend.NotFound -> isFinal + // A failed row may be an earlier attempt's, so it is final only when a missing one would be. + is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isFinal SparkLightningSend.Unavailable -> false } // Only the caller that takes the hash off settles it, so its outcome is reported once. - if (!isSettled || !uncertainSends.remove(key, failedAt)) return isSettled + if (!isSettled || !uncertainSends.remove(key, uncertain)) return isSettled when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) @@ -392,6 +394,9 @@ class SparkRepo @Inject constructor( return true } + /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ + private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong) + /** Whether Spark's last wallet sync reached it, and started after [seconds] when given. */ private suspend fun hasSyncedSince(seconds: ULong?): Boolean { val info = runSuspendCatching { sparkService.getInfo() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0a26ca3c2a..8fb4ffe10c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1553,6 +1553,38 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1", "hash"), "a failed send still held the node's retry") } + @Test + fun `a spark send missing after a sync that reached spark stays pending until its invoice expires`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val details = mock { + on { paymentHash } doReturn "hash" + on { timestamp }.thenAnswer { now.epochSeconds } + on { expiry }.thenAnswer { 3_600L } + } + val unexpired = prepared(feeSats = 0uL) + .copy(paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 0uL)) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(unexpired) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + // Every sync after the failure reaches Spark, yet Spark lists no such send: resuming it may have failed. + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "a send Spark may still finish was reported failed") + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + } + private fun info(balanceSats: ULong) = GetInfoResponse( identityPubkey = "pubkey", balanceSats = balanceSats, From 4a296671a7c90360253ac224465d20b444331963 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 21:13:47 +0100 Subject: [PATCH 123/135] fix: send spark's savings withdrawal once per transfer --- .../to/bitkit/viewmodels/TransferViewModel.kt | 3 ++- .../viewmodels/TransferViewModelTest.kt | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index f8c87e866c..9353bc087a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -405,7 +405,8 @@ class TransferViewModel @Inject constructor( // Drop any outcome from an earlier attempt so the progress screen cannot act on it. _savingsSwapResult.update { null } _isSparkWithdrawFailed.update { false } - sparkWithdrawJob = null + // A withdrawal still going out is kept, so a transfer confirmed again joins it rather than sending it twice. + if (sparkWithdrawJob?.isActive != true) sparkWithdrawJob = null closeJob = null _savingsSelection.update { SavingsSelection() } channelsToClose = channels diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 92c23574a1..03fdfa650a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -480,6 +480,29 @@ class TransferViewModelTest : BaseUnitTest() { verify(lightningRepo, times(1)).closeChannel(CHANNEL_B, false, null) } + @Test + fun `a second savings confirm never sends spark's withdrawal again`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + val withdrawn = CompletableDeferred>() + whenever { sparkRepo.withdrawAll(any(), any()) }.doSuspendableAnswer { withdrawn.await() } + sut.loadSparkWithdrawFee(SPARK_SATS) + advanceUntilIdle() + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = true) + val first = launch { sut.closeSelectedChannels() } + runCurrent() + first.cancel() + + // The transfer is confirmed again while its withdrawal is still going out. + sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_B), withdrawSpark = true) + val second = launch { sut.closeSelectedChannels() } + runCurrent() + withdrawn.complete(Result.success(Unit)) + advanceUntilIdle() + second.join() + + verify(sparkRepo, times(1)).withdrawAll(any(), any()) + } + @Test fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) From 52a3e63b67a2d03b87f3984fe3c33aed69cb0917 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 21:37:26 +0100 Subject: [PATCH 124/135] fix: fund a new spark transfer amount after a followed funding --- .../screens/transfer/SparkFundingViewModel.kt | 14 ++++-- .../transfer/SparkFundingViewModelTest.kt | 47 +++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index d63ee522cf..e6404b800b 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 @@ -116,7 +116,7 @@ class SparkFundingViewModel @Inject constructor( fun useHardwareWallet(walletId: String) { if (_uiState.value.hwWalletId == walletId) return fixedFeeFloorSats = null - _uiState.update { it.copy(hwWalletId = walletId, isMaxLoading = true) } + _uiState.update { it.copy(hwWalletId = walletId, isMaxLoading = true, txid = null) } refreshMax() } @@ -149,8 +149,16 @@ class SparkFundingViewModel @Inject constructor( fun onAmountChange(sats: Long) { val state = _uiState.value - if (sats != state.amountSats || (sats > 0 && sats == state.maxSats) != state.isMax) fixedFeeFloorSats = null - _uiState.update { it.copy(amountSats = sats, isMax = sats > 0 && sats == it.maxSats) } + val isNewTransfer = sats != state.amountSats || (sats > 0 && sats == state.maxSats) != state.isMax + if (isNewTransfer) fixedFeeFloorSats = null + _uiState.update { + // A funding followed for the earlier amount never stands in for this one's. + it.copy( + amountSats = sats, + isMax = sats > 0 && sats == it.maxSats, + txid = it.txid.takeUnless { isNewTransfer }, + ) + } } fun quarterSats(): Long = _uiState.value.maxSats.let { max -> minOf((max * QUARTER).roundToLong(), max) } 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 00b2ea8e27..49f5ea24e1 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 @@ -499,6 +499,53 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals(SideEffect.FundingPending(retained), effects.last()) } + @Test + fun `a new amount after a kept funding completed off the confirm screen is funded`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) + val retained = OnchainSendAttempt( + walletId = WalletScope.default, attemptId = "attempt", requestId = null, + orderId = null, address = "bcrt1qspark", amountSats = 50_000uL, isMaxAmount = false, + feeRateSatsPerVByte = 2uL, isTransfer = true, channelId = null, tags = emptyList(), + txid = "txid", evidence = OnchainSendEvidence.Unknown, candidateTxids = listOf("txid"), + ) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(retained) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(50_000) + sut.onAmountContinue() + advanceUntilIdle() + sut.onConfirm() + advanceUntilIdle() + // Its Sent effect lands while the Amount screen, which ignores it, is showing. + val confirmed = retained.copy(evidence = OnchainSendEvidence.Observed, localFollowupComplete = true) + whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(confirmed) + attemptUpdates.value++ + advanceUntilIdle() + // A new transfer of another amount starts on the Amount screen that showed. + sut.onAmountChange(40_000) + sut.onAmountContinue() + advanceUntilIdle() + + sut.onConfirm() + advanceUntilIdle() + + verify(lightningRepo, times(2)).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + } + @Test fun `a kept funding that completed off the confirm screen is not sent again`() = test { whenever { From 166d1c0e03a08c9ce83f05346f59ffbc0fac31e1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 21:57:28 +0100 Subject: [PATCH 125/135] fix: hold an unlisted spark send after a restart until its invoice expires --- .../java/to/bitkit/repositories/SparkRepo.kt | 41 +++++++++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 21 ++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1368b8a964..086da4187f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -797,10 +797,11 @@ class SparkRepo @Inject constructor( suspend fun lightningSendStatuses(): Map? = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext emptyMap() if (!canListPayments()) return@withContext null + val unlisted = unexpiredStartedSends() val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext null } - payments + val listed = payments .mapNotNull { payment -> (payment.details as? PaymentDetails.Lightning) ?.takeIf { payment.paymentType == SparkPaymentType.SEND } @@ -808,6 +809,8 @@ class SparkRepo @Inject constructor( } .distinct() .associateWith { hash -> requireNotNull(payments.latestSend(hash)).status } + val listedHashes = listed.keys.mapTo(mutableSetOf()) { it.lowercase() } + listed + (unlisted - listedHashes).associateWith { PaymentStatus.PENDING } } /** @@ -846,6 +849,7 @@ class SparkRepo @Inject constructor( it in recordedSince(recordsBefore) || uncertainSends.containsKey(it) } } + val unlisted = unexpiredStartedSends() // Before Spark's first sync its local list can be empty although a restored send is live. val payments = if (sparkService.isSupported && canListPayments()) { runSuspendCatching { sparkService.listPayments() } @@ -860,7 +864,8 @@ class SparkRepo @Inject constructor( it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - ?: return@withContext retried()?.let { EarlierSend.Pending(it) } + ?: return@withContext (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) + ?.let { EarlierSend.Pending(it) } if (send.status == PaymentStatus.FAILED) retried()?.let { return@withContext EarlierSend.Pending(it) } val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash when (send.status) { @@ -877,6 +882,18 @@ class SparkRepo @Inject constructor( fun hasRecordedSendSince(records: Long, paymentHash: String?): Boolean = paymentHash != null && (sendRecordedAt[paymentHash.lowercase()] ?: 0L) > records + /** + * Spark's started sends whose invoice is unexpired. A sync can still resume one Spark committed but lists no row + * for, also after a restart, so it is pending until its invoice expires, the rule `trySettleUncertainSend` holds. + */ + private suspend fun unexpiredStartedSends(): Set { + val now = clock.now().epochSeconds + val cache = cacheStore.data.first() + return cache.sparkSendHashes.filterTo(mutableSetOf()) { hash -> + cache.sparkSendExpiries[hash]?.let { it > now } == true + } + } + private suspend fun startedSend(paymentHash: String?): String? { val hash = paymentHash?.lowercase() ?: return null return hash.takeIf { it in cacheStore.data.first().sparkSendHashes } @@ -903,9 +920,27 @@ class SparkRepo @Inject constructor( */ suspend fun attemptedLightningPaymentHashes(): Set? { if (!sparkService.isSupported) return emptySet() - return lightningPaymentHashes { it.paymentType == SparkPaymentType.SEND && it.status != PaymentStatus.FAILED } + val unlisted = unexpiredStartedSends() + val sends = lightningPaymentStatuses { it.paymentType == SparkPaymentType.SEND } ?: return null + return sends.filterValues { it.any { status -> status != PaymentStatus.FAILED } }.keys + (unlisted - sends.keys) } + /** The statuses of Spark's Lightning payments that match [filter], by lowercase payment hash. */ + private suspend fun lightningPaymentStatuses(filter: (Payment) -> Boolean): Map>? = + withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext null + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrNull() + ?.filter(filter) + ?.mapNotNull { payment -> + (payment.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash?.lowercase() + ?.let { it to payment.status } + } + ?.groupBy({ it.first }, { it.second }) + ?.mapValues { it.value.toSet() } + } + private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null runSuspendCatching { sparkService.listPayments() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8fb4ffe10c..74ce4ae72e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -287,6 +287,27 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a spark send with no row holds the node after a restart until its invoice expires`() = test { + cacheData.value = AppCacheData( + sparkSendHashes = listOf("hash", "expired"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600, "expired" to now.epochSeconds - 1), + ) + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + + sut.start(0).getOrThrow() + + assertEquals( + EarlierSend.Pending("hash"), + sut.earlierLightningSend("lnbc1280n1send", "hash"), + "The node may pay an invoice whose Spark send a later sync can still resume", + ) + assertEquals(PaymentStatus.PENDING, sut.lightningSendStatuses()?.get("hash")) + assertEquals(setOf("hash"), sut.attemptedLightningPaymentHashes()) + assertNull(sut.earlierLightningSend("lnbc1280n1expired", "expired")) + } + @Test fun `a paid send whose invoice is unexpired still holds the node behind the cap while spark cant list`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 1182bb2287938db98e69920f38a5bfd307c06ad7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 21:57:35 +0100 Subject: [PATCH 126/135] chore: drop a stale spark kdoc --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 086da4187f..be11fe5ce8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -141,7 +141,6 @@ class SparkRepo @Inject constructor( private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() - /** Sends whose outcome Spark didn't report, by lowercase payment hash, pending until a later sync settles them. */ /** Sends whose outcome Spark didn't report, by payment hash. */ private val uncertainSends = ConcurrentHashMap() From 50bc48bd6e96f556c65adc93e6beec0205db1c92 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 22:12:58 +0100 Subject: [PATCH 127/135] fix: count spark as synced only when its wallet sync succeeded --- .../java/to/bitkit/repositories/SparkRepo.kt | 3 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index be11fe5ce8..67a4513a5b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -999,7 +999,8 @@ class SparkRepo @Inject constructor( runSuspendCatching { when (event) { is SdkEvent.Synced -> { - _state.update { it.copy(hasSynced = true) } + // Spark also reports Synced for a partial or skipped sync, while its wallet sync still fails. + if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } refresh() // A send whose outcome stayed unknown past its polling settles on a later sync. uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 74ce4ae72e..09982b7a0a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1449,6 +1449,23 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(sut.canListPayments(), "a restored wallet's unsynced list was read as complete") } + @Test + fun `a synced event after a failed wallet sync leaves spark's payment list unread`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + + // Spark also reports Synced for a partial sync, or one it skipped, while its wallet sync still fails. + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertFalse(sut.canListPayments(), "a list no wallet sync filled was read as complete") + } + @Test fun `an uncertain spark send keeps holding the node off while spark can't resync`() = test { whenever(sparkService.isSupported).thenReturn(true) From 7962bd4d32f592efebc01ca92b6a6c5249a029a0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:14:13 +0100 Subject: [PATCH 128/135] fix: count spark as synced only once a wallet sync succeeded --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 +++++-- .../java/to/bitkit/repositories/SparkRepoTest.kt | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 67a4513a5b..8fa42e0084 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -396,14 +396,17 @@ class SparkRepo @Inject constructor( /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong) - /** Whether Spark's last wallet sync reached it, and started after [seconds] when given. */ + /** + * Whether Spark's last wallet sync reached it, and started after [seconds] when given. A sync time is required + * either way, as the SDK sets it only on a wallet sync that succeeded and reports no error before any sync ends. + */ private suspend fun hasSyncedSince(seconds: ULong?): Boolean { val info = runSuspendCatching { sparkService.getInfo() } .onFailure { Logger.warn("Failed to read Spark's sync state", it, context = TAG) } .getOrNull() ?: return false info.lastSyncError?.let { Logger.warn("Spark's last sync failed: '$it'", context = TAG) } val syncedAt = info.lastSyncedAt - return info.lastSyncError == null && (seconds == null || syncedAt != null && syncedAt > seconds) + return info.lastSyncError == null && syncedAt != null && (seconds == null || syncedAt > seconds) } private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 09982b7a0a..fbaec568f1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1466,6 +1466,20 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(sut.canListPayments(), "a list no wallet sync filled was read as complete") } + @Test + fun `a synced event before any wallet sync succeeded leaves spark's payment list unread`() = test { + whenever(sparkService.isConnected).thenReturn(true) + // After a connect the SDK reports no sync error until a sync ends, and no sync time until one succeeds. + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + val sut = createSut() + + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertFalse(sut.canListPayments(), "a list no wallet sync filled was read as complete") + } + @Test fun `an uncertain spark send keeps holding the node off while spark can't resync`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -1629,7 +1643,7 @@ class SparkRepoTest : BaseUnitTest() { tokenBalances = emptyMap(), recoverableFundsSats = 0uL, lastSyncError = null, - lastSyncedAt = null, + lastSyncedAt = 1uL, ) private fun prepared(feeSats: ULong): PrepareSendPaymentResponse { From 7b247f31ef803ddd1d1151879521f10539229b05 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:17:49 +0100 Subject: [PATCH 129/135] fix: hold a spark send spark may still resume in its send lookup --- .../java/to/bitkit/repositories/SparkRepo.kt | 21 ++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 34 +++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8fa42e0084..256fdc9075 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -368,7 +368,7 @@ class SparkRepo @Inject constructor( // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // can still fail to resume it, so only an expired invoice shows a missing send will never go out. val isFinal = isSynced && clock.now().epochSeconds.toULong() >= uncertain.expiresAt - val send = lightningSend(paymentHash) + val send = listedLightningSend(paymentHash) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal // A failed row may be an earlier attempt's, so it is final only when a missing one would be. @@ -818,9 +818,24 @@ class SparkRepo @Inject constructor( /** * Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. * [SparkLightningSend.Unavailable] while Spark is supported but cannot list its payments, so a send it may hold - * is never read as one it never made. + * is never read as one it never made. A send Spark may still resume reads as pending: one whose outcome Spark + * didn't report, unless a row settles it, and a started one with no row whose invoice is unexpired. */ suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { + val hash = paymentHash.lowercase() + val isUnlistedHeld = hash in unexpiredStartedSends() + val send = listedLightningSend(paymentHash) + val isUncertain = uncertainSends.containsKey(hash) + val isHeld = when (send) { + SparkLightningSend.NotFound -> isUncertain || isUnlistedHeld + is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED + SparkLightningSend.Unavailable -> false + } + if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send + } + + /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ + private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound if (!canListPayments()) return@withContext SparkLightningSend.Unavailable val payments = runSuspendCatching { sparkService.listPayments() } @@ -1033,7 +1048,7 @@ class SparkRepo @Inject constructor( // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) } payment.sendHash(PaymentStatus.FAILED)?.let { hash -> - val latest = lightningSend(hash) + val latest = listedLightningSend(hash) val isReleased = latest == SparkLightningSend.NotFound || (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED if (isReleased) cacheStore.removeSparkSendHash(hash) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fbaec568f1..664f93669d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1498,6 +1498,40 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a retry of an uncertain spark send is refused, not sent again`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + whenever { sparkService.syncWallet() }.thenAnswer { throw SdkException.Generic("operators unreachable") } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + // Spark makes a new transfer for each send call, so a second one may pay the invoice again. + verify(sparkService, times(1)).send(any()) + } + + @Test + fun `an unlisted spark send kept from before a restart reads as pending until its invoice expires`() = test { + cacheData.value = AppCacheData( + sparkSendHashes = listOf("hash", "expired"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600, "expired" to now.epochSeconds - 1), + ) + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + + sut.start(0).getOrThrow() + + // Paykit reads a missing send as never made, so it would drop the proof of one Spark can still resume. + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertEquals(SparkLightningSend.NotFound, sut.lightningSend("expired")) + } + @Test fun `a failed early claim is a failure the claim follower keeps going on`() = test { whenever { sparkService.claimDeposit("txid", 0u, 300uL) } From 515a606a8f461bdb86f62a188f89786f6e5e4d1d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:20:57 +0100 Subject: [PATCH 130/135] fix: withdraw spark to savings only when both read one chain --- .../to/bitkit/viewmodels/TransferViewModel.kt | 12 ++++++++++++ .../to/bitkit/viewmodels/TransferViewModelTest.kt | 15 +++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 9353bc087a..e030640169 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -1,6 +1,7 @@ package to.bitkit.viewmodels import android.content.Context +import androidx.annotation.VisibleForTesting import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -32,6 +33,7 @@ import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentId import to.bitkit.R +import to.bitkit.env.Env import to.bitkit.ext.amountOnClose import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.toUserMessage @@ -83,6 +85,10 @@ class TransferViewModel @Inject constructor( private var sparkFeeJob: Job? = null private var confirmedSparkFeeSats: ULong? = null private var sparkWithdrawJob: Job? = null + + /** Whether Spark and Savings read one chain, so Spark's withdrawal reaches Savings; tests replace it. */ + @VisibleForTesting + internal var sharesNodeChain: () -> Boolean = { Env.sparkSharesNodeChain } private var closeJob: Deferred>? = null private var sparkFeeBalanceSats: ULong? = null private var sparkAddress: String? = null @@ -455,6 +461,12 @@ class TransferViewModel @Inject constructor( _isSparkWithdrawFailed.update { true } return } + // On regtest Savings may read another chain than Spark, so its address there would lose Spark's funds. + if (!sharesNodeChain()) { + Logger.warn("Skipped Spark withdrawal to a Savings wallet on another chain", context = TAG) + _isSparkWithdrawFailed.update { true } + return + } sparkRepo.withdrawAll(address, confirmedFeeSats) .onSuccess { sparkAddress = null diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 03fdfa650a..9037287837 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -91,6 +91,7 @@ class TransferViewModelTest : BaseUnitTest() { clock = clock, sparkRepo = sparkRepo, ) + sut.sharesNodeChain = { true } } @Test @@ -147,6 +148,20 @@ class TransferViewModelTest : BaseUnitTest() { verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) } + @Test + fun `spark is not withdrawn to a savings address on another chain`() = test { + sparkState.value = SparkState(balanceSats = SPARK_SATS) + sut.loadSparkWithdrawFee(SPARK_SATS) + sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) + // A regtest Savings wallet reads its own chain unless the node is pointed at Spark's. + sut.sharesNodeChain = { false } + + sut.closeSelectedChannels() + + verify(sparkRepo, never()).withdrawAll(any(), any()) + assertTrue(sut.isSparkWithdrawFailed.value, "the withdrawal was skipped without telling the user") + } + @Test fun `the swipe resets when spark's balance is priced again before it commits`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) From 568e2779917ffd7b9026d0c90eff3ce97ea70954 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 00:18:52 +0100 Subject: [PATCH 131/135] fix: hold a spark send spark may resume while it can't list --- .../java/to/bitkit/repositories/SparkRepo.kt | 6 +-- .../to/bitkit/repositories/SparkRepoTest.kt | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 256fdc9075..28df35913f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -819,7 +819,8 @@ class SparkRepo @Inject constructor( * Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. * [SparkLightningSend.Unavailable] while Spark is supported but cannot list its payments, so a send it may hold * is never read as one it never made. A send Spark may still resume reads as pending: one whose outcome Spark - * didn't report, unless a row settles it, and a started one with no row whose invoice is unexpired. + * didn't report, unless a row settles it, and a started one with no row whose invoice is unexpired, also while + * Spark can't list its payments, so a retry never sends it again. */ suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() @@ -827,9 +828,8 @@ class SparkRepo @Inject constructor( val send = listedLightningSend(paymentHash) val isUncertain = uncertainSends.containsKey(hash) val isHeld = when (send) { - SparkLightningSend.NotFound -> isUncertain || isUnlistedHeld + SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED - SparkLightningSend.Unavailable -> false } if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 664f93669d..8e7f584e85 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1516,6 +1516,46 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).send(any()) } + @Test + fun `a retry of an uncertain spark send is refused while spark has never synced`() = test { + whenever(sparkService.isConnected).thenReturn(true) + // No wallet sync has succeeded yet, so Spark's list can't be read. + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, times(1)).send(any()) + } + + @Test + fun `a retry of a spark send kept from before a restart is refused while its first sync fails`() = test { + cacheData.value = AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), + ) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + // Spark makes a new transfer for each send call, so the retry would pay the invoice again. + verify(sparkService, never()).send(any()) + } + @Test fun `an unlisted spark send kept from before a restart reads as pending until its invoice expires`() = test { cacheData.value = AppCacheData( From b3298a0eb7aa6d1465d46f1bcc4040928822a524 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 01:08:17 +0100 Subject: [PATCH 132/135] fix: let spark wallets pay each other's invoices as transfers on regtest --- app/src/main/java/to/bitkit/services/SparkService.kt | 3 +++ app/src/test/java/to/bitkit/services/SparkServiceTest.kt | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 22ab976ab4..0ac4d620ac 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -73,6 +73,9 @@ class SparkService @Inject constructor( lnurlDomain = null // Bitkit parses what the user scans itself, so the SDK never sends it to third-party parsers. useDefaultExternalInputParsers = false + // A Spark wallet pays an invoice as a Spark transfer only when the invoice carries the receiver's Spark + // address, which the SDK adds only with this set; on regtest only, like [prefersSpark]. + preferSparkOverLightning = network == SparkNetwork.REGTEST // Lowering it below the spread keeps the deposit from being claimed early, and does not hold back its // claim at maturity. maxDepositClaimFee = MaxFee( diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index 6d2d37def5..682a2664f7 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -18,6 +18,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull +import kotlin.test.assertTrue class SparkServiceTest { @get:Rule @@ -108,4 +109,10 @@ class SparkServiceTest { assertEquals("key", config.apiKey) } } + + @Test + fun `invoices carry the spark address on regtest only, so another spark wallet pays them as a transfer`() { + assertTrue(SparkService.configure(defaults(Network.REGTEST), apiKey = null).preferSparkOverLightning) + assertFalse(SparkService.configure(defaults(Network.MAINNET), apiKey = "key").preferSparkOverLightning) + } } From 5953744126f5cb171fb7bfe25e1fe6b21de298d9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 01:27:36 +0100 Subject: [PATCH 133/135] fix: pay between spark wallets over lightning on regtest --- app/src/main/java/to/bitkit/services/SparkService.kt | 7 ++----- app/src/test/java/to/bitkit/services/SparkServiceTest.kt | 8 ++++---- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 0ac4d620ac..d1f1e5b8ba 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -73,9 +73,6 @@ class SparkService @Inject constructor( lnurlDomain = null // Bitkit parses what the user scans itself, so the SDK never sends it to third-party parsers. useDefaultExternalInputParsers = false - // A Spark wallet pays an invoice as a Spark transfer only when the invoice carries the receiver's Spark - // address, which the SDK adds only with this set; on regtest only, like [prefersSpark]. - preferSparkOverLightning = network == SparkNetwork.REGTEST // Lowering it below the spread keeps the deposit from being claimed early, and does not hold back its // claim at maturity. maxDepositClaimFee = MaxFee( @@ -141,8 +138,8 @@ class SparkService @Inject constructor( var isWiping: Boolean = false /** - * Spark's regtest has no Lightning network, so there a Lightning invoice from another Spark wallet is paid as a - * Spark transfer, which lets two dev builds pay each other's invoices. + * On regtest, an invoice that carries a Spark address is paid as a Spark transfer. Bitkit's own invoices carry + * none, so two dev builds pay each other over Lightning through Spark's provider, as on mainnet. */ val prefersSpark: Boolean get() = Env.network == Network.REGTEST diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index 682a2664f7..04c5685ed4 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -18,7 +18,6 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull -import kotlin.test.assertTrue class SparkServiceTest { @get:Rule @@ -111,8 +110,9 @@ class SparkServiceTest { } @Test - fun `invoices carry the spark address on regtest only, so another spark wallet pays them as a transfer`() { - assertTrue(SparkService.configure(defaults(Network.REGTEST), apiKey = null).preferSparkOverLightning) - assertFalse(SparkService.configure(defaults(Network.MAINNET), apiKey = "key").preferSparkOverLightning) + fun `invoices carry no spark address on any network, so every payment is a lightning payment bitkit records`() { + Network.entries.forEach { network -> + assertFalse(SparkService.configure(defaults(network), apiKey = null).preferSparkOverLightning, "$network") + } } } From 6cdf59220bd3149b8d6d67c25fd55454a67553df Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 09:08:02 +0100 Subject: [PATCH 134/135] fix: keep an unresolved spark retry held across restarts --- .../main/java/to/bitkit/data/CacheStore.kt | 17 ++++++++ .../java/to/bitkit/repositories/SparkRepo.kt | 39 +++++++++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 39 +++++++++++++++++++ 3 files changed, 87 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index dbe0ebd3c0..136c9413d1 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -172,6 +172,18 @@ class CacheStore internal constructor( } } + /** Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds. */ + suspend fun addSparkUncertainSend(paymentHash: String, failedAt: Long) { + val hash = paymentHash.lowercase() + store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt)) } + } + + suspend fun removeSparkUncertainSend(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash !in store.data.first().sparkUncertainSends) return + store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } + } + /** Keeps [paymentHash] with its invoice's expiry in epoch seconds, [expiresAt], when known. */ suspend fun addLdkSendHash(paymentHash: String, expiresAt: Long? = null) { val hash = paymentHash.lowercase() @@ -297,6 +309,11 @@ data class AppCacheData( val sparkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ val sparkSendExpiries: Map = mapOf(), + /** + * Spark's sends whose outcome it didn't report, by hash, with when they failed in epoch seconds, so a restart + * never reads a retry's earlier failed attempt as its outcome. + */ + val sparkUncertainSends: Map = mapOf(), /** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */ val ldkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [ldkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 28df35913f..1feb678341 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -183,6 +183,7 @@ class SparkRepo @Inject constructor( if (isCollectingEvents.compareAndSet(false, true)) { scope.launch { sparkService.events.collect { onSdkEvent(it) } } } + restoreUncertainSends() val connected = sparkService.connect(walletIndex) importRestoredExitState(walletIndex) // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. @@ -340,8 +341,10 @@ class SparkRepo @Inject constructor( } } - private fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { - uncertainSends[paymentHash.lowercase()] = UncertainSend(clock.now().epochSeconds.toULong(), expiresAt) + private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { + val failedAt = clock.now().epochSeconds + uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt) + cacheStore.addSparkUncertainSend(paymentHash, failedAt) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -377,6 +380,7 @@ class SparkRepo @Inject constructor( } // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled || !uncertainSends.remove(key, uncertain)) return isSettled + cacheStore.removeSparkUncertainSend(paymentHash) when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) @@ -396,6 +400,19 @@ class SparkRepo @Inject constructor( /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong) + /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ + private suspend fun restoreUncertainSends() { + val cache = cacheStore.data.first() + cache.sparkUncertainSends.forEach { (hash, failedAt) -> + val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE + uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt)) + } + } + + /** Sends whose outcome Spark didn't report, also ones kept from before a restart not yet taken back. */ + private suspend fun uncertainSendHashes(): Set = + uncertainSends.keys + cacheStore.data.first().sparkUncertainSends.keys + /** * Whether Spark's last wallet sync reached it, and started after [seconds] when given. A sync time is required * either way, as the SDK sets it only on a wallet sync that succeeded and reports no error before any sync ends. @@ -826,7 +843,7 @@ class SparkRepo @Inject constructor( val hash = paymentHash.lowercase() val isUnlistedHeld = hash in unexpiredStartedSends() val send = listedLightningSend(paymentHash) - val isUncertain = uncertainSends.containsKey(hash) + val isUncertain = hash in uncertainSendHashes() val isHeld = when (send) { SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED @@ -854,6 +871,7 @@ class SparkRepo @Inject constructor( suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = withContext(bgDispatcher) { val recordsBefore = sendRecords.get() + val keptUncertain = cacheStore.data.first().sparkUncertainSends.keys val isOfInvoice = { send: Map.Entry -> send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() } @@ -863,7 +881,7 @@ class SparkRepo @Inject constructor( val retried = { sendsInFlight.entries.firstOrNull(isOfInvoice)?.key ?: paymentHash?.lowercase()?.takeIf { - it in recordedSince(recordsBefore) || uncertainSends.containsKey(it) + it in recordedSince(recordsBefore) || uncertainSends.containsKey(it) || it in keptUncertain } } val unlisted = unexpiredStartedSends() @@ -979,9 +997,10 @@ class SparkRepo @Inject constructor( payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } // A send in flight, also one that ended while this list was read, or recorded after it was read while the - // activities were recorded, may be missing from it or show only its earlier failed attempt, so it stays. + // activities were recorded, may be missing from it or show only its earlier failed attempt, so it stays, as + // does one whose outcome Spark didn't report, also from before a restart. val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + inFlightBefore + - recordedSince(recordsBefore) + recordedSince(recordsBefore) + uncertainSendHashes() val paid = sendHashes(PaymentStatus.COMPLETED) - live cacheStore.trimSparkSendHashes( paid = paid, @@ -998,7 +1017,8 @@ class SparkRepo @Inject constructor( val recordsBeforeCurrent = sendRecords.get() val inFlightBeforeCurrent = sendsInFlight.keys.toSet() val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return isSaved - val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + + uncertainSendHashes() failed .filter { it.lowercase() !in liveCurrent } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } @@ -1046,7 +1066,10 @@ class SparkRepo @Inject constructor( .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment) // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) } + payment.sendHash()?.let { + uncertainSends.remove(it.lowercase()) + cacheStore.removeSparkUncertainSend(it) + } payment.sendHash(PaymentStatus.FAILED)?.let { hash -> val latest = listedLightningSend(hash) val isReleased = latest == SparkLightningSend.NotFound || diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8e7f584e85..140d6f9a6d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -37,6 +37,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -1628,6 +1629,44 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { + assertUncertainRetryHeldAfterRestart(syncError = null) + } + + @Test + fun `an uncertain spark retry stays held after a restart whose first sync fails`() = test { + assertUncertainRetryHeldAfterRestart(syncError = SyncError.Network("operators unreachable")) + } + + private suspend fun TestScope.assertUncertainRetryHeldAfterRestart(syncError: SyncError?) { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + // An earlier attempt of the invoice failed, and the retry's outcome is unknown when the app stops. + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = syncError, lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + val after = createSut(store) + after.start(0).getOrThrow() + + assertTrue("hash" in store.data.first().sparkSendHashes, "A restart released a retry Spark may resume") + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) + assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) + } + @Test fun `an uncertain spark send is settled when spark syncs after its polling stopped`() = test { whenever(sparkService.isConnected).thenReturn(true) From 4f10f8d1f21252e6bb3bf9c1a31ee51995cac125 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:23:55 +0100 Subject: [PATCH 135/135] fix: hold a spark send cut off mid-call and read it as pending --- .../java/to/bitkit/repositories/SparkRepo.kt | 18 +++- .../to/bitkit/repositories/SparkRepoTest.kt | 88 +++++++++++++++++++ 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1feb678341..7b0b72144a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -314,6 +314,8 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) throw it } + // Kept until the call returns, so a send cut off by process death or cancellation stays held. + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) @@ -321,12 +323,14 @@ class SparkRepo @Inject constructor( val payment = sent.getOrElse { // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. if (it.isInvoiceExpired()) { + cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.InvoiceExpired(it) } // Spark selects the leaves to spend before anything goes to the operators, so a short balance left // nothing, for instance when an earlier send spent it after the balance was read. if (it is SdkException.InsufficientFunds) { + cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.SendRefused("Spark balance can't cover the payment", it) } @@ -334,6 +338,7 @@ class SparkRepo @Inject constructor( settleUncertainSend(paymentHash, expiresAt) throw PaymentPendingException(paymentHash) } + cacheStore.removeSparkUncertainSend(paymentHash) Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash }.onFailure { @@ -817,6 +822,7 @@ class SparkRepo @Inject constructor( if (!sparkService.isSupported) return@withContext emptyMap() if (!canListPayments()) return@withContext null val unlisted = unexpiredStartedSends() + val uncertain = uncertainSendHashes() val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext null } @@ -827,9 +833,13 @@ class SparkRepo @Inject constructor( ?.htlcDetails?.paymentHash } .distinct() - .associateWith { hash -> requireNotNull(payments.latestSend(hash)).status } + .associateWith { hash -> + val status = requireNotNull(payments.latestSend(hash)).status + // A failed row may be an earlier attempt's, while Spark may still finish the uncertain retry. + if (status == PaymentStatus.FAILED && hash.lowercase() in uncertain) PaymentStatus.PENDING else status + } val listedHashes = listed.keys.mapTo(mutableSetOf()) { it.lowercase() } - listed + (unlisted - listedHashes).associateWith { PaymentStatus.PENDING } + listed + (unlisted + uncertain - listedHashes).associateWith { PaymentStatus.PENDING } } /** @@ -956,8 +966,10 @@ class SparkRepo @Inject constructor( suspend fun attemptedLightningPaymentHashes(): Set? { if (!sparkService.isSupported) return emptySet() val unlisted = unexpiredStartedSends() + val uncertain = uncertainSendHashes() val sends = lightningPaymentStatuses { it.paymentType == SparkPaymentType.SEND } ?: return null - return sends.filterValues { it.any { status -> status != PaymentStatus.FAILED } }.keys + (unlisted - sends.keys) + return sends.filterValues { it.any { status -> status != PaymentStatus.FAILED } }.keys + + (unlisted - sends.keys) + uncertain } /** The statuses of Spark's Lightning payments that match [filter], by lowercase payment hash. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 140d6f9a6d..978d611230 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -1667,6 +1668,93 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a spark retry cut off by process death stays held after a restart while spark lists only its older failure`() = + test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + // The process dies inside Spark's send call, so the call never returns. + whenever { sparkService.send(any()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val before = createSut(store) + before.start(0).getOrThrow() + backgroundScope.launch { before.payInvoice("lnbc1", 100uL) } + runCurrent() + + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + val after = createSut(store) + after.start(0).getOrThrow() + + assertEquals( + EarlierSend.Pending("hash"), + after.earlierLightningSend("lnbc1", "hash"), + "A restart released a retry Spark may resume to the node", + ) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) + } + + @Test + fun `a cancelled spark retry stays held while spark lists only its older failure`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val sut = createSut(store) + sut.start(0).getOrThrow() + val sending = launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + + sending.cancel() + runCurrent() + + assertEquals( + EarlierSend.Pending("hash"), + sut.earlierLightningSend("lnbc1", "hash"), + "A cancelled send released a retry Spark may resume to the node", + ) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + } + + @Test + fun `an uncertain spark retry past an older failure reads as pending to paykit and quickpay`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + store.addSparkSendHash("hash", expiresAt = now.epochSeconds + 3_600) + store.addSparkUncertainSend("hash", now.epochSeconds) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val sut = createSut(store) + sut.start(0).getOrThrow() + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertEquals( + PaymentStatus.PENDING, + sut.lightningSendStatuses()?.get("hash"), + "QuickPay reads an uncertain retry as failed", + ) + assertTrue( + "hash" in sut.attemptedLightningPaymentHashes().orEmpty(), + "Paykit reads an uncertain retry as never attempted", + ) + } + + private fun unexpiredPrepared(): PrepareSendPaymentResponse { + val details = mock { + on { paymentHash } doReturn "hash" + on { timestamp }.thenAnswer { now.epochSeconds } + on { expiry }.thenAnswer { 3_600L } + } + return prepared(feeSats = 0uL).copy(paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 0uL)) + } + @Test fun `an uncertain spark send is settled when spark syncs after its polling stopped`() = test { whenever(sparkService.isConnected).thenReturn(true)