From f00fb41195358af299c73fd4d3cf7472c0c62ec2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 03:10:44 +0100 Subject: [PATCH 01/90] feat: pay contacts via spark Rebuilt on the split Spark head; carries the Pubky Swaps route (#1732) as it was merged into this branch. --- app/build.gradle.kts | 4 + app/src/main/java/to/bitkit/env/Env.kt | 11 ++ .../repositories/PubkySwapsRouteRepo.kt | 127 ++++++++++++ .../java/to/bitkit/repositories/SparkRepo.kt | 39 ++++ .../screens/wallets/send/SendConfirmScreen.kt | 23 +++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 180 +++++++++++++++++- 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 + .../to/bitkit/repositories/SparkRepoTest.kt | 45 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 3 + changelog.d/next/1732.added.md | 1 + changelog.d/next/1754.added.md | 1 + gradle/libs.versions.toml | 2 +- journeys/paykit-spark-route.xml | 27 +++ journeys/paykit-swap-route.xml | 28 +++ 29 files changed, 505 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt create mode 100644 changelog.d/next/1732.added.md create mode 100644 changelog.d/next/1754.added.md create mode 100644 journeys/paykit-spark-route.xml create mode 100644 journeys/paykit-swap-route.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 04873d1fbc..4974812897 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -81,6 +81,8 @@ val e2eHomegateUrlEnv = providers.environmentVariable("E2E_HOMEGATE_URL") .orElse(e2eLocalHostEnv.map { "http://$it:6288" }) val e2eHomeserverPubkyEnv = providers.environmentVariable("E2E_HOMESERVER_PUBKY").orElse("") val e2eHomegateOverrideEnv = providers.environmentVariable("E2E_HOMEGATE_URL").orElse("") +val pubkySwapsRoutesEnv = envFlag("PUBKY_SWAPS_ROUTES", default = false) +val pubkySwapsProvidersEnv = providers.environmentVariable("PUBKY_SWAPS_PROVIDERS").orElse("") val paykitUiDisabledEnv = envFlag("PAYKIT_UI_DISABLED", default = false) val trezorBridgeEnv = localProp("TREZOR_BRIDGE").map { it.toBoolean().toString() }.orElse("false") val trezorBridgeUrlEnv = localProp("TREZOR_BRIDGE_URL").orElse("http://10.0.2.2:21325") @@ -364,6 +366,8 @@ androidComponents { buildConfigFields.put("E2E_HOMEGATE_URL", e2eHomegateUrlEnv.stringField()) buildConfigFields.put("E2E_HOMESERVER_PUBKY", e2eHomeserverPubkyEnv.stringField()) buildConfigFields.put("E2E_HOMEGATE_OVERRIDE", e2eHomegateOverrideEnv.stringField()) + buildConfigFields.put("PUBKY_SWAPS_ROUTES", pubkySwapsRoutesEnv.booleanField()) + buildConfigFields.put("PUBKY_SWAPS_PROVIDERS", pubkySwapsProvidersEnv.stringField()) for (key in listOf("E2E_VSS_SERVER_URL", "E2E_LNURL_AUTH_SERVER_URL", "E2E_BLOCKTANK_API_URL")) { val value = if (variant.buildType == "debug") localProp(key).orElse("") else provider { "" } buildConfigFields.put(key, value.stringField()) diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 09b2fd0dab..47b4858539 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -62,6 +62,17 @@ internal object Env { */ val isSwapSupported get() = network == Network.BITCOIN + /** + * Whether a Paykit payment may route through a Pubky Swaps provider when no balance reaches the contact's + * endpoints. Regtest debug builds with `PUBKY_SWAPS_ROUTES=true` only. + */ + val isPubkySwapsRouteEnabled: Boolean + get() = isDebug && network == Network.REGTEST && BuildConfig.PUBKY_SWAPS_ROUTES + + /** Swap providers to ask besides the user's contacts, from `PUBKY_SWAPS_PROVIDERS` (comma-separated pubkys). */ + val pubkySwapsProviders: List + get() = BuildConfig.PUBKY_SWAPS_PROVIDERS.split(',').map { it.trim() }.filter { it.isNotEmpty() } + const val fxRateRefreshInterval = 2 * 60 * 1000L // 2 minutes in millis const val fxRateStaleThreshold = 10 * 60 * 1000L // 10 minutes in millis const val lspOrdersRefreshInterval = 2 * 60 * 1000L // 2 minutes in millis diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt new file mode 100644 index 0000000000..a2a9c36237 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -0,0 +1,127 @@ +package to.bitkit.repositories + +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaykitRouteRequest +import com.synonym.bitkitcore.PubkySwapRoutePayment +import com.synonym.bitkitcore.PubkySwapRouteState +import com.synonym.bitkitcore.ServiceRouteLeg +import com.synonym.bitkitcore.pubkySwapsAdvance +import com.synonym.bitkitcore.pubkySwapsCommitRoute +import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import to.bitkit.data.keychain.Keychain +import to.bitkit.di.IoDispatcher +import to.bitkit.env.Env +import to.bitkit.ext.nowMillis +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.PubkyProfile +import to.bitkit.models.PubkyPublicKeyFormat +import to.bitkit.models.toCoreNetwork +import to.bitkit.utils.AppError +import to.bitkit.utils.Logger +import to.bitkit.utils.ServiceError +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the + * contact published. bitkit-core picks the provider and checks its quote, contract and hold invoice; the wallet pays + * the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. + */ +@Singleton +class PubkySwapsRouteRepo @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val keychain: Keychain, + private val pubkyRepo: PubkyRepo, + private val sparkRepo: SparkRepo, +) { + companion object { + private const val TAG = "PubkySwapsRouteRepo" + private const val CLAIM_FEE_RATE_SAT_VB = 2uL + private val POLL_INTERVAL = 2.seconds + private val CLAIM_TIMEOUT = 10.minutes + } + + val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled + + /** The contact behind a provider's pubky, so the review shows who routes the payment. */ + fun providerContact(pubky: String): PubkyProfile? = + pubkyRepo.contacts.value.firstOrNull { PubkyPublicKeyFormat.matches(it.publicKey, pubky) } + + suspend fun route( + amountSats: ULong, + endpoints: List, + lightningSpendableSats: ULong, + onchainSpendableSats: ULong, + ): Result = withSecrets { mnemonic, passphrase -> + // Providers come from the user's own graph: every contact is asked for its swap offer. + val candidates = pubkyRepo.contacts.value.map { it.publicKey } + Env.pubkySwapsProviders + val serviceLegs = serviceLegs(endpoints, amountSats) + Logger.debug("Routing Paykit payment via '${candidates.map(PubkyPublicKeyFormat::redacted)}'", context = TAG) + pubkySwapsRoutePaykitPayment( + request = PaykitRouteRequest( + amountSat = amountSats, + contactEndpoints = endpoints, + lightningSpendableSat = lightningSpendableSats, + onchainSpendableSat = onchainSpendableSats, + providers = candidates, + feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, + serviceLegs = serviceLegs, + ), + network = Env.network.toCoreNetwork(), + mnemonic = mnemonic, + bip39Passphrase = passphrase, + ) + } + + /** Legs through the services the wallet holds a balance on, which compete with the providers on fee. */ + private suspend fun serviceLegs(endpoints: List, amountSats: ULong): List = + endpoints.mapNotNull { endpoint -> + sparkRepo.withdrawalRouteLeg(endpoint, amountSats) + .onFailure { Logger.warn("No Spark route to '${endpoint.methodId}'", it, context = TAG) } + .getOrNull() + } + + /** Runs a service leg the router picked and returns the txid that pays the contact. */ + suspend fun payServiceLeg(leg: ServiceRouteLeg): Result = when (leg.service) { + SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat) + else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) + } + + suspend fun commit(quoteId: String): Result = withSecrets { mnemonic, passphrase -> + pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase) + } + + /** Advance the swap until bitkit-core claims the lockup to the contact, returning the claim txid. */ + suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result { + val deadline = nowMillis() + timeout.inWholeMilliseconds + while (true) { + val status = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } + .getOrElse { return Result.failure(it) } + when (val state = status.state) { + is PubkySwapRouteState.Claimed -> return Result.success(state.txid) + is PubkySwapRouteState.Failed -> return Result.failure(AppError(state.reason)) + else -> Logger.debug("Pubky Swaps route '$swapId': $state", context = TAG) + } + if (nowMillis() > deadline) { + return Result.failure(AppError("Swap '$swapId' not claimed yet: '${status.state}'")) + } + delay(POLL_INTERVAL) + } + } + + private suspend fun withSecrets(block: suspend (String, String?) -> T): Result = withContext(ioDispatcher) { + runSuspendCatching { + val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) + ?: throw ServiceError.MnemonicNotFound() + val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + block(mnemonic, passphrase) + } + } +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 398d92f4b5..90fef42a8a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -15,8 +15,10 @@ import breez_sdk_spark.SendOnchainFeeQuote import breez_sdk_spark.SendPaymentMethod import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.LightningActivity +import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType +import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList @@ -78,6 +80,8 @@ class SparkRepo @Inject constructor( companion object { private const val TAG = "SparkRepo" private const val MSATS_PER_SAT = 1_000uL + const val ROUTE_SERVICE = "spark" + private const val ROUTE_ATOMICITY = "trusted" /** How often to look at a deposit until its Instant claim is decided. */ private val CLAIM_POLL_INTERVAL = 5.seconds @@ -352,6 +356,41 @@ class SparkRepo @Inject constructor( private fun PrepareSendPaymentResponse.withdrawalQuote(): SendOnchainFeeQuote = (paymentMethod as SendPaymentMethod.BitcoinAddress).feeQuote + /** + * A Paykit route that withdraws exactly [amountSats] to the contact's on-chain [endpoint] at medium speed, with + * Spark's fee on top, or null while Spark cannot send it. bitkit-core weighs it against the Pubky Swaps providers. + */ + suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result = + withContext(bgDispatcher) { + runSuspendCatching { + if (!canSend(amountSats)) return@runSuspendCatching null + val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod + val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote + val debitSats = amountSats + quote.speedMedium.userFeeSat + if (quote.isEstimate || !canSend(debitSats)) return@runSuspendCatching null + ServiceRouteLeg( + service = ROUTE_SERVICE, + endpoint = endpoint, + deliveredSat = amountSats, + debitSat = debitSats, + atomicity = ROUTE_ATOMICITY, + validUntilUnix = quote.expiresAt, + ) + } + } + + /** Withdraws exactly [amountSats] to the on-chain [address] at medium speed and returns the withdrawal's txid. */ + suspend fun withdraw(address: String, amountSats: ULong): Result = withContext(bgDispatcher) { + runSuspendCatching { + val payment = sparkService.send(sparkService.prepareSend(address, amountSats)) + Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) + refresh() + (payment.details as? PaymentDetails.Withdraw)?.txId ?: payment.id + }.onFailure { + Logger.error("Failed to withdraw to a Paykit contact with Spark", it, context = TAG) + } + } + /** * 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. diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index fd0ea27efc..18beebfdb8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -59,6 +59,7 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.ext.commentAllowed +import to.bitkit.ext.ellipsisMiddle import to.bitkit.ext.formatInvoiceExpiryRelative import to.bitkit.models.FeeRate import to.bitkit.models.PaykitAsset @@ -108,6 +109,9 @@ import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds private val EXPIRY_REFRESH_INTERVAL = 60.seconds + +/** Characters of a swap provider's pubky shown on the confirm screen. */ +private const val PROVIDER_KEY_LENGTH = 12 const val SEND_CONFIRM_RESET_RESULT_KEY = "SEND_CONFIRM_RESET_RESULT_KEY" @Composable @@ -868,6 +872,25 @@ private fun LightningDetails( } } + uiState.paykitSwapRoute?.let { route -> + val text = when { + route.serviceLeg != null -> stringResource(R.string.wallet__send_swap_route_spark) + route.quote != null -> stringResource( + R.string.wallet__send_swap_route_provider, + route.providerName?.takeIf { it.isNotBlank() } + ?: route.quote.providerPubky.ellipsisMiddle(PROVIDER_KEY_LENGTH), + ) + else -> return@let + } + SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { + BodySSB( + text = text, + maxLines = 1, + modifier = Modifier.testTag("ReviewSwapRoute") + ) + } + } + if (!isLnurlPay && !description.isNullOrEmpty() && description.trim() != uiState.confirmationRequestNote) { SendCell(caption = stringResource(R.string.wallet__note)) { Row(modifier = Modifier.horizontalScroll(rememberScrollState())) { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 6fabcf9943..94444d650b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -27,8 +27,12 @@ import com.synonym.bitkitcore.LnurlChannelData import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.LnurlWithdrawData import com.synonym.bitkitcore.OnChainInvoice +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.PaymentType +import com.synonym.bitkitcore.PubkySwapRouteQuote import com.synonym.bitkitcore.Scanner +import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.SortDirection import com.synonym.bitkitcore.UsdtQuote import com.synonym.paykit.PaymentConversion @@ -215,6 +219,7 @@ import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyIdentityReadiness import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.PubkySignIn +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.PublicPaykitPaymentResult import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayPaymentFailedError @@ -319,6 +324,7 @@ class AppViewModel @Inject constructor( private val paykitPaymentRequestDiagnostics: PaykitPaymentRequestDiagnostics, private val refreshContactPaykitLink: RefreshContactPaykitLinkUseCase, private val usdtRepo: UsdtRepo, + private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, val paykitUsdtPayments: PaykitUsdtPaymentRepo, private val samRockRepo: SamRockRepo, private val appUpdateSheet: AppUpdateTimedSheet, @@ -4039,14 +4045,20 @@ class AppViewModel @Inject constructor( val canUseOnchain = address.isNotEmpty() && walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) - val payMethod = paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) + val swapRoute = paykitSwapRoute(payment, address, canUseLightning || canUseOnchain || useUsdt) + val payMethod = if (swapRoute != null) { + SendMethod.LIGHTNING + } else { + paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) + } _sendUiState.update { it.copy( address = address, addressInput = address, isAddressInputValid = address.isNotEmpty(), decodedInvoice = invoice, lnurl = lnurl, paykitUsesUsdt = useUsdt, usdtRecipient = recipient, amount = invoice?.amountSatoshis?.takeIf { payMethod == SendMethod.LIGHTNING } ?: 0u, paykitAmount = "", - payMethod = payMethod + payMethod = payMethod, + paykitSwapRoute = swapRoute, ) } if (usdtRepo.shouldRefresh(isUsdtEnabled.value)) usdtRepo.refresh(history = false) @@ -4179,6 +4191,22 @@ class AppViewModel @Inject constructor( return !canUseBitcoin && balance > 0u } + /** + * A contact whose only reachable endpoint is on-chain, paid from spending when savings cannot cover it: bitkit-core + * routes it through a Pubky Swaps provider. Incoming requests keep their own proof flow and are never swap-routed. + */ + private fun paykitSwapRoute( + payment: ContactPaymentContext, + address: String, + canPayDirectly: Boolean, + ): PaykitSwapRouteUi? { + if (!pubkySwapsRouteRepo.isEnabled || canPayDirectly || address.isEmpty()) return null + if (payment.incomingPaymentRequest != null) return null + if (walletRepo.balanceState.value.maxSendLightningSats == 0uL) return null + val methodId = payment.endpoints.firstOrNull { it.methodId.isOnchain }?.methodId ?: return null + return PaykitSwapRouteUi(endpoint = PaykitEndpoint(methodId = methodId.rawValue, value = address)) + } + private fun canFundPaykitLightning(invoice: LightningInvoice?, lnurl: LnurlParams.LnurlPay?): Boolean { if (invoice == null && lnurl == null) return false val amount = invoice?.amountSatoshis?.coerceAtLeast(1u) ?: lnurl?.data?.minSendableSat() ?: 1u @@ -4568,6 +4596,10 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } + _sendUiState.value.paykitSwapRoute?.let { + if (quotePaykitSwapRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) + return + } _sendUiState.update { it.copy(isLoading = true) } try { @@ -4582,6 +4614,57 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) } + private suspend fun quotePaykitSwapRoute(route: PaykitSwapRouteUi): Boolean { + _sendUiState.update { it.copy(isLoading = true) } + val balances = walletRepo.balanceState.value + val result = pubkySwapsRouteRepo.route( + amountSats = _sendUiState.value.amount, + endpoints = listOf(route.endpoint), + lightningSpendableSats = maxSendableLightningSats(), + onchainSpendableSats = balances.maxSendOnchainSats, + ) + _sendUiState.update { it.copy(isLoading = false) } + val paykitRoute = result.getOrElse { + Logger.error("Failed to route Paykit payment through Pubky Swaps", it, context = TAG) + toast(it) + return false + } + val quote = when (paykitRoute) { + is PaykitRoute.Swap -> paykitRoute.quote + is PaykitRoute.None -> { + toast(AppError(paykitRoute.reason)) + return false + } + is PaykitRoute.Service -> { + val leg = paykitRoute.leg + _sendUiState.update { + it.copy( + paykitSwapRoute = route.copy(quote = null, serviceLeg = leg), + lightningFeeSats = (leg.debitSat - leg.deliveredSat).toLong(), + ) + } + return true + } + // Balances changed after the contact opened: the regular flow must reopen it. + is PaykitRoute.Direct -> { + _sendUiState.update { it.copy(paykitSwapRoute = null) } + toast(AppError(context.getString(R.string.common__error_body))) + return false + } + } + _sendUiState.update { + it.copy( + paykitSwapRoute = route.copy( + quote = quote, + serviceLeg = null, + providerName = pubkySwapsRouteRepo.providerContact(quote.providerPubky)?.name, + ), + lightningFeeSats = quote.totalFeeSat.toLong(), + ) + } + return true + } + private suspend fun reviewPaykitAmount(navigateToUsdtReview: Boolean = true): Boolean { val paykit = synchronized(contactPaymentContextLock) { activeContactPaymentContext } if (paykit == null || paykit.endpoints.isEmpty()) return true @@ -4857,7 +4940,10 @@ class AppViewModel @Inject constructor( resetQuickPay() val fromMainScanner = isMainScanner - if (contactPaymentContext != null && requiresPaykitAssetSelection(contactPaymentContext)) { + if ( + contactPaymentContext != null && + (requiresPaykitAssetSelection(contactPaymentContext) || requiresPaykitSwapRoute(contactPaymentContext)) + ) { openPaykitContactPayment(contactPaymentContext, fromMainScanner, suppressQuickPay, walletGeneration) return@withContext } @@ -4983,6 +5069,13 @@ class AppViewModel @Inject constructor( } } + private fun requiresPaykitSwapRoute(payment: ContactPaymentContext): Boolean { + if (!pubkySwapsRouteRepo.isEnabled || payment.incomingPaymentRequest != null) return false + if (payment.endpoints.isEmpty() || !payment.endpoints.all { it.methodId.isOnchain }) return false + val balances = walletRepo.balanceState.value + return balances.maxSendOnchainSats <= Defaults.dustLimit.toULong() && balances.maxSendLightningSats > 0uL + } + private fun requiresPaykitAssetSelection(payment: ContactPaymentContext): Boolean = payment.endpoints.isNotEmpty() && ( payment.endpoints.any { it.methodId == MethodId.UsdtArbitrum } || @@ -6216,6 +6309,15 @@ class AppViewModel @Inject constructor( return } + _sendUiState.value.paykitSwapRoute?.serviceLeg?.let { + proceedWithServiceRoutedPayment(it, contactPaymentContext, allowanceAttemptId) + return + } + _sendUiState.value.paykitSwapRoute?.quote?.let { + proceedWithSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId) + return + } + when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> proceedWithOnchainPayment( incomingPaymentRequest, @@ -6593,6 +6695,65 @@ class AppViewModel @Inject constructor( ) } + private suspend fun proceedWithServiceRoutedPayment( + leg: ServiceRouteLeg, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + val txid = pubkySwapsRouteRepo.payServiceLeg(leg).getOrElse { + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = txid) + Logger.info("Paid Paykit contact through '${leg.service}' in '$txid'", context = TAG) + onSendSuccess( + NewTransactionSheetDetails( + type = NewTransactionSheetType.ONCHAIN, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = txid, + sats = leg.deliveredSat.toLong(), + ), + ) + } + + private suspend fun proceedWithSwapRoutedPayment( + quote: PubkySwapRouteQuote, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + val payment = pubkySwapsRouteRepo.commit(quote.quoteId).getOrElse { + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + Logger.info("Committed Pubky Swaps route '${payment.swapId}' to '${payment.destinationAddress}'", context = TAG) + // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. + lightningRepo.payInvoice(payment.invoice).getOrElse { + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + val claimTxid = pubkySwapsRouteRepo.awaitClaim(payment.swapId).getOrElse { + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + finishManualAllowancePayment(allowanceAttemptId, succeeded = true) + Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$claimTxid'", context = TAG) + onSendSuccess( + NewTransactionSheetDetails( + type = NewTransactionSheetType.ONCHAIN, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = claimTxid, + sats = payment.deliveredSat.toLong(), + ), + ) + } + private suspend fun proceedWithLightningPayment( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, @@ -8980,6 +9141,7 @@ data class SendUiState( val requiresAmountReview: Boolean = false, val initialSubscriptionPaymentNeedsConfirmation: Boolean = false, val incomingPaymentRequestId: PaykitPaymentRequestId? = null, + val paykitSwapRoute: PaykitSwapRouteUi? = null, ) { val canSwitchBitcoinFundingSource: Boolean get() = fundingOptions.count { it.enabled && it.source != SendFundingSource.Usdt } > 1 @@ -9008,6 +9170,18 @@ data class SendUiState( !initialSubscriptionPaymentNeedsConfirmation && !requiresAmountReview } +/** + * A Paykit payment routed through a Pubky Swaps provider or a service the wallet holds a balance on: the endpoint, + * the route once quoted (a provider's quote or a service leg), and the provider's name. + */ +@Stable +data class PaykitSwapRouteUi( + val endpoint: PaykitEndpoint, + val quote: PubkySwapRouteQuote? = null, + val providerName: String? = null, + val serviceLeg: ServiceRouteLeg? = null, +) + @Immutable data class OnchainFeeUi( val rate: FeeRate = FeeRate.fromSpeed(TransactionSpeed.default()), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 39227d7601..02b328b302 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1029,6 +1029,7 @@ جارٍ دفع\n<accent>الفاتورة...</accent> تأكيد تم إرسال Bitcoin + المسار اسحب للدفع إلى نعم، أرسل 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 dac1da7456..df44172b07 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1062,6 +1062,7 @@ Pagando\n<accent>factura...</accent> Confirmar Bitcoin Enviado + Ruta Deslizar para pagar Para Sí, enviar diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 334505505c..4ff283484c 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1055,6 +1055,7 @@ Pagant\n<accent>factura...</accent> Confirmar Bitcoin enviat + Ruta Desplaça per pagar A Sí, Enviar diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 91f4805c90..9b9e67758a 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1060,6 +1060,7 @@ Placení\n<accent>faktury...</accent> Potvrdit bitcoin odeslán + Trasa Zaplatit přejetím prstem Komu Ano, odeslat diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 5cea87a889..963a9f6749 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -910,6 +910,7 @@ Bestätigung in Kontakt auswählen Rechnungsverfall + Route Zum Bezahlen wischen Ja, senden Es scheint, dass du über $100 sendest. Möchtest du fortfahren? diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 13bc6c27e3..57b54e56c7 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1034,6 +1034,7 @@ Πληρωμή\n<accent>τιμολογίου...</accent> Επιβεβαίωση Τα Bitcoin στάλθηκαν + Διαδρομή Σύρε για πληρωμή Προς Ναι, Στείλε diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index e50e8de4c2..c22cf1a703 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1055,6 +1055,7 @@ Pagando\n<accent>factura...</accent> Confirmar Bitcoin Enviado + Ruta Deslizar para pagar Para Sí, enviar diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index fa41c6b382..0acad2ffc5 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -902,6 +902,7 @@ Confirmando en Seleccionar contacto Expiración de la factura + Ruta Deslizar para pagar Sí, enviar Parece que está enviando más de 100 dólares. ¿Desea continuar? diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 205a538624..7f9f86c5a8 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -911,6 +911,7 @@ Confirmation en Sélectionnez un contact Expiration de la facture + Itinéraire Glisser pour payer Oui, Envoyer Il apparaît que vous envoyez plus de 100 $. Voulez-vous continuer ? diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f46eaf89c8..3d663caa86 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1058,6 +1058,7 @@ Pagamento\n<accent>fattura...</accent> Conferma Bitcoin Inviati + Percorso Scorri per Pagare A Si, Invia diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index fc7c27129e..2fff35ac91 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1053,6 +1053,7 @@ Factuur\n<accent>betalen...</accent> Bevestigen Bitcoin verzonden + Route Veeg om te betalen Naar Ja, verzenden diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 61316f843c..2eb651ce65 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -913,6 +913,7 @@ Potwierdzenie w ciągu Wybierz kontakt Termin faktury + Trasa Przesuń, aby zapłacić Tak, wyślij Wygląda na to, że wysyłasz ponad $100. Czy kontynuować? diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 3e7b7deb6b..9f204e9ca0 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1062,6 +1062,7 @@ Pagando \n<accent>invoice...</accent> Confirmar Bitcoin Enviado + Rota Deslize para Pagar Para Sim, Enviar diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 81321c2947..f798125cb1 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -774,6 +774,7 @@ Confirmar Confirmando em Vencimento do invoice + Rota Deslize para Pagar Sim, Enviar Parece que você está enviando mais de US$ 100. Deseja continuar? diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 3f8d38a426..a5d5c7f0c8 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1078,6 +1078,7 @@ <accent>счёта...</accent> Подтвердить Биткоины отправлены + Маршрут Отправить Кому Да, Отправить diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2fb23120cf..a9360c5c88 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1626,6 +1626,9 @@ Paying\n<accent>invoice...</accent> Confirm Bitcoin Sent + Route + Pubky Swaps · %1$s + Spark Swipe To Pay To Yes, Send diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index dc56da0703..d01092ca52 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -25,6 +25,8 @@ import breez_sdk_spark.SparkHtlcDetails import breez_sdk_spark.SparkHtlcStatus import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -201,6 +203,49 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf(SparkWithdrawal("withdrawal", 128uL, 1_470uL)), sut.state.value.withdrawals) } + @Test + fun `quotes a withdrawal to a Paykit contact as a route leg`() = test { + val sut = readySpark(balanceSats = 50_000uL) + + val leg = sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow() + + assertEquals( + ServiceRouteLeg( + service = "spark", + endpoint = contactEndpoint, + deliveredSat = 20_000uL, + debitSat = 20_300uL, + atomicity = "trusted", + validUntilUnix = 1_900_000_000uL, + ), + leg, + ) + } + + @Test + fun `offers no route leg the balance cannot cover with its fee`() = test { + val sut = readySpark(balanceSats = 20_299uL) + + assertEquals(null, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()) + } + + private val contactEndpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = "bcrt1qcontact") + + private suspend fun readySpark(balanceSats: ULong): SparkRepo { + whenever { sparkService.getInfo() }.thenReturn(GetInfoResponse("pubkey", balanceSats, emptyMap(), 0uL)) + val speed = SendOnchainSpeedFeeQuote(userFeeSat = 300uL, l1BroadcastFeeSat = 200uL) + val prepared = mock() + whenever(prepared.paymentMethod).thenReturn( + SendPaymentMethod.BitcoinAddress( + address = mock(), + feeQuote = SendOnchainFeeQuote("quote", 1_900_000_000uL, speed, speed, speed, isEstimate = false), + ), + ) + whenever { sparkService.prepareSend(eq("bcrt1qcontact"), eq(20_000uL), anyOrNull()) }.thenReturn(prepared) + whenever(sparkService.isConnected).thenReturn(true) + return createSut().also { it.start(0).getOrThrow() } + } + @Test fun `skips an exit backup from another network`() = test { val sut = createSut() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ac1d2b580f..31df759f21 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -201,6 +201,7 @@ import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyIdentityReadiness import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.PubkySignIn +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.PublicPaykitPaymentResult import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayCompletionKind @@ -304,6 +305,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitPaymentProofRepo = mock() private val paykitPaymentRequestDiagnostics = mock() private val usdtRepo = mock() + private val pubkySwapsRouteRepo = mock() private val usdtState = MutableStateFlow(UsdtWalletState(balance = 1_000_000u)) private val paykitUsdtPayments = mock() private val samRockRepo = mock() @@ -957,6 +959,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paykitPaymentRequestDiagnostics = paykitPaymentRequestDiagnostics, refreshContactPaykitLink = refreshContactPaykitLink, usdtRepo = usdtRepo, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, paykitUsdtPayments = paykitUsdtPayments, samRockRepo = samRockRepo, appUpdateSheet = mock { on { type } doReturn TimedSheetType.APP_UPDATE }, diff --git a/changelog.d/next/1732.added.md b/changelog.d/next/1732.added.md new file mode 100644 index 0000000000..d7dfa80257 --- /dev/null +++ b/changelog.d/next/1732.added.md @@ -0,0 +1 @@ +Bitkit can pay a contact who only accepts on-chain bitcoin from your spending balance, through a Pubky Swaps provider among your contacts. diff --git a/changelog.d/next/1754.added.md b/changelog.d/next/1754.added.md new file mode 100644 index 0000000000..9dd64f6e8c --- /dev/null +++ b/changelog.d/next/1754.added.md @@ -0,0 +1 @@ +Paykit contacts who only accept on-chain bitcoin can be paid from Spark when that costs less than a swap. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a899b0db87..299aa02284 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,7 +21,7 @@ activity-compose = { module = "androidx.activity:activity-compose", version = "1 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" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-swaps.3" } 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" } diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml new file mode 100644 index 0000000000..d2eec897a3 --- /dev/null +++ b/journeys/paykit-spark-route.xml @@ -0,0 +1,27 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet whose spending balance is held + on Spark, routes through a Spark withdrawal straight to the contact's address, without the user picking a route, + and that the contact receives the exact amount on chain. + + Preconditions: a dev debug build with E2E=true, E2E_BACKEND=local, E2E_HOMESERVER_PUBKY set to the local + marketplace homeserver and PUBKY_SWAPS_ROUTES=true; bitkit-docker's default stack with the marketplace and + payment-requests profiles; adb reverse for 6286, 6287, 6288, 15411, 15412, 60001, 23735, 23000 and 23010. + The wallet has no channels and an empty savings balance, a Spark balance of at least 25 000 sats from Lightspark's + regtest faucet sent to the deposit address on the Spark screen, a Pubky profile on the local homeserver, and the + fixture-issuer's pubky saved as a contact. The contact is bitkit-docker's fixture-issuer, which publishes only a + btc-regtest-p2wpkh endpoint; Spark pays it on Lightspark's regtest chain. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Tap the fixture-issuer (tag "SendContact_" followed by its pubky) + Verify the amount screen (tag "send_amount_screen") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Spark" + Swipe to pay (tag "GRAB") + Verify the Bitcoin Sent screen (tag "SendSuccess") shows 20 000 + Verify Lightspark's regtest mempool shows the withdrawal transaction paying exactly 20 000 sats to the fixture-issuer's address + + diff --git a/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml new file mode 100644 index 0000000000..5de3d268fa --- /dev/null +++ b/journeys/paykit-swap-route.xml @@ -0,0 +1,28 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet that holds only a spending + balance, routes through a Pubky Swaps provider found among the user's own contacts, without the user picking a + swap, and that the contact receives the exact amount on chain. + + Preconditions: a dev debug build with E2E=true, E2E_BACKEND=local, E2E_HOMESERVER_PUBKY set to the local + marketplace homeserver and PUBKY_SWAPS_ROUTES=true; bitkit-docker's + default stack with the marketplace, payment-requests and lnurl-pay profiles; the provider running against + bitkit-docker's LND and funded; adb reverse for 6286, 6287, 6288, 15411, 15412, 60001, 23735, 23000 and 23010. + The wallet has a spending balance from an LNURL channel with bitkit-docker's LND and an empty savings balance, + a Pubky profile on the local homeserver, and both the provider's and the fixture-issuer's pubkys saved as contacts. + The contact is bitkit-docker's fixture-issuer, which publishes only a btc-regtest-p2wpkh endpoint. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Verify the contact list shows both the fixture-issuer and the provider, and tap the fixture-issuer (tag "SendContact_" followed by its pubky) + Verify the amount screen (tag "send_amount_screen") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Pubky Swaps" followed by the provider's shortened pubky + Swipe to pay (tag "GRAB") + Once the provider logs "HTLC funded; awaiting client claim", mine one block on bitkit-docker's bitcoind + Verify the Bitcoin Sent screen (tag "SendSuccess") is visible + Verify the provider logs "client claimed; hold invoice settled", and bitcoind shows the claim transaction paying exactly 0.0002 BTC to the fixture-issuer's address + + From 735b5a9fb5f14ed954524d7efc48f365b822cf4c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 22:26:18 +0100 Subject: [PATCH 02/90] feat: route paykit payments with bitkit-core spark.2 --- app/build.gradle.kts | 4 - app/src/main/java/to/bitkit/env/Env.kt | 11 -- .../to/bitkit/repositories/PaykitRouteRepo.kt | 70 +++++++++ .../repositories/PubkySwapsRouteRepo.kt | 127 ---------------- .../screens/wallets/send/SendConfirmScreen.kt | 17 +-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 136 +++++------------- app/src/main/res/values/strings.xml | 1 - .../viewmodels/AppViewModelSendFlowTest.kt | 6 +- changelog.d/next/1732.added.md | 1 - changelog.d/next/1754.added.md | 2 +- gradle/libs.versions.toml | 2 +- journeys/paykit-spark-route.xml | 2 +- journeys/paykit-swap-route.xml | 28 ---- 13 files changed, 112 insertions(+), 295 deletions(-) create mode 100644 app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt delete mode 100644 app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt delete mode 100644 changelog.d/next/1732.added.md delete mode 100644 journeys/paykit-swap-route.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d5e3f7a3f2..e10c852c72 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -81,8 +81,6 @@ val e2eHomegateUrlEnv = providers.environmentVariable("E2E_HOMEGATE_URL") .orElse(e2eLocalHostEnv.map { "http://$it:6288" }) val e2eHomeserverPubkyEnv = providers.environmentVariable("E2E_HOMESERVER_PUBKY").orElse("") val e2eHomegateOverrideEnv = providers.environmentVariable("E2E_HOMEGATE_URL").orElse("") -val pubkySwapsRoutesEnv = envFlag("PUBKY_SWAPS_ROUTES", default = false) -val pubkySwapsProvidersEnv = providers.environmentVariable("PUBKY_SWAPS_PROVIDERS").orElse("") val paykitUiDisabledEnv = envFlag("PAYKIT_UI_DISABLED", default = false) val trezorBridgeEnv = localProp("TREZOR_BRIDGE").map { it.toBoolean().toString() }.orElse("false") val trezorBridgeUrlEnv = localProp("TREZOR_BRIDGE_URL").orElse("http://10.0.2.2:21325") @@ -366,8 +364,6 @@ androidComponents { buildConfigFields.put("E2E_HOMEGATE_URL", e2eHomegateUrlEnv.stringField()) buildConfigFields.put("E2E_HOMESERVER_PUBKY", e2eHomeserverPubkyEnv.stringField()) buildConfigFields.put("E2E_HOMEGATE_OVERRIDE", e2eHomegateOverrideEnv.stringField()) - buildConfigFields.put("PUBKY_SWAPS_ROUTES", pubkySwapsRoutesEnv.booleanField()) - buildConfigFields.put("PUBKY_SWAPS_PROVIDERS", pubkySwapsProvidersEnv.stringField()) for (key in listOf("E2E_VSS_SERVER_URL", "E2E_LNURL_AUTH_SERVER_URL", "E2E_BLOCKTANK_API_URL")) { val value = if (variant.buildType == "debug") localProp(key).orElse("") else provider { "" } buildConfigFields.put(key, value.stringField()) diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 7b985e786d..8f035eb59d 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -63,17 +63,6 @@ internal object Env { */ val isSwapSupported get() = network == Network.BITCOIN - /** - * Whether a Paykit payment may route through a Pubky Swaps provider when no balance reaches the contact's - * endpoints. Regtest debug builds with `PUBKY_SWAPS_ROUTES=true` only. - */ - val isPubkySwapsRouteEnabled: Boolean - get() = isDebug && network == Network.REGTEST && BuildConfig.PUBKY_SWAPS_ROUTES - - /** Swap providers to ask besides the user's contacts, from `PUBKY_SWAPS_PROVIDERS` (comma-separated pubkys). */ - val pubkySwapsProviders: List - get() = BuildConfig.PUBKY_SWAPS_PROVIDERS.split(',').map { it.trim() }.filter { it.isNotEmpty() } - const val fxRateRefreshInterval = 2 * 60 * 1000L // 2 minutes in millis const val fxRateStaleThreshold = 10 * 60 * 1000L // 10 minutes in millis const val lspOrdersRefreshInterval = 2 * 60 * 1000L // 2 minutes in millis diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt new file mode 100644 index 0000000000..8f53f79df6 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -0,0 +1,70 @@ +package to.bitkit.repositories + +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaykitRouteRequest +import com.synonym.bitkitcore.ServiceRouteLeg +import com.synonym.bitkitcore.paykitRoutePayment +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import to.bitkit.di.IoDispatcher +import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.toCoreNetwork +import to.bitkit.utils.AppError +import to.bitkit.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Picks how to pay a Paykit contact through bitkit-core's Paykit router: directly from a balance the wallet holds, + * or through a Spark withdrawal to the contact's on-chain endpoint when no balance reaches the contact. The router + * makes no network calls; the app quotes each Spark leg and runs the one the router returns. + */ +@Singleton +class PaykitRouteRepo @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val sparkRepo: SparkRepo, +) { + companion object { + private const val TAG = "PaykitRouteRepo" + } + + /** Whether Spark holds a balance it can send, so a Spark leg may reach a contact no other balance reaches. */ + val canRouteThroughSpark: Boolean + get() = sparkRepo.state.value.let { it.isReady && it.sendableSats > 0uL } + + suspend fun route( + amountSats: ULong, + endpoints: List, + lightningSpendableSats: ULong, + onchainSpendableSats: ULong, + ): Result = withContext(ioDispatcher) { + runSuspendCatching { + paykitRoutePayment( + request = PaykitRouteRequest( + amountSat = amountSats, + contactEndpoints = endpoints, + lightningSpendableSat = lightningSpendableSats, + onchainSpendableSat = onchainSpendableSats, + serviceLegs = serviceLegs(endpoints, amountSats), + ), + network = Env.network.toCoreNetwork(), + ) + } + } + + /** Spark withdrawals to the contact's on-chain endpoints, each quoted with its fee. */ + private suspend fun serviceLegs(endpoints: List, amountSats: ULong): List = + endpoints.mapNotNull { endpoint -> + sparkRepo.withdrawalRouteLeg(endpoint, amountSats) + .onFailure { Logger.warn("No Spark route to '${endpoint.methodId}'", it, context = TAG) } + .getOrNull() + } + + /** Runs a service leg the router picked and returns the txid that pays the contact. */ + suspend fun payServiceLeg(leg: ServiceRouteLeg): Result = when (leg.service) { + SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat) + else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) + } +} diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt deleted file mode 100644 index a2a9c36237..0000000000 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ /dev/null @@ -1,127 +0,0 @@ -package to.bitkit.repositories - -import com.synonym.bitkitcore.PaykitEndpoint -import com.synonym.bitkitcore.PaykitRoute -import com.synonym.bitkitcore.PaykitRouteRequest -import com.synonym.bitkitcore.PubkySwapRoutePayment -import com.synonym.bitkitcore.PubkySwapRouteState -import com.synonym.bitkitcore.ServiceRouteLeg -import com.synonym.bitkitcore.pubkySwapsAdvance -import com.synonym.bitkitcore.pubkySwapsCommitRoute -import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment -import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.delay -import kotlinx.coroutines.withContext -import to.bitkit.data.keychain.Keychain -import to.bitkit.di.IoDispatcher -import to.bitkit.env.Env -import to.bitkit.ext.nowMillis -import to.bitkit.ext.runSuspendCatching -import to.bitkit.models.PubkyProfile -import to.bitkit.models.PubkyPublicKeyFormat -import to.bitkit.models.toCoreNetwork -import to.bitkit.utils.AppError -import to.bitkit.utils.Logger -import to.bitkit.utils.ServiceError -import javax.inject.Inject -import javax.inject.Singleton -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds - -/** - * Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the - * contact published. bitkit-core picks the provider and checks its quote, contract and hold invoice; the wallet pays - * the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. - */ -@Singleton -class PubkySwapsRouteRepo @Inject constructor( - @IoDispatcher private val ioDispatcher: CoroutineDispatcher, - private val keychain: Keychain, - private val pubkyRepo: PubkyRepo, - private val sparkRepo: SparkRepo, -) { - companion object { - private const val TAG = "PubkySwapsRouteRepo" - private const val CLAIM_FEE_RATE_SAT_VB = 2uL - private val POLL_INTERVAL = 2.seconds - private val CLAIM_TIMEOUT = 10.minutes - } - - val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled - - /** The contact behind a provider's pubky, so the review shows who routes the payment. */ - fun providerContact(pubky: String): PubkyProfile? = - pubkyRepo.contacts.value.firstOrNull { PubkyPublicKeyFormat.matches(it.publicKey, pubky) } - - suspend fun route( - amountSats: ULong, - endpoints: List, - lightningSpendableSats: ULong, - onchainSpendableSats: ULong, - ): Result = withSecrets { mnemonic, passphrase -> - // Providers come from the user's own graph: every contact is asked for its swap offer. - val candidates = pubkyRepo.contacts.value.map { it.publicKey } + Env.pubkySwapsProviders - val serviceLegs = serviceLegs(endpoints, amountSats) - Logger.debug("Routing Paykit payment via '${candidates.map(PubkyPublicKeyFormat::redacted)}'", context = TAG) - pubkySwapsRoutePaykitPayment( - request = PaykitRouteRequest( - amountSat = amountSats, - contactEndpoints = endpoints, - lightningSpendableSat = lightningSpendableSats, - onchainSpendableSat = onchainSpendableSats, - providers = candidates, - feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, - serviceLegs = serviceLegs, - ), - network = Env.network.toCoreNetwork(), - mnemonic = mnemonic, - bip39Passphrase = passphrase, - ) - } - - /** Legs through the services the wallet holds a balance on, which compete with the providers on fee. */ - private suspend fun serviceLegs(endpoints: List, amountSats: ULong): List = - endpoints.mapNotNull { endpoint -> - sparkRepo.withdrawalRouteLeg(endpoint, amountSats) - .onFailure { Logger.warn("No Spark route to '${endpoint.methodId}'", it, context = TAG) } - .getOrNull() - } - - /** Runs a service leg the router picked and returns the txid that pays the contact. */ - suspend fun payServiceLeg(leg: ServiceRouteLeg): Result = when (leg.service) { - SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat) - else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) - } - - suspend fun commit(quoteId: String): Result = withSecrets { mnemonic, passphrase -> - pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase) - } - - /** Advance the swap until bitkit-core claims the lockup to the contact, returning the claim txid. */ - suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result { - val deadline = nowMillis() + timeout.inWholeMilliseconds - while (true) { - val status = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } - .getOrElse { return Result.failure(it) } - when (val state = status.state) { - is PubkySwapRouteState.Claimed -> return Result.success(state.txid) - is PubkySwapRouteState.Failed -> return Result.failure(AppError(state.reason)) - else -> Logger.debug("Pubky Swaps route '$swapId': $state", context = TAG) - } - if (nowMillis() > deadline) { - return Result.failure(AppError("Swap '$swapId' not claimed yet: '${status.state}'")) - } - delay(POLL_INTERVAL) - } - } - - private suspend fun withSecrets(block: suspend (String, String?) -> T): Result = withContext(ioDispatcher) { - runSuspendCatching { - val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) - ?: throw ServiceError.MnemonicNotFound() - val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) - block(mnemonic, passphrase) - } - } -} diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 18beebfdb8..42a9841e43 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -59,7 +59,6 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.ext.commentAllowed -import to.bitkit.ext.ellipsisMiddle import to.bitkit.ext.formatInvoiceExpiryRelative import to.bitkit.models.FeeRate import to.bitkit.models.PaykitAsset @@ -109,9 +108,6 @@ import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds private val EXPIRY_REFRESH_INTERVAL = 60.seconds - -/** Characters of a swap provider's pubky shown on the confirm screen. */ -private const val PROVIDER_KEY_LENGTH = 12 const val SEND_CONFIRM_RESET_RESULT_KEY = "SEND_CONFIRM_RESET_RESULT_KEY" @Composable @@ -872,19 +868,10 @@ private fun LightningDetails( } } - uiState.paykitSwapRoute?.let { route -> - val text = when { - route.serviceLeg != null -> stringResource(R.string.wallet__send_swap_route_spark) - route.quote != null -> stringResource( - R.string.wallet__send_swap_route_provider, - route.providerName?.takeIf { it.isNotBlank() } - ?: route.quote.providerPubky.ellipsisMiddle(PROVIDER_KEY_LENGTH), - ) - else -> return@let - } + if (uiState.paykitRoute?.serviceLeg != null) { SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { BodySSB( - text = text, + text = stringResource(R.string.wallet__send_swap_route_spark), maxLines = 1, modifier = Modifier.testTag("ReviewSwapRoute") ) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9c5c80e8ca..388003c44a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -30,7 +30,6 @@ import com.synonym.bitkitcore.OnChainInvoice import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.PaymentType -import com.synonym.bitkitcore.PubkySwapRouteQuote import com.synonym.bitkitcore.Scanner import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.SortDirection @@ -205,6 +204,7 @@ import to.bitkit.repositories.PaykitPaymentRequestId import to.bitkit.repositories.PaykitPaymentRequestRefreshMode import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTarget +import to.bitkit.repositories.PaykitRouteRepo import to.bitkit.repositories.PaykitSubscription import to.bitkit.repositories.PaykitSubscriptionDraft import to.bitkit.repositories.PaykitSubscriptionId @@ -220,7 +220,6 @@ import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyIdentityReadiness import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.PubkySignIn -import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.PublicPaykitPaymentResult import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayPaymentFailedError @@ -326,7 +325,7 @@ class AppViewModel @Inject constructor( private val paykitPaymentRequestDiagnostics: PaykitPaymentRequestDiagnostics, private val refreshContactPaykitLink: RefreshContactPaykitLinkUseCase, private val usdtRepo: UsdtRepo, - private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, + private val paykitRouteRepo: PaykitRouteRepo, val paykitUsdtPayments: PaykitUsdtPaymentRepo, private val samRockRepo: SamRockRepo, private val appUpdateSheet: AppUpdateTimedSheet, @@ -4052,8 +4051,8 @@ class AppViewModel @Inject constructor( val canUseOnchain = address.isNotEmpty() && walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) - val swapRoute = paykitSwapRoute(payment, address, canUseLightning || canUseOnchain || useUsdt) - val payMethod = if (swapRoute != null) { + val route = paykitServiceRoute(payment, address, canUseLightning || canUseOnchain || useUsdt) + val payMethod = if (route != null) { SendMethod.LIGHTNING } else { paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) @@ -4065,7 +4064,7 @@ class AppViewModel @Inject constructor( amount = invoice?.amountSatoshis?.takeIf { payMethod == SendMethod.LIGHTNING } ?: 0u, paykitAmount = "", payMethod = payMethod, - paykitSwapRoute = swapRoute, + paykitRoute = route, ) } if (usdtRepo.shouldRefresh(isUsdtEnabled.value)) usdtRepo.refresh(history = false) @@ -4198,20 +4197,15 @@ class AppViewModel @Inject constructor( return !canUseBitcoin && balance > 0u } - /** - * A contact whose only reachable endpoint is on-chain, paid from spending when savings cannot cover it: bitkit-core - * routes it through a Pubky Swaps provider. Incoming requests keep their own proof flow and are never swap-routed. - */ - private fun paykitSwapRoute( + private fun paykitServiceRoute( payment: ContactPaymentContext, address: String, canPayDirectly: Boolean, - ): PaykitSwapRouteUi? { - if (!pubkySwapsRouteRepo.isEnabled || canPayDirectly || address.isEmpty()) return null + ): PaykitRouteUi? { + if (!paykitRouteRepo.canRouteThroughSpark || canPayDirectly || address.isEmpty()) return null if (payment.incomingPaymentRequest != null) return null - if (walletRepo.balanceState.value.maxSendLightningSats == 0uL) return null val methodId = payment.endpoints.firstOrNull { it.methodId.isOnchain }?.methodId ?: return null - return PaykitSwapRouteUi(endpoint = PaykitEndpoint(methodId = methodId.rawValue, value = address)) + return PaykitRouteUi(endpoint = PaykitEndpoint(methodId = methodId.rawValue, value = address)) } private fun canFundPaykitLightning(invoice: LightningInvoice?, lnurl: LnurlParams.LnurlPay?): Boolean { @@ -4635,8 +4629,8 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } - _sendUiState.value.paykitSwapRoute?.let { - if (quotePaykitSwapRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) + _sendUiState.value.paykitRoute?.let { + if (quotePaykitRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) return } @@ -4653,54 +4647,38 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) } - private suspend fun quotePaykitSwapRoute(route: PaykitSwapRouteUi): Boolean { + private suspend fun quotePaykitRoute(route: PaykitRouteUi): Boolean { _sendUiState.update { it.copy(isLoading = true) } - val balances = walletRepo.balanceState.value - val result = pubkySwapsRouteRepo.route( + val result = paykitRouteRepo.route( amountSats = _sendUiState.value.amount, endpoints = listOf(route.endpoint), lightningSpendableSats = maxSendableLightningSats(), - onchainSpendableSats = balances.maxSendOnchainSats, + onchainSpendableSats = walletRepo.balanceState.value.maxSendOnchainSats, ) _sendUiState.update { it.copy(isLoading = false) } - val paykitRoute = result.getOrElse { - Logger.error("Failed to route Paykit payment through Pubky Swaps", it, context = TAG) + val picked = result.getOrElse { + Logger.error("Failed to route Paykit payment", it, context = TAG) toast(it) return false } - val quote = when (paykitRoute) { - is PaykitRoute.Swap -> paykitRoute.quote + when (picked) { + is PaykitRoute.Service -> _sendUiState.update { + it.copy( + paykitRoute = route.copy(serviceLeg = picked.leg), + lightningFeeSats = (picked.leg.debitSat - picked.leg.deliveredSat).toLong(), + ) + } is PaykitRoute.None -> { - toast(AppError(paykitRoute.reason)) + toast(AppError(picked.reason)) return false } - is PaykitRoute.Service -> { - val leg = paykitRoute.leg - _sendUiState.update { - it.copy( - paykitSwapRoute = route.copy(quote = null, serviceLeg = leg), - lightningFeeSats = (leg.debitSat - leg.deliveredSat).toLong(), - ) - } - return true - } // Balances changed after the contact opened: the regular flow must reopen it. is PaykitRoute.Direct -> { - _sendUiState.update { it.copy(paykitSwapRoute = null) } + _sendUiState.update { it.copy(paykitRoute = null) } toast(AppError(context.getString(R.string.common__error_body))) return false } } - _sendUiState.update { - it.copy( - paykitSwapRoute = route.copy( - quote = quote, - serviceLeg = null, - providerName = pubkySwapsRouteRepo.providerContact(quote.providerPubky)?.name, - ), - lightningFeeSats = quote.totalFeeSat.toLong(), - ) - } return true } @@ -4981,7 +4959,7 @@ class AppViewModel @Inject constructor( val fromMainScanner = isMainScanner if ( contactPaymentContext != null && - (requiresPaykitAssetSelection(contactPaymentContext) || requiresPaykitSwapRoute(contactPaymentContext)) + (requiresPaykitAssetSelection(contactPaymentContext) || requiresPaykitServiceRoute(contactPaymentContext)) ) { openPaykitContactPayment(contactPaymentContext, fromMainScanner, suppressQuickPay, walletGeneration) return@withContext @@ -5108,11 +5086,10 @@ class AppViewModel @Inject constructor( } } - private fun requiresPaykitSwapRoute(payment: ContactPaymentContext): Boolean { - if (!pubkySwapsRouteRepo.isEnabled || payment.incomingPaymentRequest != null) return false + private fun requiresPaykitServiceRoute(payment: ContactPaymentContext): Boolean { + if (!paykitRouteRepo.canRouteThroughSpark || payment.incomingPaymentRequest != null) return false if (payment.endpoints.isEmpty() || !payment.endpoints.all { it.methodId.isOnchain }) return false - val balances = walletRepo.balanceState.value - return balances.maxSendOnchainSats <= Defaults.dustLimit.toULong() && balances.maxSendLightningSats > 0uL + return walletRepo.balanceState.value.maxSendOnchainSats <= Defaults.dustLimit.toULong() } private fun requiresPaykitAssetSelection(payment: ContactPaymentContext): Boolean = @@ -6400,14 +6377,10 @@ class AppViewModel @Inject constructor( return } - _sendUiState.value.paykitSwapRoute?.serviceLeg?.let { + _sendUiState.value.paykitRoute?.serviceLeg?.let { proceedWithServiceRoutedPayment(it, contactPaymentContext, allowanceAttemptId) return } - _sendUiState.value.paykitSwapRoute?.quote?.let { - proceedWithSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId) - return - } when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> proceedWithOnchainPayment( @@ -6808,7 +6781,7 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { - val txid = pubkySwapsRouteRepo.payServiceLeg(leg).getOrElse { + val txid = paykitRouteRepo.payServiceLeg(leg).getOrElse { releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext) @@ -6826,42 +6799,6 @@ class AppViewModel @Inject constructor( ) } - private suspend fun proceedWithSwapRoutedPayment( - quote: PubkySwapRouteQuote, - contactPaymentContext: ContactPaymentContext?, - allowanceAttemptId: String?, - ) { - val payment = pubkySwapsRouteRepo.commit(quote.quoteId).getOrElse { - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) - return - } - Logger.info("Committed Pubky Swaps route '${payment.swapId}' to '${payment.destinationAddress}'", context = TAG) - // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. - lightningRepo.payInvoice(payment.invoice).getOrElse { - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) - return - } - val claimTxid = pubkySwapsRouteRepo.awaitClaim(payment.swapId).getOrElse { - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) - return - } - finishManualAllowancePayment(allowanceAttemptId, succeeded = true) - Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$claimTxid'", context = TAG) - onSendSuccess( - NewTransactionSheetDetails( - type = NewTransactionSheetType.ONCHAIN, - direction = NewTransactionSheetDirection.SENT, - paymentHashOrTxId = claimTxid, - sats = payment.deliveredSat.toLong(), - ), - ) - } - private suspend fun proceedWithLightningPayment( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, @@ -9265,7 +9202,7 @@ data class SendUiState( val fixedOnchainAmount: ULong? = null, val initialSubscriptionPaymentNeedsConfirmation: Boolean = false, val incomingPaymentRequestId: PaykitPaymentRequestId? = null, - val paykitSwapRoute: PaykitSwapRouteUi? = null, + val paykitRoute: PaykitRouteUi? = null, ) { val canSwitchBitcoinFundingSource: Boolean get() = fundingOptions.count { it.enabled && it.source != SendFundingSource.Usdt } > 1 @@ -9295,15 +9232,10 @@ data class SendUiState( !initialSubscriptionPaymentNeedsConfirmation && !requiresAmountReview } -/** - * A Paykit payment routed through a Pubky Swaps provider or a service the wallet holds a balance on: the endpoint, - * the route once quoted (a provider's quote or a service leg), and the provider's name. - */ +/** A Paykit payment routed through a service the wallet holds a balance on: the endpoint, and the leg once quoted. */ @Stable -data class PaykitSwapRouteUi( +data class PaykitRouteUi( val endpoint: PaykitEndpoint, - val quote: PubkySwapRouteQuote? = null, - val providerName: String? = null, val serviceLeg: ServiceRouteLeg? = null, ) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9e4c2f2697..f2036cbac2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1629,7 +1629,6 @@ Confirm Bitcoin Sent Route - Pubky Swaps · %1$s Spark Swipe To Pay To diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index bbeda8566a..598ff2883c 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -188,6 +188,7 @@ import to.bitkit.repositories.PaykitPaymentRequestRefreshMode import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTarget import to.bitkit.repositories.PaykitRecurrenceUnit +import to.bitkit.repositories.PaykitRouteRepo import to.bitkit.repositories.PaykitSubscription import to.bitkit.repositories.PaykitSubscriptionId import to.bitkit.repositories.PaykitSubscriptionMetadata @@ -204,7 +205,6 @@ import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyIdentityReadiness import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.PubkySignIn -import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.PublicPaykitPaymentResult import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayCompletionKind @@ -308,7 +308,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitPaymentProofRepo = mock() private val paykitPaymentRequestDiagnostics = mock() private val usdtRepo = mock() - private val pubkySwapsRouteRepo = mock() + private val paykitRouteRepo = mock() private val usdtState = MutableStateFlow(UsdtWalletState(balance = 1_000_000u)) private val paykitUsdtPayments = mock() private val samRockRepo = mock() @@ -963,7 +963,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paykitPaymentRequestDiagnostics = paykitPaymentRequestDiagnostics, refreshContactPaykitLink = refreshContactPaykitLink, usdtRepo = usdtRepo, - pubkySwapsRouteRepo = pubkySwapsRouteRepo, + paykitRouteRepo = paykitRouteRepo, paykitUsdtPayments = paykitUsdtPayments, samRockRepo = samRockRepo, appUpdateSheet = mock { on { type } doReturn TimedSheetType.APP_UPDATE }, diff --git a/changelog.d/next/1732.added.md b/changelog.d/next/1732.added.md deleted file mode 100644 index d7dfa80257..0000000000 --- a/changelog.d/next/1732.added.md +++ /dev/null @@ -1 +0,0 @@ -Bitkit can pay a contact who only accepts on-chain bitcoin from your spending balance, through a Pubky Swaps provider among your contacts. diff --git a/changelog.d/next/1754.added.md b/changelog.d/next/1754.added.md index 9dd64f6e8c..c908dc605f 100644 --- a/changelog.d/next/1754.added.md +++ b/changelog.d/next/1754.added.md @@ -1 +1 @@ -Paykit contacts who only accept on-chain bitcoin can be paid from Spark when that costs less than a swap. +Paykit contacts who only accept on-chain bitcoin can be paid from Spark. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4d039fd1e5..ca4d19f783 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,7 +21,7 @@ activity-compose = { module = "androidx.activity:activity-compose", version = "1 appcompat = { module = "androidx.appcompat:appcompat", version = "1.8.0" } 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-swaps.3" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-spark.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.86" } diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml index d2eec897a3..814c9a75d0 100644 --- a/journeys/paykit-spark-route.xml +++ b/journeys/paykit-spark-route.xml @@ -5,7 +5,7 @@ and that the contact receives the exact amount on chain. Preconditions: a dev debug build with E2E=true, E2E_BACKEND=local, E2E_HOMESERVER_PUBKY set to the local - marketplace homeserver and PUBKY_SWAPS_ROUTES=true; bitkit-docker's default stack with the marketplace and + marketplace homeserver; bitkit-docker's default stack with the marketplace and payment-requests profiles; adb reverse for 6286, 6287, 6288, 15411, 15412, 60001, 23735, 23000 and 23010. The wallet has no channels and an empty savings balance, a Spark balance of at least 25 000 sats from Lightspark's regtest faucet sent to the deposit address on the Spark screen, a Pubky profile on the local homeserver, and the diff --git a/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml deleted file mode 100644 index 5de3d268fa..0000000000 --- a/journeys/paykit-swap-route.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet that holds only a spending - balance, routes through a Pubky Swaps provider found among the user's own contacts, without the user picking a - swap, and that the contact receives the exact amount on chain. - - Preconditions: a dev debug build with E2E=true, E2E_BACKEND=local, E2E_HOMESERVER_PUBKY set to the local - marketplace homeserver and PUBKY_SWAPS_ROUTES=true; bitkit-docker's - default stack with the marketplace, payment-requests and lnurl-pay profiles; the provider running against - bitkit-docker's LND and funded; adb reverse for 6286, 6287, 6288, 15411, 15412, 60001, 23735, 23000 and 23010. - The wallet has a spending balance from an LNURL channel with bitkit-docker's LND and an empty savings balance, - a Pubky profile on the local homeserver, and both the provider's and the fixture-issuer's pubkys saved as contacts. - The contact is bitkit-docker's fixture-issuer, which publishes only a btc-regtest-p2wpkh endpoint. - - - Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 - Tap Send (tag "Send"), then Contact (tag "RecipientContact") - Verify the contact list shows both the fixture-issuer and the provider, and tap the fixture-issuer (tag "SendContact_" followed by its pubky) - Verify the amount screen (tag "send_amount_screen") offers SPENDING as the source - Enter 20000 and tap Continue (tag "ContinueAmount") - Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") - Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Pubky Swaps" followed by the provider's shortened pubky - Swipe to pay (tag "GRAB") - Once the provider logs "HTLC funded; awaiting client claim", mine one block on bitkit-docker's bitcoind - Verify the Bitcoin Sent screen (tag "SendSuccess") is visible - Verify the provider logs "client claimed; hold invoice settled", and bitcoind shows the claim transaction paying exactly 0.0002 BTC to the fixture-issuer's address - - From 26d976e72a1bd4e39329be07f2a50fff3adab373 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 22:55:59 +0100 Subject: [PATCH 03/90] fix: record spark withdrawals to contacts --- .../main/java/to/bitkit/data/CacheStore.kt | 3 + .../to/bitkit/repositories/PaykitRouteRepo.kt | 6 +- .../java/to/bitkit/repositories/SparkRepo.kt | 83 ++++++++++++++++--- .../java/to/bitkit/services/SparkService.kt | 2 + .../to/bitkit/repositories/SparkRepoTest.kt | 65 +++++++++++++++ 5 files changed, 146 insertions(+), 13 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..18433a880d 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -18,6 +18,7 @@ import to.bitkit.models.FxRate import to.bitkit.models.NewTransactionSheetDetails import to.bitkit.models.QuickPayLedger import to.bitkit.models.WalletScope +import to.bitkit.repositories.PendingSparkWithdrawal import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton @@ -169,6 +170,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(), + /** A Spark withdrawal to a Paykit contact that started, kept until Spark's payment list settles it. */ + val pendingSparkWithdrawal: PendingSparkWithdrawal? = null, ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 8f53f79df6..f2aa7a339c 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -62,9 +62,9 @@ class PaykitRouteRepo @Inject constructor( .getOrNull() } - /** Runs a service leg the router picked and returns the txid that pays the contact. */ - suspend fun payServiceLeg(leg: ServiceRouteLeg): Result = when (leg.service) { - SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat) + /** Runs a service leg the router picked to the [contact] and returns the txid that pays them. */ + suspend fun payServiceLeg(leg: ServiceRouteLeg, contact: String?): Result = when (leg.service) { + SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat, contact) else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 44793d1b22..f6a3ab72b7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -15,6 +15,7 @@ import breez_sdk_spark.SendOnchainFeeQuote import breez_sdk_spark.SendPaymentMethod import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.LightningActivity +import com.synonym.bitkitcore.OnchainActivity import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType @@ -38,6 +39,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.Serializable import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId @@ -492,17 +494,33 @@ class SparkRepo @Inject constructor( } } - /** Withdraws exactly [amountSats] to the on-chain [address] at medium speed and returns the withdrawal's txid. */ - suspend fun withdraw(address: String, amountSats: ULong): Result = withContext(bgDispatcher) { - runSuspendCatching { - val payment = sparkService.send(sparkService.prepareSend(address, amountSats)) - Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) - refresh() - (payment.details as? PaymentDetails.Withdraw)?.txId ?: payment.id - }.onFailure { - Logger.error("Failed to withdraw to a Paykit contact with Spark", it, context = TAG) + /** + * Withdraws exactly [amountSats] to a Paykit [contact]'s on-chain [address] at medium speed and returns the + * withdrawal's txid. A journal entry written before the send lets the next start settle a withdrawal the app was + * killed during, from Spark's payment list, and refuses another withdrawal until then. + */ + suspend fun withdraw(address: String, amountSats: ULong, contact: String?): Result = + withContext(bgDispatcher) { + runSuspendCatching { + if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() + val prepared = sparkService.prepareSend(address, amountSats) + val journal = PendingSparkWithdrawal(address, amountSats, contact) + cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } + val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { + // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. + runSuspendCatching { sparkService.syncWallet() }.onSuccess { syncActivities() } + throw it + } + Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) + recordActivity(payment) + runSuspendCatching { refresh() }.onFailure { + Logger.warn("Failed to refresh Spark after withdrawal '${payment.id}'", it, context = TAG) + } + (payment.details as? PaymentDetails.Withdraw)?.txId ?: payment.id + }.onFailure { + Logger.error("Failed to withdraw to a Paykit contact with Spark", it, context = TAG) + } } - } /** * Lists a deposit the app just broadcast as pending right away, then syncs so Spark sees it sooner than its @@ -736,6 +754,13 @@ class SparkRepo @Inject constructor( private suspend fun syncActivities() { sparkService.listPayments().forEach { recordActivity(it) } + // A synced list that still lacks the journaled withdrawal proves the app was killed before Spark sent it. + if (_state.value.hasSynced) { + cacheStore.data.first().pendingSparkWithdrawal?.let { journal -> + Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) + cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + } + } } private suspend fun onSdkEvent(event: SdkEvent) { @@ -771,6 +796,7 @@ class SparkRepo @Inject constructor( } private suspend fun recordActivity(payment: Payment) { + (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it) } val lightning = payment.details as? PaymentDetails.Lightning ?: return if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return @@ -805,6 +831,35 @@ class SparkRepo @Inject constructor( } } + /** + * Records a withdrawal to a Paykit contact as an on-chain send, settling the journal entry it matches. Transfers to + * Savings have no row here: the node lists their arrival as the transfer. + */ + private suspend fun recordWithdrawal(payment: Payment, withdraw: PaymentDetails.Withdraw) { + val txid = withdraw.txId + val existing = (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1 + ?.takeIf { it.txType == PaymentType.SENT } + val journal = cacheStore.data.first().pendingSparkWithdrawal?.takeIf { + it.address == withdraw.destinationAddress && it.amountSats == payment.amount.toLong().toULong() + } + if (existing == null && journal == null) return + val activity = OnchainActivity.create( + id = txid, + txType = PaymentType.SENT, + txId = txid, + value = payment.amount.toLong().toULong(), + fee = payment.fees.toLong().toULong(), + address = withdraw.destinationAddress, + timestamp = payment.timestamp, + confirmed = payment.status == PaymentStatus.COMPLETED, + doesExist = payment.status != PaymentStatus.FAILED, + contact = existing?.contact ?: journal?.contact, + seenAt = existing?.seenAt, + ) + activityRepo.get().upsertActivity(Activity.Onchain(activity)) + if (journal != null) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + } + 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 @@ -837,6 +892,14 @@ class SparkRepo @Inject constructor( private fun PrepareSendPaymentResponse.withdrawalQuote(): SendOnchainFeeQuote = (paymentMethod as SendPaymentMethod.BitcoinAddress).feeQuote +/** A withdrawal to a Paykit contact that started and that Spark's payment list has not settled yet. */ +@Serializable +data class PendingSparkWithdrawal( + val address: String, + val amountSats: ULong, + val contact: String?, +) + private class PreparedWithdrawal( val address: String, val balanceSats: ULong, diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index cef9e61f39..3c6f3d2c5c 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -296,6 +296,8 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me /** The withdrawal fee rose above the fee the user confirmed. */ class WithdrawalFeeChanged : SparkError("Spark withdrawal fee changed since it was confirmed") + class WithdrawalPending : SparkError("An earlier Spark withdrawal is still settling") + /** * 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. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2c407dd50a..7afcfd754b 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.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -238,6 +239,70 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(null, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()) } + @Test + fun `records a withdrawal to a contact with its contact and fee`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + + assertEquals("withdrawal", sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow()) + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + val onchain = assertIs(activity.firstValue).v1 + assertEquals(ActivityPaymentType.SENT, onchain.txType) + assertEquals(20_000uL, onchain.value) + assertEquals(300uL, onchain.fee) + assertEquals("pubkycontact", onchain.contact) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `refuses a withdrawal while an earlier one is unsettled`() = test { + val sut = journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + + assertIs(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `settles a journaled withdrawal from Spark's list on start`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + + journaledSpark() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `drops a journaled withdrawal Spark never sent`() = test { + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + journaledSpark() + + verify(activityRepo, never()).upsertActivity(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + private suspend fun journaledSpark(): SparkRepo { + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + return readySpark(balanceSats = 50_000uL) + } + + private fun contactWithdrawal() = sentPayment(fees = 300).copy( + id = "withdrawal-payment", + amount = BigInteger.valueOf(20_000), + method = PaymentMethod.WITHDRAW, + details = PaymentDetails.Withdraw("withdrawal", 0u, "bcrt1qcontact"), + ) + private val contactEndpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = "bcrt1qcontact") private suspend fun readySpark(balanceSats: ULong): SparkRepo { From 1cbb4b6c959a59a6ed44584a47157ba09082720e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 22:56:00 +0100 Subject: [PATCH 04/90] fix: offer spark when savings cannot pay a contact --- .../screens/wallets/send/SendConfirmScreen.kt | 2 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 22 +++++--- .../viewmodels/AppViewModelSendFlowTest.kt | 51 +++++++++++++++++++ 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 42a9841e43..bfcba46970 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -868,7 +868,7 @@ private fun LightningDetails( } } - if (uiState.paykitRoute?.serviceLeg != null) { + if (uiState.routedPaykitRoute?.serviceLeg != null) { SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { BodySSB( text = stringResource(R.string.wallet__send_swap_route_spark), diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 388003c44a..566609f5e2 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4051,8 +4051,8 @@ class AppViewModel @Inject constructor( val canUseOnchain = address.isNotEmpty() && walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) - val route = paykitServiceRoute(payment, address, canUseLightning || canUseOnchain || useUsdt) - val payMethod = if (route != null) { + val route = paykitServiceRoute(payment, address, canUseLightning || useUsdt) + val payMethod = if (route != null && !canUseOnchain) { SendMethod.LIGHTNING } else { paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) @@ -4629,7 +4629,7 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } - _sendUiState.value.paykitRoute?.let { + _sendUiState.value.routedPaykitRoute?.let { if (quotePaykitRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) return } @@ -5088,8 +5088,7 @@ class AppViewModel @Inject constructor( private fun requiresPaykitServiceRoute(payment: ContactPaymentContext): Boolean { if (!paykitRouteRepo.canRouteThroughSpark || payment.incomingPaymentRequest != null) return false - if (payment.endpoints.isEmpty() || !payment.endpoints.all { it.methodId.isOnchain }) return false - return walletRepo.balanceState.value.maxSendOnchainSats <= Defaults.dustLimit.toULong() + return payment.endpoints.isNotEmpty() && payment.endpoints.all { it.methodId.isOnchain } } private fun requiresPaykitAssetSelection(payment: ContactPaymentContext): Boolean = @@ -5730,7 +5729,10 @@ class AppViewModel @Inject constructor( return@buildList } if (state.usdtRecipient != null) add(SendFundingSource.Usdt) - if (state.isUnified || state.decodedInvoice != null || state.lnurl is LnurlParams.LnurlPay) { + if ( + state.isUnified || state.decodedInvoice != null || state.lnurl is LnurlParams.LnurlPay || + state.paykitRoute != null + ) { add( SendFundingSource.Spending ) @@ -6377,7 +6379,7 @@ class AppViewModel @Inject constructor( return } - _sendUiState.value.paykitRoute?.serviceLeg?.let { + _sendUiState.value.routedPaykitRoute?.serviceLeg?.let { proceedWithServiceRoutedPayment(it, contactPaymentContext, allowanceAttemptId) return } @@ -6781,7 +6783,7 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { - val txid = paykitRouteRepo.payServiceLeg(leg).getOrElse { + val txid = paykitRouteRepo.payServiceLeg(leg, contactPaymentContext?.publicKey).getOrElse { releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext) @@ -9204,6 +9206,10 @@ data class SendUiState( val incomingPaymentRequestId: PaykitPaymentRequestId? = null, val paykitRoute: PaykitRouteUi? = null, ) { + /** The Paykit route this payment takes: offered routes run only while Spending is the source. */ + val routedPaykitRoute: PaykitRouteUi? + get() = paykitRoute?.takeIf { payMethod == SendMethod.LIGHTNING } + val canSwitchBitcoinFundingSource: Boolean get() = fundingOptions.count { it.enabled && it.source != SendFundingSource.Usdt } > 1 diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 598ff2883c..9f17d409c7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -21,7 +21,9 @@ import com.synonym.bitkitcore.LnurlAddressData import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.NetworkType import com.synonym.bitkitcore.OnChainInvoice +import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.Scanner +import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.UsdtDestination import com.synonym.bitkitcore.UsdtException import com.synonym.bitkitcore.UsdtPaymentRequest @@ -11974,6 +11976,55 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo).consumePrivatePaymentList(contactKey, privateContext) } + @Test + fun `spark route pays the contact while spending is the source`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(paykitRouteRepo.payServiceLeg(leg, "pubkycontact")).thenReturn(Result.success("txid")) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(leg.endpoint, leg), + ), + ) + + confirmCurrentPayment() + + verify(paykitRouteRepo).payServiceLeg(leg, "pubkycontact") + } + + @Test + fun `spark route stays unused once savings is the source`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + stubSuccessfulOnchainSend(leg.endpoint.value, leg.deliveredSat) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(leg.endpoint, leg), + ), + ) + + confirmCurrentPayment() + + verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull()) + } + + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( + service = "spark", + endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), + deliveredSat = 1_000uL, + debitSat = 1_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + @Test fun `incoming payment request consumes its private list before it is accepted`() = test { val address = "bcrt1qpaymentrequest" From bd755b83995d61f2c8c492dc1be94d3926edbe26 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 23:42:42 +0100 Subject: [PATCH 05/90] feat: route every contact payment through the paykit router --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 5 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 127 ++++++++++++------ .../viewmodels/AppViewModelSendFlowTest.kt | 95 ++++++++++++- 3 files changed, 185 insertions(+), 42 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index f2aa7a339c..09cfb2a102 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -39,6 +39,7 @@ class PaykitRouteRepo @Inject constructor( endpoints: List, lightningSpendableSats: ULong, onchainSpendableSats: ULong, + quoteServiceLegs: Boolean, ): Result = withContext(ioDispatcher) { runSuspendCatching { paykitRoutePayment( @@ -47,7 +48,7 @@ class PaykitRouteRepo @Inject constructor( contactEndpoints = endpoints, lightningSpendableSat = lightningSpendableSats, onchainSpendableSat = onchainSpendableSats, - serviceLegs = serviceLegs(endpoints, amountSats), + serviceLegs = if (quoteServiceLegs) serviceLegs(endpoints, amountSats) else emptyList(), ), network = Env.network.toCoreNetwork(), ) @@ -56,7 +57,7 @@ class PaykitRouteRepo @Inject constructor( /** Spark withdrawals to the contact's on-chain endpoints, each quoted with its fee. */ private suspend fun serviceLegs(endpoints: List, amountSats: ULong): List = - endpoints.mapNotNull { endpoint -> + endpoints.filter { MethodId.fromRawValue(it.methodId)?.isOnchain == true }.mapNotNull { endpoint -> sparkRepo.withdrawalRouteLeg(endpoint, amountSats) .onFailure { Logger.warn("No Spark route to '${endpoint.methodId}'", it, context = TAG) } .getOrNull() diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 566609f5e2..ff69031a1d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4051,8 +4051,13 @@ class AppViewModel @Inject constructor( val canUseOnchain = address.isNotEmpty() && walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) - val route = paykitServiceRoute(payment, address, canUseLightning || useUsdt) - val payMethod = if (route != null && !canUseOnchain) { + val offersSparkLeg = offersSparkLeg(payment, address, canUseLightning || useUsdt) + val route = PaykitRouteUi( + endpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } + .map { PaykitEndpoint(methodId = it.methodId.rawValue, value = it.value) }, + offersSparkLeg = offersSparkLeg, + ).takeIf { it.endpoints.isNotEmpty() } + val payMethod = if (offersSparkLeg && !canUseOnchain) { SendMethod.LIGHTNING } else { paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) @@ -4197,15 +4202,9 @@ class AppViewModel @Inject constructor( return !canUseBitcoin && balance > 0u } - private fun paykitServiceRoute( - payment: ContactPaymentContext, - address: String, - canPayDirectly: Boolean, - ): PaykitRouteUi? { - if (!paykitRouteRepo.canRouteThroughSpark || canPayDirectly || address.isEmpty()) return null - if (payment.incomingPaymentRequest != null) return null - val methodId = payment.endpoints.firstOrNull { it.methodId.isOnchain }?.methodId ?: return null - return PaykitRouteUi(endpoint = PaykitEndpoint(methodId = methodId.rawValue, value = address)) + private fun offersSparkLeg(payment: ContactPaymentContext, address: String, canPayDirectly: Boolean): Boolean { + if (!paykitRouteRepo.canRouteThroughSpark || canPayDirectly || address.isEmpty()) return false + return payment.incomingPaymentRequest == null && payment.endpoints.any { it.methodId.isOnchain } } private fun canFundPaykitLightning(invoice: LightningInvoice?, lnurl: LnurlParams.LnurlPay?): Boolean { @@ -4629,9 +4628,15 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } - _sendUiState.value.routedPaykitRoute?.let { - if (quotePaykitRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) - return + _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + when (routePaykitPayment(it)) { + PaykitRouteOutcome.Leg -> { + setSendEffect(SendEffect.NavigateToConfirm) + return + } + PaykitRouteOutcome.Refused -> return + PaykitRouteOutcome.Direct -> Unit + } } _sendUiState.update { it.copy(isLoading = true) } @@ -4647,39 +4652,73 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) } - private suspend fun quotePaykitRoute(route: PaykitRouteUi): Boolean { + /** + * Asks bitkit-core's router how to pay the contact from the selected source: Spending offers every endpoint and a + * Spark leg to on-chain ones, Savings only the on-chain endpoints. Direct pays the endpoint it names. + */ + private suspend fun routePaykitPayment(route: PaykitRouteUi): PaykitRouteOutcome { + val state = _sendUiState.value + val fromSpending = state.payMethod == SendMethod.LIGHTNING _sendUiState.update { it.copy(isLoading = true) } val result = paykitRouteRepo.route( - amountSats = _sendUiState.value.amount, - endpoints = listOf(route.endpoint), - lightningSpendableSats = maxSendableLightningSats(), - onchainSpendableSats = walletRepo.balanceState.value.maxSendOnchainSats, + amountSats = state.amount, + endpoints = if (fromSpending) route.endpoints else route.endpoints.filter { it.isOnchain() }, + lightningSpendableSats = if (fromSpending) maxSendableLightningSats() else 0uL, + onchainSpendableSats = if (fromSpending) 0uL else walletRepo.balanceState.value.maxSendOnchainSats, + quoteServiceLegs = fromSpending && route.offersSparkLeg, ) _sendUiState.update { it.copy(isLoading = false) } val picked = result.getOrElse { Logger.error("Failed to route Paykit payment", it, context = TAG) toast(it) - return false + return PaykitRouteOutcome.Refused } - when (picked) { - is PaykitRoute.Service -> _sendUiState.update { - it.copy( - paykitRoute = route.copy(serviceLeg = picked.leg), - lightningFeeSats = (picked.leg.debitSat - picked.leg.deliveredSat).toLong(), - ) + return when (picked) { + is PaykitRoute.Direct -> { + payDirectEndpoint(route, picked.endpoint) + PaykitRouteOutcome.Direct + } + is PaykitRoute.Service -> { + _sendUiState.update { + it.copy( + paykitRoute = route.copy(serviceLeg = picked.leg), + lightningFeeSats = (picked.leg.debitSat - picked.leg.deliveredSat).toLong(), + ) + } + PaykitRouteOutcome.Leg } is PaykitRoute.None -> { - toast(AppError(picked.reason)) - return false + _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__error_sending_title), + description = picked.reason, + ) + PaykitRouteOutcome.Refused } - // Balances changed after the contact opened: the regular flow must reopen it. - is PaykitRoute.Direct -> { - _sendUiState.update { it.copy(paykitRoute = null) } - toast(AppError(context.getString(R.string.common__error_body))) - return false + } + } + + private fun payDirectEndpoint(route: PaykitRouteUi, endpoint: PaykitEndpoint) { + _sendUiState.update { + when { + endpoint.isOnchain() -> it.copy( + payMethod = SendMethod.ONCHAIN, + address = endpoint.value, + paykitRoute = route.copy(serviceLeg = null), + ) + endpoint.methodId == MethodId.Lnurl.rawValue -> it.copy( + payMethod = SendMethod.LIGHTNING, + decodedInvoice = null, + paykitRoute = route.copy(serviceLeg = null), + ) + else -> it.copy( + payMethod = SendMethod.LIGHTNING, + lnurl = null, + paykitRoute = route.copy(serviceLeg = null), + ) } } - return true } private suspend fun reviewPaykitAmount(navigateToUsdtReview: Boolean = true): Boolean { @@ -5731,7 +5770,7 @@ class AppViewModel @Inject constructor( if (state.usdtRecipient != null) add(SendFundingSource.Usdt) if ( state.isUnified || state.decodedInvoice != null || state.lnurl is LnurlParams.LnurlPay || - state.paykitRoute != null + state.paykitRoute?.offersSparkLeg == true ) { add( SendFundingSource.Spending @@ -9206,10 +9245,14 @@ data class SendUiState( val incomingPaymentRequestId: PaykitPaymentRequestId? = null, val paykitRoute: PaykitRouteUi? = null, ) { - /** The Paykit route this payment takes: offered routes run only while Spending is the source. */ + /** The Paykit route this payment takes: a Spark leg runs only while Spending is the source. */ val routedPaykitRoute: PaykitRouteUi? get() = paykitRoute?.takeIf { payMethod == SendMethod.LIGHTNING } + /** Whether bitkit-core's router picks how this contact payment is paid; USDT and hardware wallets pay as picked. */ + val routesPaykitPayment: Boolean + get() = !paykitUsesUsdt && hardwareWalletId == null && lnurl !is LnurlParams.LnurlWithdraw + val canSwitchBitcoinFundingSource: Boolean get() = fundingOptions.count { it.enabled && it.source != SendFundingSource.Usdt } > 1 @@ -9238,13 +9281,21 @@ data class SendUiState( !initialSubscriptionPaymentNeedsConfirmation && !requiresAmountReview } -/** A Paykit payment routed through a service the wallet holds a balance on: the endpoint, and the leg once quoted. */ +/** + * A contact payment bitkit-core's router picks the way for: the contact's bitcoin endpoints, whether a Spark leg may + * reach its on-chain ones, and the leg once the router picked one. + */ @Stable data class PaykitRouteUi( - val endpoint: PaykitEndpoint, + val endpoints: List, + val offersSparkLeg: Boolean = false, val serviceLeg: ServiceRouteLeg? = null, ) +private enum class PaykitRouteOutcome { Direct, Leg, Refused } + +private fun PaykitEndpoint.isOnchain(): Boolean = MethodId.fromRawValue(methodId)?.isOnchain == true + @Immutable data class OnchainFeeUi( val rate: FeeRate = FeeRate.fromSpeed(TransactionSpeed.default()), diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 9f17d409c7..d67549be15 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -22,6 +22,7 @@ import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.NetworkType import com.synonym.bitkitcore.OnChainInvoice import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.Scanner import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.UsdtDestination @@ -11986,7 +11987,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { address = leg.endpoint.value, amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(leg.endpoint, leg), + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12007,7 +12008,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - paykitRoute = PaykitRouteUi(leg.endpoint, leg), + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12016,6 +12017,96 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull()) } + @Test + fun `router direct pays the lightning endpoint it picks`() = test { + val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + setSendState( + SendUiState( + amount = 1_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(bolt11, onchain)), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(paykitRouteRepo).route(eq(1_000uL), eq(listOf(bolt11, onchain)), any(), eq(0uL), eq(false)) + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + } + + @Test + fun `router direct pays the onchain endpoint it picks from savings`() = test { + val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = REGTEST_ADDRESS) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(onchain))) + setSendState( + SendUiState( + amount = 1_000u, + payMethod = SendMethod.ONCHAIN, + paykitRoute = PaykitRouteUi(listOf(bolt11, onchain)), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(paykitRouteRepo).route(eq(1_000uL), eq(listOf(onchain)), eq(0uL), eq(100_000uL), eq(false)) + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + assertEquals(REGTEST_ADDRESS, sut.sendUiState.value.address) + } + + @Test + fun `router service leg opens the confirm screen with the leg's fee`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + setSendState( + SendUiState( + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals(300L, sut.sendUiState.value.lightningFeeSats) + } + verify(paykitRouteRepo).route(eq(leg.deliveredSat), eq(listOf(leg.endpoint)), any(), eq(0uL), eq(true)) + } + + @Test + fun `router none keeps the amount screen open`() = test { + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Nothing can pay this contact"))) + setSendState( + SendUiState( + amount = 1_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(onchain), offersSparkLeg = true), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + expectNoEvents() + } + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + } + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( service = "spark", endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), From a792f949ca598bc749d7fddc19b4d027b1009ef8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 23:50:00 +0100 Subject: [PATCH 06/90] fix: show the app's copy when no route pays a contact --- app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 6 ++++-- .../java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt | 6 ++++++ 2 files changed, 10 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 ff69031a1d..abaf955f04 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4688,11 +4688,13 @@ class AppViewModel @Inject constructor( PaykitRouteOutcome.Leg } is PaykitRoute.None -> { + Logger.warn("Found no Paykit route: '${picked.reason}'", context = TAG) _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } toast( type = Toast.ToastType.ERROR, - title = context.getString(R.string.wallet__error_sending_title), - description = picked.reason, + title = context.getString(R.string.wallet__send_amount_exceeded__title), + description = context.getString(R.string.wallet__send_amount_exceeded__description), + testTag = "PaykitRouteNoneToast", ) PaykitRouteOutcome.Refused } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d67549be15..eab741e362 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12105,6 +12105,12 @@ class AppViewModelSendFlowTest : BaseUnitTest() { expectNoEvents() } assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + verify(toastManager).enqueue( + check { + assertEquals("PaykitRouteNoneToast", it.testTag) + assertFalse(it.description.orEmpty().contains("Nothing can pay this contact")) + }, + ) } private fun sparkRouteLeg(address: String) = ServiceRouteLeg( From b37ea91a2849d167dee82e3dce839f6a04364a5a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 23:57:44 +0100 Subject: [PATCH 07/90] fix: tell an unpayable contact from a short balance --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 26 ++++++++++++--- app/src/main/res/values/strings.xml | 2 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 32 +++++++++++++++---- 3 files changed, 48 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index abaf955f04..c58002928a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4659,12 +4659,14 @@ class AppViewModel @Inject constructor( private suspend fun routePaykitPayment(route: PaykitRouteUi): PaykitRouteOutcome { val state = _sendUiState.value val fromSpending = state.payMethod == SendMethod.LIGHTNING + val lightningSpendable = if (fromSpending) maxSendableLightningSats() else 0uL + val onchainSpendable = if (fromSpending) 0uL else walletRepo.balanceState.value.maxSendOnchainSats _sendUiState.update { it.copy(isLoading = true) } val result = paykitRouteRepo.route( amountSats = state.amount, endpoints = if (fromSpending) route.endpoints else route.endpoints.filter { it.isOnchain() }, - lightningSpendableSats = if (fromSpending) maxSendableLightningSats() else 0uL, - onchainSpendableSats = if (fromSpending) 0uL else walletRepo.balanceState.value.maxSendOnchainSats, + lightningSpendableSats = lightningSpendable, + onchainSpendableSats = onchainSpendable, quoteServiceLegs = fromSpending && route.offersSparkLeg, ) _sendUiState.update { it.copy(isLoading = false) } @@ -4690,11 +4692,25 @@ class AppViewModel @Inject constructor( is PaykitRoute.None -> { Logger.warn("Found no Paykit route: '${picked.reason}'", context = TAG) _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } + // The router's reason is English for the log: the app tells a short balance from an unusable contact. + val isBalanceShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() toast( type = Toast.ToastType.ERROR, - title = context.getString(R.string.wallet__send_amount_exceeded__title), - description = context.getString(R.string.wallet__send_amount_exceeded__description), - testTag = "PaykitRouteNoneToast", + title = context.getString( + if (isBalanceShort) { + R.string.wallet__send_amount_exceeded__title + } else { + R.string.wallet__send_paykit_no_route__title + } + ), + description = context.getString( + if (isBalanceShort) { + R.string.wallet__send_amount_exceeded__description + } else { + R.string.wallet__send_paykit_no_route__description + } + ), + testTag = if (isBalanceShort) "PaykitRouteBalanceToast" else "PaykitRouteNoneToast", ) PaykitRouteOutcome.Refused } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f2036cbac2..c87d201f90 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1602,6 +1602,8 @@ Invoice expiration The maximum spendable amount is a bit lower due to a required reserve balance. Reserve Balance + This contact has no payment method Bitkit can use right now. + Can\'t pay this contact Cancel expired payment Checking the network. This can take up to 30 seconds. Payment cancelled. Its coins are back in your wallet. diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index eab741e362..3d5020d779 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12086,8 +12086,32 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `router none keeps the amount screen open`() = test { + fun `router none with a short balance says the balance is short`() = test { + routerNone(maxSendLightningSats = 500u) + + verify(toastManager).enqueue( + check { + assertEquals("PaykitRouteBalanceToast", it.testTag) + assertFalse(it.description.orEmpty().contains("Nothing can pay this contact")) + }, + ) + } + + @Test + fun `router none with enough balance says the contact cannot be paid`() = test { + routerNone(maxSendLightningSats = 100_000u) + + verify(toastManager).enqueue( + check { + assertEquals("PaykitRouteNoneToast", it.testTag) + assertFalse(it.description.orEmpty().contains("Nothing can pay this contact")) + }, + ) + } + + private suspend fun TestScope.routerNone(maxSendLightningSats: ULong) { val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + balanceState.value = BalanceState(maxSendLightningSats = maxSendLightningSats) whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) .thenReturn(Result.success(PaykitRoute.None("Nothing can pay this contact"))) setSendState( @@ -12105,12 +12129,6 @@ class AppViewModelSendFlowTest : BaseUnitTest() { expectNoEvents() } assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) - verify(toastManager).enqueue( - check { - assertEquals("PaykitRouteNoneToast", it.testTag) - assertFalse(it.description.orEmpty().contains("Nothing can pay this contact")) - }, - ) } private fun sparkRouteLeg(address: String) = ServiceRouteLeg( From 25b40e0fd082fe11a2dee13df34bc700363afd5b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 00:32:40 +0100 Subject: [PATCH 08/90] chore: move to bitkit-core 0.8.0-spark.3 --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ca4d19f783..5cec230e1f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,7 +21,7 @@ activity-compose = { module = "androidx.activity:activity-compose", version = "1 appcompat = { module = "androidx.appcompat:appcompat", version = "1.8.0" } 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-spark.2" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-spark.3" } 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.86" } From 964218cf324f0a47695a6582ab019872f8f554e2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 01:44:31 +0100 Subject: [PATCH 09/90] chore: translate the no-route copy --- app/src/main/res/values-ar/strings.xml | 2 ++ app/src/main/res/values-b+es+419/strings.xml | 2 ++ app/src/main/res/values-ca/strings.xml | 2 ++ app/src/main/res/values-cs/strings.xml | 2 ++ app/src/main/res/values-de/strings.xml | 2 ++ app/src/main/res/values-el/strings.xml | 2 ++ app/src/main/res/values-es-rES/strings.xml | 2 ++ app/src/main/res/values-es/strings.xml | 2 ++ app/src/main/res/values-fr/strings.xml | 2 ++ app/src/main/res/values-it/strings.xml | 2 ++ app/src/main/res/values-nl/strings.xml | 2 ++ app/src/main/res/values-pl/strings.xml | 2 ++ app/src/main/res/values-pt-rBR/strings.xml | 2 ++ app/src/main/res/values-pt/strings.xml | 2 ++ app/src/main/res/values-ru/strings.xml | 2 ++ 15 files changed, 30 insertions(+) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 889d126beb..c16a364722 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1024,6 +1024,8 @@ انتهاء صلاحية الفاتورة الحد الأقصى القابل للإنفاق أقل قليلاً بسبب الرصيد الاحتياطي المطلوب. الرصيد الاحتياطي + ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ Bitkit استخدامها الآن. + لا يمكن الدفع لجهة الاتصال هذه لم تعد التحويلات إلى رصيد الإنفاق متاحة. يتحقق Bitkit أولًا من الشبكة، ثم يعيد عملات هذا التحويل إلى محفظتك حتى لا يتأكد التحويل الأصلي أبدًا. يكلّف ذلك رسوم شبكة. QuickPay جارٍ دفع\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 bfd700f18c..51fb61fc1a 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1055,6 +1055,8 @@ Expiración de la factura La cantidad máxima que se puede gastar es un poco más baja debido al saldo de reserva exigido. Saldo de reserva + Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. + No se puede pagar a este contacto Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero revisa la red y luego devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit. Pago pendiente diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 2e238ad0cb..8ab700d307 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1049,6 +1049,8 @@ Caducitat de la factura L\'import màxim gastable és una mica inferior a causa d\'un saldo de reserva requerit. Saldo de reserva + Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara. + No es pot pagar aquest contacte Les transferències al saldo de despesa ja no estan disponibles. Bitkit primer comprova la xarxa i després retorna les monedes d\'aquesta transferència a la teva cartera perquè la transferència original no es pugui confirmar mai. Això té una comissió de xarxa. Pagament pendent QuickPay diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index cd260eac5c..9b2889fabd 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1053,6 +1053,8 @@ Expirace faktury Maximální částka, kterou lze utratit, je o něco nižší kvůli požadovanému zůstatku rezervy. Zůstatek rezervy + Tento kontakt nemá žádnou platební metodu, kterou by Bitkit mohl nyní použít. + Tomuto kontaktu nelze zaplatit Převody na útratový zůstatek už nejsou dostupné. Bitkit nejprve zkontroluje síť a pak vrátí mince tohoto převodu do vaší peněženky, aby se původní převod nikdy nepotvrdil. Stojí to síťový poplatek. Tato platba trvá o něco déle, než se očekávalo. Bitkit můžete používat i nadále. Platba čeká na vyřízení diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 7cc64bff3a..ac9125c43d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -888,6 +888,8 @@ Senden Empfangen Bitcoin senden + Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann. + Zahlung an diesen Kontakt nicht möglich Überweisungen auf dein Ausgabenguthaben sind nicht mehr verfügbar. Bitkit prüft zuerst das Netzwerk und schickt die Coins dieser Überweisung dann zurück in deine Wallet, damit die ursprüngliche Überweisung nie bestätigt wird. Dafür fällt eine Netzwerkgebühr an. An Kontakt diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 8ef689b6bc..f6ab1e1a5c 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1029,6 +1029,8 @@ Λήξη τιμολογίου Το μέγιστο δαπανήσιμο ποσό είναι λίγο χαμηλότερο λόγω απαιτούμενου αποθεματικού υπολοίπου. Αποθεματικό υπόλοιπο + Αυτή η επαφή δεν έχει τρόπο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit αυτή τη στιγμή. + Δεν είναι δυνατή η πληρωμή αυτής της επαφής Οι μεταφορές στο υπόλοιπο δαπανών δεν είναι πλέον διαθέσιμες. Το Bitkit ελέγχει πρώτα το δίκτυο και μετά επιστρέφει τα νομίσματα αυτής της μεταφοράς στο πορτοφόλι σας, ώστε η αρχική μεταφορά να μην επιβεβαιωθεί ποτέ. Αυτό έχει χρέωση δικτύου. QuickPay Πληρωμή\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 5e7d939b47..9446b587d7 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1050,6 +1050,8 @@ Expiración de la factura La cantidad máxima gastable es un poco menor debido a un saldo de reserva requerido. Saldo de reserva + Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. + No se puede pagar a este contacto Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. QuickPay Pagando\n<accent>factura...</accent> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 5a951c0351..c062bf3ee8 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -886,6 +886,8 @@ Recibir Transferencia Entrante: Enviar Bitcoin + Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. + No se puede pagar a este contacto Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Para Contactar diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index ab176608f2..5a8d811da3 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -889,6 +889,8 @@ Envoyer Recevoir Envoyer des bitcoins + Ce contact n\'a aucun moyen de paiement que Bitkit peut utiliser pour le moment. + Impossible de payer ce contact Les transferts vers le solde de dépenses ne sont plus disponibles. Bitkit vérifie d\'abord le réseau, puis renvoie les pièces de ce transfert vers votre portefeuille afin que le transfert d\'origine ne soit jamais confirmé. Cela coûte des frais de réseau. Pour Contact diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 07f846d862..39b64bf1bb 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1051,6 +1051,8 @@ Scadenza invoice L\'importo massimo spendibile e\' leggermente inferiore a causa di un saldo di riserva richiesto. Saldo di Riserva + Questo contatto non ha alcun metodo di pagamento che Bitkit possa usare ora. + Impossibile pagare questo contatto I trasferimenti al saldo di spesa non sono più disponibili. Bitkit controlla prima la rete, poi rimanda le monete di questo trasferimento al tuo wallet, così il trasferimento originale non potrà mai essere confermato. Questo costa una commissione di rete. Questo pagamento sta richiedendo un po\' più tempo del previsto. Puoi continuare a utilizzare Bitkit. Pagamento in sospeso diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 47b97fd1f4..b98af661c2 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1046,6 +1046,8 @@ Factuutvervaldatum Het maximaal te besteden bedrag is iets lager vanwege een vereist reservesaldo. Reservesaldo + Dit contact heeft nu geen betaalmethode die Bitkit kan gebruiken. + Kan dit contact niet betalen Overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Bitkit controleert eerst het netwerk en stuurt de munten van deze overboeking dan terug naar je wallet, zodat de oorspronkelijke overboeking nooit bevestigd wordt. Dit kost netwerkkosten. Deze betaling duurt iets langer dan verwacht. U kunt Bitkit blijven gebruiken. Betaling Onderweg diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 8c4d7936ca..ed01fb20a6 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -891,6 +891,8 @@ Wyślij Otrzymaj Wyślij Bitcoin + Ten kontakt nie ma teraz metody płatności, której Bitkit może użyć. + Nie można zapłacić temu kontaktowi Przelewy na saldo wydatków nie są już dostępne. Bitkit najpierw sprawdza sieć, a potem odsyła monety z tego przelewu do Twojego portfela, aby pierwotny przelew nigdy nie został potwierdzony. Wiąże się to z opłatą sieciową. Do Kontakt diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 9bcaeb96bc..0ca1d6d838 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1055,6 +1055,8 @@ Vencimento do invoice O valor máximo utilizável é um pouco menor devido a um saldo de reserva obrigatório. Saldo de reserva + Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora. + Não é possível pagar este contato As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. Pagamento Pendente diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index afa053a8b0..03f42bc285 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -755,6 +755,8 @@ Enviar Receber Enviar Bitcoin + Este contacto não tem nenhum método de pagamento que a Bitkit possa usar agora. + Não é possível pagar a este contacto As transferências para o saldo de gastos já não estão disponíveis. A Bitkit verifica primeiro a rede e depois devolve as moedas desta transferência à sua carteira, para que a transferência original nunca seja confirmada. Isto tem uma taxa de rede. Para Contato diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index ff127bcf31..6d64ceeca1 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1070,6 +1070,8 @@ Срок действия инвойса Максимальная сумма для траты немного меньше из-за необходимого резервного баланса. Резервный баланс + У этого контакта сейчас нет способа оплаты, который может использовать Bitkit. + Невозможно оплатить этому контакту Переводы на баланс расходов больше недоступны. Bitkit сначала проверяет сеть, а затем возвращает монеты этого перевода в ваш кошелёк, чтобы исходный перевод никогда не подтвердился. За это взимается сетевая комиссия. Этот платеж занимает больше времени, чем ожидалось. Вы можете продолжать использовать Bitkit. Платеж в ожидании From 47a1484a88b3ee07edea75e04d4af1487ba73615 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 01:44:31 +0100 Subject: [PATCH 10/90] feat: pay payment requests from spark through the router --- .../to/bitkit/repositories/LightningRepo.kt | 4 + .../repositories/PaykitPaymentProofRepo.kt | 89 ++++++++++++++- .../to/bitkit/repositories/PaykitRouteRepo.kt | 13 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 30 ++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 71 ++++++++++-- .../PaykitPaymentProofRepoTest.kt | 58 ++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 44 ++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 107 +++++++++++++++++- 8 files changed, 395 insertions(+), 21 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..f14b2310cc 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2331,6 +2331,10 @@ class LightningRepo @Inject constructor( } } + /** The txid of Spark's withdrawal of exactly [amountSats] to [address], once Spark lists it. */ + suspend fun sparkWithdrawalTxid(address: String, amountSats: ULong): String? = + sparkRepo.withdrawalTxid(address, amountSats) + /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index c759ca37f7..b4ea5b67da 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -108,6 +108,8 @@ data class PendingPaykitPaymentProof( val previousPrivatePaymentListVersion: ULong? = null, /** Set only for an automatic Allowance payment, from its submitted attempt. Manual payments omit it. */ val allowanceId: String? = null, + /** An on-chain payment sent as a Spark withdrawal, settled from Spark's payment list instead of the node's. */ + val sparkWithdrawal: Boolean = false, ) data class PaykitOnchainPaymentProofResolution( @@ -297,6 +299,45 @@ class PaykitPaymentProofRepo @Inject constructor( privatePaymentListVersion: ULong? = null, signedTx: HwFundingSignedTx? = null, previousPrivatePaymentListVersion: ULong? = null, + ): Result = markOnchainStarted( + request = request, + address = address, + amountSats = amountSats, + walletId = walletId, + privatePaymentListVersion = privatePaymentListVersion, + signedTx = signedTx, + previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, + sparkWithdrawal = false, + ) + + /** Marks the on-chain proof of [request] started for a Spark withdrawal of [amountSats] to [address]. */ + suspend fun markSparkOnchainPaymentStarted( + request: PaykitPaymentRequest, + address: String, + amountSats: ULong, + privatePaymentListVersion: ULong? = null, + previousPrivatePaymentListVersion: ULong? = null, + ): Result = markOnchainStarted( + request = request, + address = address, + amountSats = amountSats, + walletId = WalletScope.default, + privatePaymentListVersion = privatePaymentListVersion, + signedTx = null, + previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, + sparkWithdrawal = true, + ) + + @Suppress("LongParameterList") + private suspend fun markOnchainStarted( + request: PaykitPaymentRequest, + address: String, + amountSats: ULong, + walletId: String, + privatePaymentListVersion: ULong?, + signedTx: HwFundingSignedTx?, + previousPrivatePaymentListVersion: ULong?, + sparkWithdrawal: Boolean, ): Result = withContext(ioDispatcher) { runSuspendCatching { val identity = currentIdentity() ?: throw PaykitPaymentRequestError.RequestUnavailable @@ -336,12 +377,52 @@ class PaykitPaymentProofRepo @Inject constructor( hardwareFeeRate = signedTx?.feeRate, hardwareTotalSpent = signedTx?.totalSpent, hardwareDispatchAttempted = signedTx?.let { false }, + sparkWithdrawal = sparkWithdrawal, ) persist(proofs) } }.onFailure { Logger.warn("Failed to mark a Paykit on-chain payment as started", it, context = TAG) } } + /** Completes the started proof of [request] paid by the Spark withdrawal [txid] and delivers it. */ + suspend fun completeSparkOnchainPayment(request: PaykitPaymentRequest, txid: String): Boolean = + withContext(ioDispatcher) { + if (!txid.isHex(HASH_BYTE_COUNT)) return@withContext false + val identity = currentIdentity() ?: return@withContext false + runSuspendCatching { + operationMutex.withLock { + val proof = loadProofs().lastOrNull { + PubkyPublicKeyFormat.matches(it.identity, identity) && it.requestId == request.id && + it.sparkWithdrawal && it.paymentStarted && it.proofData == null + } ?: return@withLock false + completeSparkOnchainProofLocked(proof, txid) + } + }.onFailure { + Logger.warn("Failed to complete a Paykit proof for a Spark withdrawal", it, context = TAG) + }.getOrDefault(false) + } + + private suspend fun reconcileSparkOnchainProof(proof: PendingPaykitPaymentProof): Boolean { + if (!proof.paymentStarted || proof.proofData != null) return false + val address = proof.onchainAddress ?: return false + val amount = proof.onchainAmountSats ?: return false + val txid = lightningRepo.sparkWithdrawalTxid(address, amount) ?: return false + return completeSparkOnchainProofLocked(proof, txid) + } + + private suspend fun completeSparkOnchainProofLocked(proof: PendingPaykitPaymentProof, txid: String): Boolean { + val proofs = loadProofs().toMutableList() + val index = proofs.indexOf(proof) + if (index < 0) return false + val completed = proof.copy( + paymentIdentifier = txid.lowercase(), + proofData = txid.lowercase(), + onchainAcceptanceVerified = true, + ) + proofs[index] = completed + return persistAndSubmit(listOf(completed), proofs) + } + suspend fun completeLightningPayment(paymentHash: String, preimage: String?) = withContext(ioDispatcher) { if (preimage == null) return@withContext if (!preimage.matchesPaymentHash(paymentHash)) { @@ -1182,7 +1263,10 @@ class PaykitPaymentProofRepo @Inject constructor( }.getOrElse { return@withContext } if (snapshot.isEmpty()) return@withContext finishDeniedHardwarePreparations(snapshot) - snapshot.filter { it.kind == PaykitPaymentProofKind.Onchain && it.onchainWalletId == WalletScope.default } + snapshot.filter { + it.kind == PaykitPaymentProofKind.Onchain && it.onchainWalletId == WalletScope.default && + !it.sparkWithdrawal + } .forEach { proof -> val txid = proof.proofData ?: attempt?.txid val validCompletedProof = proof.paymentStarted && proof.proofData?.isHex(HASH_BYTE_COUNT) == true && @@ -1250,6 +1334,9 @@ class PaykitPaymentProofRepo @Inject constructor( activityReady: Boolean, ): Boolean { if (proof.hardwareDispatchDenied) return false + if (proof.sparkWithdrawal) { + return if (proof.proofData != null) submitReady(proof) else reconcileSparkOnchainProof(proof) + } if (proof.kind == PaykitPaymentProofKind.Onchain && proof.onchainWalletId == WalletScope.default && !activityReady ) { diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 09cfb2a102..2aa917c903 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -63,9 +63,16 @@ class PaykitRouteRepo @Inject constructor( .getOrNull() } - /** Runs a service leg the router picked to the [contact] and returns the txid that pays them. */ - suspend fun payServiceLeg(leg: ServiceRouteLeg, contact: String?): Result = when (leg.service) { - SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat, contact) + /** + * Runs a service leg the router picked to the [contact] and returns the txid that pays them; [onBeforeSend] runs + * once the leg is prepared, right before it sends. + */ + suspend fun payServiceLeg( + leg: ServiceRouteLeg, + contact: String?, + onBeforeSend: suspend () -> Boolean = { true }, + ): Result = when (leg.service) { + SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat, contact, onBeforeSend) else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ed6bf6b6bc..5caf318c33 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -484,7 +484,9 @@ class SparkRepo @Inject constructor( if (!canSend(amountSats)) return@runSuspendCatching null val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote - val debitSats = amountSats + quote.speedMedium.userFeeSat + // Spark charges its fee and the L1 broadcast fee on top of what reaches the contact. + val speed = quote.speedMedium + val debitSats = amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() if (quote.isEstimate || !canSend(debitSats)) return@runSuspendCatching null ServiceRouteLeg( service = ROUTE_SERVICE, @@ -497,16 +499,34 @@ class SparkRepo @Inject constructor( } } + /** The txid of a withdrawal Spark sent of exactly [amountSats] to [address], once Spark's synced list holds it. */ + suspend fun withdrawalTxid(address: String, amountSats: ULong): String? = withContext(bgDispatcher) { + if (!_state.value.hasSynced) return@withContext null + sparkService.listPayments().firstNotNullOfOrNull { payment -> + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@firstNotNullOfOrNull null + withdraw.txId.takeIf { + payment.status != PaymentStatus.FAILED && withdraw.destinationAddress == address && + payment.amount.toLong().toULong() == amountSats + } + } + } + /** * Withdraws exactly [amountSats] to a Paykit [contact]'s on-chain [address] at medium speed and returns the * withdrawal's txid. A journal entry written before the send lets the next start settle a withdrawal the app was * killed during, from Spark's payment list, and refuses another withdrawal until then. */ - suspend fun withdraw(address: String, amountSats: ULong, contact: String?): Result = + suspend fun withdraw( + address: String, + amountSats: ULong, + contact: String?, + onBeforeSend: suspend () -> Boolean = { true }, + ): Result = withContext(bgDispatcher) { runSuspendCatching { if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() val prepared = sparkService.prepareSend(address, amountSats) + if (!onBeforeSend()) throw PaymentAbortedBeforeSend() val journal = PendingSparkWithdrawal(address, amountSats, contact) cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { @@ -678,7 +698,7 @@ class SparkRepo @Inject constructor( 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.getOnchainActivityByTxId(txid)?.takeUnless { it.isTransfer || it.txType == PaymentType.SENT }?.let { activities.updateActivity(it.id, Activity.Onchain(it.copy(isTransfer = true))) } true @@ -689,7 +709,9 @@ class SparkRepo @Inject constructor( 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 + // A withdrawal to a Paykit contact is a send of its own; only an arrival in Savings is a transfer. + val activity = activities.getOnchainActivityByTxId(txid) + ?.takeUnless { it.isTransfer || it.txType == PaymentType.SENT } ?: return@forEach activities.updateActivity(activity.id, Activity.Onchain(activity.copy(isTransfer = true))) } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c58002928a..9a968e796f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4133,6 +4133,9 @@ class AppViewModel @Inject constructor( ) return true } + _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + if (routePaykitPayment(it) == PaykitRouteOutcome.Refused) return false + } if (!bindBitcoinRequestTerms()) return false requireCurrentPaymentPreparation(walletGeneration) navigateToSendRoute(fromMainScanner, SendRoute.Confirm, SendEffect.NavigateToConfirm, walletGeneration) @@ -4204,7 +4207,7 @@ class AppViewModel @Inject constructor( private fun offersSparkLeg(payment: ContactPaymentContext, address: String, canPayDirectly: Boolean): Boolean { if (!paykitRouteRepo.canRouteThroughSpark || canPayDirectly || address.isEmpty()) return false - return payment.incomingPaymentRequest == null && payment.endpoints.any { it.methodId.isOnchain } + return payment.endpoints.any { it.methodId.isOnchain } } private fun canFundPaykitLightning(invoice: LightningInvoice?, lnurl: LnurlParams.LnurlPay?): Boolean { @@ -4388,6 +4391,12 @@ class AppViewModel @Inject constructor( ) } updateCanSwitchWallet() + // A request's confirm screen opens without the amount step, so a source switch asks the router again there. + if (activeIncomingPaymentRequest() != null) { + _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + routePaykitPayment(it) + } + } reviewFundingSourceChange(current, canReviewInPlace, wasReviewed) } @@ -5144,7 +5153,7 @@ class AppViewModel @Inject constructor( } private fun requiresPaykitServiceRoute(payment: ContactPaymentContext): Boolean { - if (!paykitRouteRepo.canRouteThroughSpark || payment.incomingPaymentRequest != null) return false + if (!paykitRouteRepo.canRouteThroughSpark) return false return payment.endpoints.isNotEmpty() && payment.endpoints.all { it.methodId.isOnchain } } @@ -5808,10 +5817,11 @@ class AppViewModel @Inject constructor( source: SendFundingSource = selectedFundingSource(), ): MethodId = when (source) { SendFundingSource.Usdt -> MethodId.UsdtArbitrum - SendFundingSource.Spending -> when (lnurl) { - is LnurlParams.LnurlPay -> MethodId.Lnurl - else -> MethodId.Bolt11 - } + SendFundingSource.Spending -> routedPaykitRoute?.serviceLeg?.let { MethodId.fromRawValue(it.endpoint.methodId) } + ?: when (lnurl) { + is LnurlParams.LnurlPay -> MethodId.Lnurl + else -> MethodId.Bolt11 + } SendFundingSource.Savings, is SendFundingSource.Hardware -> PublicPaykitRepo.onchainMethodId(address) } @@ -6437,7 +6447,13 @@ class AppViewModel @Inject constructor( } _sendUiState.value.routedPaykitRoute?.serviceLeg?.let { - proceedWithServiceRoutedPayment(it, contactPaymentContext, allowanceAttemptId) + proceedWithServiceRoutedPayment( + leg = it, + incomingPaymentRequest = incomingPaymentRequest, + preparedPaymentProofRequest = preparedPaymentProofRequest, + contactPaymentContext = contactPaymentContext, + allowanceAttemptId = allowanceAttemptId, + ) return } @@ -6472,6 +6488,7 @@ class AppViewModel @Inject constructor( val endpointIdentifier = paymentProofPreparation(contactPaymentContext).endpointIdentifier val paymentHash = _sendUiState.value.decodedInvoice ?.takeIf { _sendUiState.value.payMethod == SendMethod.LIGHTNING } + ?.takeIf { _sendUiState.value.routedPaykitRoute?.serviceLeg == null } ?.paymentHash?.toHex() return paykitAllowanceRepo.beginManualPayment(request, endpointIdentifier, paymentHash) .recoverCatching { @@ -6837,15 +6854,26 @@ class AppViewModel @Inject constructor( private suspend fun proceedWithServiceRoutedPayment( leg: ServiceRouteLeg, + incomingPaymentRequest: PaykitPaymentRequest?, + preparedPaymentProofRequest: PaykitPaymentRequest?, contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { - val txid = paykitRouteRepo.payServiceLeg(leg, contactPaymentContext?.publicKey).getOrElse { + val txid = paykitRouteRepo.payServiceLeg(leg, contactPaymentContext?.publicKey) { + startSparkOnchainProof(leg, incomingPaymentRequest, preparedPaymentProofRequest, contactPaymentContext) + .getOrThrow() + true + }.getOrElse { releasePrivatePaymentListIfNeeded(contactPaymentContext) + cancelPaymentProofPreparation(preparedPaymentProofRequest) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext) return } + incomingPaymentRequest?.let { request -> + // The journaled withdrawal and Spark's payment list let a later reconcile finish a proof that fails here. + viewModelScope.launch { paykitPaymentProofRepo.completeSparkOnchainPayment(request, txid) } + } finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = txid) Logger.info("Paid Paykit contact through '${leg.service}' in '$txid'", context = TAG) onSendSuccess( @@ -6858,6 +6886,33 @@ class AppViewModel @Inject constructor( ) } + /** + * Runs once the Spark withdrawal is prepared, right before it sends: checks the request may still be paid, then + * marks its on-chain proof started for the leg's address and checks the original payer. + */ + private suspend fun startSparkOnchainProof( + leg: ServiceRouteLeg, + incomingPaymentRequest: PaykitPaymentRequest?, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + ): Result = runSuspendCatching { + val request = incomingPaymentRequest ?: return@runSuspendCatching + paykitPaymentRequestRepo.ensurePaymentAllowed(request).getOrThrow() + val prepared = preparedPaymentProofRequest + if (prepared != null) { + val originalPayer = paykitPaymentProofRepo.captureOriginalOnchainPayer(prepared).getOrThrow() + val privateContext = contactPaymentContext?.privatePaymentContext + paykitPaymentProofRepo.markSparkOnchainPaymentStarted( + request = request, + address = leg.endpoint.value, + amountSats = leg.deliveredSat, + privatePaymentListVersion = privateContext?.paymentListVersion, + previousPrivatePaymentListVersion = privateContext?.previousPaymentListVersion, + ).getOrThrow() + paykitPaymentProofRepo.verifyOriginalOnchainPayer(prepared, originalPayer).getOrThrow() + } + } + private suspend fun proceedWithLightningPayment( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 92741be3cd..d53e51379d 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -848,6 +848,64 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(storedProofs.isEmpty()) } + @Test + fun `onchain proof of a spark withdrawal completes with its txid`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + 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.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + + assertTrue(repo.completeSparkOnchainPayment(request, txid)) + + runCurrent() + val proofCaptor = argumentCaptor() + verify(paykitSdkService).submitPaymentProof( + any(), any(), any(), any(), proofCaptor.capture(), isNull(), isNull(), isNull(), any(), + ) + assertEquals( + """{"data":"$txid","type":"${PaykitPaymentProofKind.Onchain.type}"}""", + proofCaptor.firstValue, + ) + } + + @Test + fun `onchain proof of a spark withdrawal settles from spark after a restart`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + 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.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + + whenever(lightningRepo.sparkWithdrawalTxid(ONCHAIN_ADDRESS, request.amount.atomic)).thenReturn(null) + paymentProofRepo().reconcile() + assertTrue(storedProofs.single().paymentStarted) + assertEquals(null, storedProofs.single().proofData) + + whenever(lightningRepo.sparkWithdrawalTxid(ONCHAIN_ADDRESS, request.amount.atomic)).thenReturn(txid) + paymentProofRepo().reconcile() + runCurrent() + + val proofCaptor = argumentCaptor() + verify(paykitSdkService).submitPaymentProof( + any(), any(), any(), any(), proofCaptor.capture(), isNull(), isNull(), isNull(), any(), + ) + assertEquals( + """{"data":"$txid","type":"${PaykitPaymentProofKind.Onchain.type}"}""", + proofCaptor.firstValue, + ) + } + @Test fun `a spark retry decides a lightning proof the node failed`() = test { val record = paymentRequestRecord() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 45e36dc744..84b435d4ae 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -224,7 +224,7 @@ class SparkRepoTest : BaseUnitTest() { service = "spark", endpoint = contactEndpoint, deliveredSat = 20_000uL, - debitSat = 20_300uL, + debitSat = 20_500uL, atomicity = "trusted", validUntilUnix = 1_900_000_000uL, ), @@ -234,7 +234,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `offers no route leg the balance cannot cover with its fee`() = test { - val sut = readySpark(balanceSats = 20_299uL) + val sut = readySpark(balanceSats = 20_499uL) assertEquals(null, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()) } @@ -289,6 +289,46 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a withdrawal refused right before it sends writes no journal`() = test { + val sut = journaledSpark() + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { false }) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `finds the txid of a withdrawal to an address once spark synced`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = journaledSpark() + + assertEquals("withdrawal", sut.withdrawalTxid("bcrt1qcontact", 20_000uL)) + assertNull(sut.withdrawalTxid("bcrt1qcontact", 19_999uL)) + assertNull(sut.withdrawalTxid("bcrt1qother", 20_000uL)) + } + + @Test + fun `a withdrawal to a contact is not marked as a transfer`() = test { + val sent = OnchainActivity.create( + id = "withdrawal", + txType = ActivityPaymentType.SENT, + txId = "withdrawal", + value = 20_000uL, + fee = 500uL, + address = "bcrt1qcontact", + timestamp = 1uL, + ) + whenever { activityRepo.getOnchainActivityByTxId(eq("withdrawal"), any()) }.thenReturn(sent) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = journaledSpark() + + assertTrue(sut.markWithdrawalAsTransfer("withdrawal")) + verify(activityRepo, never()).updateActivity(any(), any(), any()) + } + private suspend fun journaledSpark(): SparkRepo { whenever { cacheStore.update(any()) }.doSuspendableAnswer { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3d5020d779..226048448e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -708,6 +708,16 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private var walletGeneration = 0L private fun stubRepositories() { + // The router pays the endpoint of the selected source: Lightning from Spending, on-chain from Savings. + // Result is an inline class, so a suspend answer returns its value unboxed. + whenever { paykitRouteRepo.route(any(), any(), any(), any(), any()) }.thenAnswer { + val endpoints = it.getArgument>(1) + val fromSpending = it.getArgument(3) == 0L + val picked = endpoints.firstOrNull { endpoint -> + MethodId.fromRawValue(endpoint.methodId)?.isOnchain != fromSpending + } ?: endpoints.first() + PaykitRoute.Direct(picked) + } whenever(connectionRecovery.currentGeneration()).thenAnswer { walletGeneration } whenever(connectionRecovery.isCurrentGeneration(anyOrNull())).thenAnswer { it.getArgument(0) == walletGeneration @@ -11980,7 +11990,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `spark route pays the contact while spending is the source`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") - whenever(paykitRouteRepo.payServiceLeg(leg, "pubkycontact")).thenReturn(Result.success("txid")) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any())).thenReturn(Result.success("txid")) setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( SendUiState( @@ -11993,7 +12003,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo).payServiceLeg(leg, "pubkycontact") + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any()) } @Test @@ -12014,7 +12024,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull()) + verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull(), any()) } @Test @@ -12131,6 +12141,55 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) } + @Test + fun `spark route pays an onchain request and completes its proof`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val txid = "ab".repeat(32) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull())) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(2) + if (onBeforeSend()) Result.success(txid) else Result.failure(AppError("refused")) + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + inOrder(paykitPaymentRequestRepo, paykitPaymentProofRepo).apply { + verify(paykitPaymentRequestRepo).ensurePaymentAllowed(request) + verify(paykitPaymentProofRepo).markSparkOnchainPaymentStarted( + eq(request), + eq(leg.endpoint.value), + eq(leg.deliveredSat), + anyOrNull(), + anyOrNull(), + ) + verify(paykitPaymentProofRepo).completeSparkOnchainPayment(request, txid) + } + } + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( service = "spark", endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), @@ -17409,6 +17468,48 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitPaymentProofRepo, never()).prepare(any(), any(), any(), any(), anyOrNull(), anyOrNull()) } + @Test + fun `request confirmation pays the endpoint the router picks`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.USD, 250u), + pricing = PaykitRequestPricing(PaymentConversion.Fixed(listOf(ConversionRate("btc", "0.00001")))), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + val resolution = CompletableDeferred>() + whenever(privatePaykitRepo.beginPaymentRequest(request)).doSuspendableAnswer { resolution.await() } + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + assertEquals(request, (sut.currentSheet.value as? Sheet.Send)?.preparingRequest) + resolution.complete( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))) + ) + runCurrent() + + assertEquals(Sheet.Send(SendRoute.Confirm), sut.currentSheet.value) + assertEquals(2_500uL, sut.sendUiState.value.amount) + assertTrue(sut.sendUiState.value.isAmountInputValid) + assertFalse(sut.sendUiState.value.shouldAutomaticallyPay) + assertFalse(sut.sendUiState.value.shouldConfirmPay) + verify(paykitPaymentRequestRepo, never()).accept(any()) + verify(paykitRouteRepo).route( + eq(2_500uL), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + eq(0uL), + eq(100_000uL), + eq(false), + ) + } + @Test fun `fixed dollar request accepting USDT opens bitcoin confirmation while USDT is off`() = test { enablePaykitUi() From c106fb058c8aff085839c509326e7868d70d4fec Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 02:09:11 +0100 Subject: [PATCH 11/90] fix: keep a spark withdrawal proof through backup --- .../bitkit/models/PaykitPaymentStateBackup.kt | 3 +++ .../models/PaykitPaymentStateBackupTest.kt | 17 +++++++++++++++++ changelog.d/next/1754.added.md | 2 +- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt b/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt index 38a9731d0f..bebf545af1 100644 --- a/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt +++ b/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt @@ -66,6 +66,7 @@ data class PaykitPaymentStateBackup( val privatePaymentListVersion: ULong? = null, val previousPrivatePaymentListVersion: ULong? = null, val allowanceId: String? = null, + val sparkWithdrawal: Boolean = false, ) { init { require( @@ -98,6 +99,7 @@ data class PaykitPaymentStateBackup( privatePaymentListVersion = proof.privatePaymentListVersion, previousPrivatePaymentListVersion = proof.previousPrivatePaymentListVersion, allowanceId = proof.allowanceId, + sparkWithdrawal = proof.sparkWithdrawal, ) fun restored() = PendingPaykitPaymentProof( @@ -124,6 +126,7 @@ data class PaykitPaymentStateBackup( privatePaymentListVersion = privatePaymentListVersion, previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, allowanceId = allowanceId, + sparkWithdrawal = sparkWithdrawal, ) } } diff --git a/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt b/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt index 57d40557c6..019e3533a3 100644 --- a/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt +++ b/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt @@ -52,6 +52,23 @@ class PaykitPaymentStateBackupTest { } } + @Test + fun `spark withdrawal proof keeps its rail through backup`() { + WalletScope.pushTestOverride("wallet0").use { + val backup = Json.decodeFromString( + """ + {"identity":"alice","requestId":{"paymentRequestId":"request","counterparty":"bob"}, + "paymentEndpointIdentifier":"btc-regtest-p2wpkh","kind":"bitcoin-onchain-txid","paymentStarted":true, + "onchainMatchingTransactionIdsBeforeAttempt":[],"sparkWithdrawal":true} + """.trimIndent(), + ) + val restored = backup.restored() + assertTrue(restored.sparkWithdrawal) + val json = Json.encodeToString(PaykitPaymentStateBackup.Proof(restored)) + assertContains(json, "\"sparkWithdrawal\":true") + } + } + @Test fun `shared active operation survives payment backup reader writer roundtrip`() { val wire = """ diff --git a/changelog.d/next/1754.added.md b/changelog.d/next/1754.added.md index c908dc605f..ceedc45d9c 100644 --- a/changelog.d/next/1754.added.md +++ b/changelog.d/next/1754.added.md @@ -1 +1 @@ -Paykit contacts who only accept on-chain bitcoin can be paid from Spark. +Paykit contacts and payment requests can be paid from Spark, including contacts and requests that only accept on-chain bitcoin. From d49fc3f496ce121bda37fc717b96a245f38177c8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 02:36:23 +0100 Subject: [PATCH 12/90] fix: keep contact withdrawals out of transfers to savings --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 20 +++++++++++++++++++ 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 5caf318c33..e622020178 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -655,13 +655,14 @@ class SparkRepo @Inject constructor( ) } (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } + val transfers = payments.toWithdrawals().filterNot { isContactWithdrawal(it.txid) }.toImmutableList() _state.update { it.copy( isReady = true, balanceSats = info.balanceSats, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), - withdrawals = payments.toWithdrawals(), + withdrawals = transfers, ).withBroadcastDeposits() } markClaimedDeposits(claimed) @@ -690,6 +691,10 @@ class SparkRepo @Inject constructor( } .toImmutableList() + /** A withdrawal to a Paykit contact is recorded as an on-chain send: it is no Transfer to Savings. */ + private suspend fun isContactWithdrawal(txid: String): Boolean = + (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1?.txType == PaymentType.SENT + /** * 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. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 84b435d4ae..a02462856d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -329,6 +329,26 @@ class SparkRepoTest : BaseUnitTest() { verify(activityRepo, never()).updateActivity(any(), any(), any()) } + @Test + fun `lists a withdrawal to a contact with the sends, not as a transfer to savings`() = test { + val sent = OnchainActivity.create( + id = "withdrawal", + txType = ActivityPaymentType.SENT, + txId = "withdrawal", + value = 20_000uL, + fee = 300uL, + address = "bcrt1qcontact", + timestamp = 1uL, + ) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(Activity.Onchain(sent))) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + + val sut = journaledSpark() + + assertTrue(sut.state.value.withdrawals.isEmpty()) + } + private suspend fun journaledSpark(): SparkRepo { whenever { cacheStore.update(any()) }.doSuspendableAnswer { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) From 154f273dc407cdfdfde7ba27825fac3658bb8ff7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 03:34:06 +0100 Subject: [PATCH 13/90] fix: tie spark withdrawals to their attempt and confirmed fee --- .../to/bitkit/repositories/LightningRepo.kt | 12 +- .../repositories/PaykitPaymentProofRepo.kt | 45 +++++++- .../to/bitkit/repositories/PaykitRouteRepo.kt | 8 +- .../java/to/bitkit/repositories/SparkRepo.kt | 60 ++++++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 32 +++++- .../PaykitPaymentProofRepoTest.kt | 30 ++++- .../to/bitkit/repositories/SparkRepoTest.kt | 58 ++++++++-- .../viewmodels/AppViewModelSendFlowTest.kt | 104 +++++++++++++++++- 8 files changed, 314 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index f14b2310cc..b81c29a59d 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2331,9 +2331,15 @@ class LightningRepo @Inject constructor( } } - /** The txid of Spark's withdrawal of exactly [amountSats] to [address], once Spark lists it. */ - suspend fun sparkWithdrawalTxid(address: String, amountSats: ULong): String? = - sparkRepo.withdrawalTxid(address, amountSats) + /** What became of a Spark withdrawal attempt of exactly [amountSats] to [address], from Spark's payment list. */ + suspend fun sparkWithdrawalOutcome( + address: String, + amountSats: ULong, + earlierTxids: Set, + ): SparkWithdrawalOutcome = sparkRepo.withdrawalOutcome(address, amountSats, earlierTxids) + + /** Txids of the Spark withdrawals to [address] so far, which a new attempt to it never counts as its own. */ + suspend fun sparkWithdrawalTxidsTo(address: String): Set = sparkRepo.withdrawalTxidsTo(address) /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index b4ea5b67da..69b0a1ea75 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -317,6 +317,7 @@ class PaykitPaymentProofRepo @Inject constructor( amountSats: ULong, privatePaymentListVersion: ULong? = null, previousPrivatePaymentListVersion: ULong? = null, + earlierWithdrawalTxids: Set = emptySet(), ): Result = markOnchainStarted( request = request, address = address, @@ -326,6 +327,7 @@ class PaykitPaymentProofRepo @Inject constructor( signedTx = null, previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, sparkWithdrawal = true, + earlierWithdrawalTxids = earlierWithdrawalTxids, ) @Suppress("LongParameterList") @@ -338,6 +340,7 @@ class PaykitPaymentProofRepo @Inject constructor( signedTx: HwFundingSignedTx?, previousPrivatePaymentListVersion: ULong?, sparkWithdrawal: Boolean, + earlierWithdrawalTxids: Set = emptySet(), ): Result = withContext(ioDispatcher) { runSuspendCatching { val identity = currentIdentity() ?: throw PaykitPaymentRequestError.RequestUnavailable @@ -378,6 +381,11 @@ class PaykitPaymentProofRepo @Inject constructor( hardwareTotalSpent = signedTx?.totalSpent, hardwareDispatchAttempted = signedTx?.let { false }, sparkWithdrawal = sparkWithdrawal, + onchainMatchingTransactionIdsBeforeAttempt = if (sparkWithdrawal) { + earlierWithdrawalTxids + } else { + proofs[index].onchainMatchingTransactionIdsBeforeAttempt + }, ) persist(proofs) } @@ -402,12 +410,45 @@ class PaykitPaymentProofRepo @Inject constructor( }.getOrDefault(false) } + /** + * Releases the started Spark proof of [request] when Spark shows its withdrawal never sent, so the request can be + * paid again; returns whether it did. + */ + suspend fun releaseUnsentSparkOnchainProof(request: PaykitPaymentRequest): Boolean = withContext(ioDispatcher) { + val identity = currentIdentity() ?: return@withContext false + runSuspendCatching { + operationMutex.withLock { + val proof = loadProofs().lastOrNull { + PubkyPublicKeyFormat.matches(it.identity, identity) && it.requestId == request.id && + it.sparkWithdrawal && it.paymentStarted && it.proofData == null + } ?: return@withLock false + reconcileSparkOnchainProof(proof) + loadProofs().none { it == proof } + } + }.onFailure { + Logger.warn("Failed to release an unsent Spark withdrawal proof", it, context = TAG) + }.getOrDefault(false) + } + + /** Settles a started Spark proof from Spark's list: completed by its own withdrawal, removed when it never sent. */ private suspend fun reconcileSparkOnchainProof(proof: PendingPaykitPaymentProof): Boolean { if (!proof.paymentStarted || proof.proofData != null) return false val address = proof.onchainAddress ?: return false val amount = proof.onchainAmountSats ?: return false - val txid = lightningRepo.sparkWithdrawalTxid(address, amount) ?: return false - return completeSparkOnchainProofLocked(proof, txid) + val outcome = lightningRepo.sparkWithdrawalOutcome( + address, + amount, + proof.onchainMatchingTransactionIdsBeforeAttempt, + ) + return when (outcome) { + is SparkWithdrawalOutcome.Sent -> completeSparkOnchainProofLocked(proof, outcome.txid) + SparkWithdrawalOutcome.Unsent -> { + Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) + removeProofsLocked { it == proof } + false + } + SparkWithdrawalOutcome.Unknown -> false + } } private suspend fun completeSparkOnchainProofLocked(proof: PendingPaykitPaymentProof, txid: String): Boolean { diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 2aa917c903..76c53c5208 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -72,7 +72,13 @@ class PaykitRouteRepo @Inject constructor( contact: String?, onBeforeSend: suspend () -> Boolean = { true }, ): Result = when (leg.service) { - SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(leg.endpoint.value, leg.deliveredSat, contact, onBeforeSend) + SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw( + address = leg.endpoint.value, + amountSats = leg.deliveredSat, + contact = contact, + maxDebitSats = leg.debitSat, + onBeforeSend = onBeforeSend, + ) else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index e622020178..6c59b7b56e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -499,16 +499,36 @@ class SparkRepo @Inject constructor( } } - /** The txid of a withdrawal Spark sent of exactly [amountSats] to [address], once Spark's synced list holds it. */ - suspend fun withdrawalTxid(address: String, amountSats: ULong): String? = withContext(bgDispatcher) { - if (!_state.value.hasSynced) return@withContext null - sparkService.listPayments().firstNotNullOfOrNull { payment -> + /** Txids of the withdrawals Spark lists to [address], so a new attempt to it can tell its own withdrawal apart. */ + suspend fun withdrawalTxidsTo(address: String): Set = withContext(bgDispatcher) { + sparkService.listPayments().mapNotNull { payment -> + (payment.details as? PaymentDetails.Withdraw)?.takeIf { it.destinationAddress == address }?.txId + }.toSet() + } + + /** + * What became of an attempt to withdraw exactly [amountSats] to [address]: sent once Spark's synced list holds a + * withdrawal to it that is not one of [earlierTxids], unsent once Spark synced and no journaled withdrawal to + * [address] is still settling, else unknown. + */ + suspend fun withdrawalOutcome( + address: String, + amountSats: ULong, + earlierTxids: Set, + ): SparkWithdrawalOutcome = withContext(bgDispatcher) { + if (!_state.value.hasSynced) return@withContext SparkWithdrawalOutcome.Unknown + val txid = sparkService.listPayments().firstNotNullOfOrNull { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@firstNotNullOfOrNull null withdraw.txId.takeIf { payment.status != PaymentStatus.FAILED && withdraw.destinationAddress == address && - payment.amount.toLong().toULong() == amountSats + payment.amount.toLong().toULong() == amountSats && it !in earlierTxids } } + when { + txid != null -> SparkWithdrawalOutcome.Sent(txid) + cacheStore.data.first().pendingSparkWithdrawal?.address == address -> SparkWithdrawalOutcome.Unknown + else -> SparkWithdrawalOutcome.Unsent + } } /** @@ -520,14 +540,20 @@ class SparkRepo @Inject constructor( address: String, amountSats: ULong, contact: String?, + maxDebitSats: ULong? = null, onBeforeSend: suspend () -> Boolean = { true }, ): Result = withContext(bgDispatcher) { runSuspendCatching { if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() val prepared = sparkService.prepareSend(address, amountSats) + val speed = prepared.withdrawalQuote().speedMedium + val debitSats = amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() + // The user confirmed the leg's debit; a quote that rose since then needs a new confirmation. + if (maxDebitSats != null && debitSats > maxDebitSats) throw SparkError.WithdrawalFeeChanged() + val earlierTxids = withdrawalTxidsTo(address) if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - val journal = PendingSparkWithdrawal(address, amountSats, contact) + val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids) cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. @@ -870,7 +896,8 @@ class SparkRepo @Inject constructor( val existing = (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1 ?.takeIf { it.txType == PaymentType.SENT } val journal = cacheStore.data.first().pendingSparkWithdrawal?.takeIf { - it.address == withdraw.destinationAddress && it.amountSats == payment.amount.toLong().toULong() + it.address == withdraw.destinationAddress && it.amountSats == payment.amount.toLong().toULong() && + txid !in it.earlierTxids } if (existing == null && journal == null) return val activity = OnchainActivity.create( @@ -886,8 +913,11 @@ class SparkRepo @Inject constructor( contact = existing?.contact ?: journal?.contact, seenAt = existing?.seenAt, ) - activityRepo.get().upsertActivity(Activity.Onchain(activity)) - if (journal != null) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + // The journal stays until the activity is saved, so a failed save is retried from Spark's list. + val saved = activityRepo.get().upsertActivity(Activity.Onchain(activity)) + .onFailure { Logger.warn("Failed to record Spark withdrawal '$txid'", it, context = TAG) } + .isSuccess + if (saved && journal != null) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } } private suspend fun receivedContact(payment: Payment, paymentHash: String): String? { @@ -928,8 +958,20 @@ data class PendingSparkWithdrawal( val address: String, val amountSats: ULong, val contact: String?, + /** Withdrawals to [address] listed before this attempt, which never settle it. */ + val earlierTxids: Set = emptySet(), ) +/** What became of a Spark withdrawal attempt, from Spark's payment list. */ +sealed interface SparkWithdrawalOutcome { + data class Sent(val txid: String) : SparkWithdrawalOutcome + + /** Spark synced, holds no withdrawal for the attempt and has none settling: it never sent. */ + data object Unsent : SparkWithdrawalOutcome + + data object Unknown : SparkWithdrawalOutcome +} + private class PreparedWithdrawal( val address: String, val balanceSats: ULong, diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9a968e796f..ac48de584c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -473,6 +473,10 @@ class AppViewModel @Inject constructor( private val processedPaymentsLock = Any() private val processedPayments = mutableSetOf() private val contactPaymentContextLock = Any() + + /** The Paykit router picked this payment's way on Continue or a request's confirm step, so a switch reroutes. */ + @Volatile + private var paykitRouteDecided = false private var activeContactPaymentContext: ContactPaymentContext? = null val usdtWallet = usdtRepo.state val isUsdtEnabled = usdtPreferences.enabled.stateIn(viewModelScope, SharingStarted.Eagerly, false) @@ -4051,7 +4055,9 @@ class AppViewModel @Inject constructor( val canUseOnchain = address.isNotEmpty() && walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) - val offersSparkLeg = offersSparkLeg(payment, address, canUseLightning || useUsdt) + // The Spark leg stays offered beside USDT, so switching such a contact to Spending can still route through it. + val offersSparkLeg = offersSparkLeg(payment, address, canUseLightning) + paykitRouteDecided = false val route = PaykitRouteUi( endpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } .map { PaykitEndpoint(methodId = it.methodId.rawValue, value = it.value) }, @@ -4232,6 +4238,7 @@ class AppViewModel @Inject constructor( private suspend fun onAmountChange(amount: ULong) { if (_sendUiState.value.paykitUsesUsdt || !_sendUiState.value.isAmountEditable) return + paykitRouteDecided = false _sendUiState.update { it.copy( amount = amount, @@ -4391,8 +4398,8 @@ class AppViewModel @Inject constructor( ) } updateCanSwitchWallet() - // A request's confirm screen opens without the amount step, so a source switch asks the router again there. - if (activeIncomingPaymentRequest() != null) { + // A source switch on Confirm asks the router again, for a request (no amount step) or a route already decided. + if (activeIncomingPaymentRequest() != null || paykitRouteDecided) { _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { routePaykitPayment(it) } @@ -4684,6 +4691,7 @@ class AppViewModel @Inject constructor( toast(it) return PaykitRouteOutcome.Refused } + paykitRouteDecided = picked !is PaykitRoute.None return when (picked) { is PaykitRoute.Direct -> { payDirectEndpoint(route, picked.endpoint) @@ -6271,6 +6279,9 @@ class AppViewModel @Inject constructor( if (_sendUiState.value.showSanityWarningDialog != null) return val settings = settingsStore.data.first() + // A Spark leg spends its debit, the amount plus Spark's fees, from Spark's balance. + val leg = _sendUiState.value.routedPaykitRoute?.serviceLeg + val spentSats = leg?.debitSat ?: amountSats val balanceToCheck = when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> { _sendUiState.value.hardwareAvailableSats @@ -6280,7 +6291,7 @@ class AppViewModel @Inject constructor( SendMethod.LIGHTNING -> walletRepo.balanceState.value.maxSendLightningSats } if ( - amountSats > BigDecimal.valueOf(balanceToCheck.toLong()) + spentSats > BigDecimal.valueOf(balanceToCheck.toLong()) .times(BigDecimal(MAX_BALANCE_FRACTION)).toLong().toUInt() && SanityWarning.OVER_HALF_BALANCE !in _sendUiState.value.confirmedWarnings ) { @@ -6303,9 +6314,11 @@ class AppViewModel @Inject constructor( return } - if (_sendUiState.value.payMethod != SendMethod.ONCHAIN) return + if (_sendUiState.value.payMethod != SendMethod.ONCHAIN && leg == null) return - val totalFee = if (_sendUiState.value.hardwareWalletId != null) { + val totalFee = if (leg != null) { + leg.debitSat.safe() - leg.deliveredSat.safe() + } else if (_sendUiState.value.hardwareWalletId != null) { _sendUiState.value.onchainFeeUi.sats?.toULong() ?: return } else { lightningRepo.calculateTotalFee( @@ -6864,12 +6877,18 @@ class AppViewModel @Inject constructor( .getOrThrow() true }.getOrElse { + // A started proof is released only once Spark shows the withdrawal never sent. + incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(preparedPaymentProofRequest) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext) return } + _sendUiState.value.selectedTags.takeIf { it.isNotEmpty() }?.let { tags -> + activityRepo.addTagsToActivity(txid, tags) + .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } + } incomingPaymentRequest?.let { request -> // The journaled withdrawal and Spark's payment list let a later reconcile finish a proof that fails here. viewModelScope.launch { paykitPaymentProofRepo.completeSparkOnchainPayment(request, txid) } @@ -6908,6 +6927,7 @@ class AppViewModel @Inject constructor( amountSats = leg.deliveredSat, privatePaymentListVersion = privateContext?.paymentListVersion, previousPrivatePaymentListVersion = privateContext?.previousPaymentListVersion, + earlierWithdrawalTxids = lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value), ).getOrThrow() paykitPaymentProofRepo.verifyOriginalOnchainPayer(prepared, originalPayer).getOrThrow() } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index d53e51379d..7e0863be41 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -885,14 +885,21 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { ).thenReturn(record) val repo = paymentProofRepo() repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() - repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + earlierWithdrawalTxids = setOf("ef".repeat(32)), + ).getOrThrow() - whenever(lightningRepo.sparkWithdrawalTxid(ONCHAIN_ADDRESS, request.amount.atomic)).thenReturn(null) + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, setOf("ef".repeat(32)))) + .thenReturn(SparkWithdrawalOutcome.Unknown) paymentProofRepo().reconcile() assertTrue(storedProofs.single().paymentStarted) assertEquals(null, storedProofs.single().proofData) - whenever(lightningRepo.sparkWithdrawalTxid(ONCHAIN_ADDRESS, request.amount.atomic)).thenReturn(txid) + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, setOf("ef".repeat(32)))) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) paymentProofRepo().reconcile() runCurrent() @@ -906,6 +913,23 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { ) } + @Test + fun `a spark withdrawal proof that never sent is released so the request can be paid again`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + assertTrue(repo.releaseUnsentSparkOnchainProof(request)) + + assertTrue(storedProofs.isEmpty()) + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + } + @Test fun `a spark retry decides a lightning proof the node failed`() = test { val record = paymentRequestRecord() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a02462856d..3edb151696 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -62,6 +62,7 @@ import to.bitkit.models.WalletScope import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.AppError import to.bitkit.utils.ServiceError import java.io.File import java.math.BigInteger @@ -300,16 +301,6 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } - @Test - fun `finds the txid of a withdrawal to an address once spark synced`() = test { - whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) - val sut = journaledSpark() - - assertEquals("withdrawal", sut.withdrawalTxid("bcrt1qcontact", 20_000uL)) - assertNull(sut.withdrawalTxid("bcrt1qcontact", 19_999uL)) - assertNull(sut.withdrawalTxid("bcrt1qother", 20_000uL)) - } - @Test fun `a withdrawal to a contact is not marked as a transfer`() = test { val sent = OnchainActivity.create( @@ -349,6 +340,53 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(sut.state.value.withdrawals.isEmpty()) } + @Test + fun `refuses a withdrawal whose fee rose above the confirmed debit`() = test { + val sut = journaledSpark() + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, maxDebitSats = 20_499uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `keeps the journal when the withdrawal's activity fails to save`() = test { + val sut = journaledSpark() + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(AppError("disk full"))) + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + } + + @Test + fun `an earlier withdrawal to the same address never settles a new attempt`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = journaledSpark() + cacheData.update { + it.copy( + pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null, setOf("withdrawal")), + ) + } + + assertEquals( + SparkWithdrawalOutcome.Unknown, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, setOf("withdrawal")), + ) + cacheData.update { it.copy(pendingSparkWithdrawal = null) } + assertEquals( + SparkWithdrawalOutcome.Unsent, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, setOf("withdrawal")), + ) + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + ) + } + private suspend fun journaledSpark(): SparkRepo { whenever { cacheStore.update(any()) }.doSuspendableAnswer { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 226048448e..ef04ad7778 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12155,7 +12155,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) .thenReturn(Result.success(Unit)) whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) - whenever(paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) .thenReturn(Result.success(Unit)) whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) .thenReturn(Result.success(Unit)) @@ -12185,11 +12188,110 @@ class AppViewModelSendFlowTest : BaseUnitTest() { eq(leg.deliveredSat), anyOrNull(), anyOrNull(), + any(), ) verify(paykitPaymentProofRepo).completeSparkOnchainPayment(request, txid) } } + @Test + fun `spark route saves the tags picked on confirmation`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any())).thenReturn(Result.success("txid")) + whenever(activityRepo.addTagsToActivity(any(), any(), any())).thenReturn(Result.success(Unit)) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + selectedTags = persistentListOf("rent"), + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + + verify(activityRepo).addTagsToActivity(eq("txid"), eq(listOf("rent")), any()) + } + + @Test + fun `a failed spark leg releases a request proof spark never sent`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any())) + .thenReturn(Result.failure(AppError("send failed"))) + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(paykitPaymentProofRepo).releaseUnsentSparkOnchainProof(request) + } + + @Test + fun `a source switch on confirmation reroutes a contact payment`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + } + + @Test + fun `spark leg fees count in the payment warnings`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact").copy(deliveredSat = 1_000uL, debitSat = 2_000uL) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isAmountInputValid = true, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + sut.setSendEvent(SendEvent.SwipeToPay) + advanceUntilIdle() + + assertEquals(SanityWarning.FEE_OVER_HALF_VALUE, sut.sendUiState.value.showSanityWarningDialog) + } + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( service = "spark", endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), From 12ae2191dfbcaee0102b6b5abcb7947b95debe44 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 03:46:16 +0100 Subject: [PATCH 14/90] fix: pay requests savings cannot cover from spark --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 2 + .../java/to/bitkit/repositories/SparkRepo.kt | 13 ++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 22 ++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 16 ++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 55 ++++++++++++++++--- 5 files changed, 92 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 76c53c5208..b85e46b901 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -70,6 +70,7 @@ class PaykitRouteRepo @Inject constructor( suspend fun payServiceLeg( leg: ServiceRouteLeg, contact: String?, + tags: List = emptyList(), onBeforeSend: suspend () -> Boolean = { true }, ): Result = when (leg.service) { SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw( @@ -77,6 +78,7 @@ class PaykitRouteRepo @Inject constructor( amountSats = leg.deliveredSat, contact = contact, maxDebitSats = leg.debitSat, + tags = tags, onBeforeSend = onBeforeSend, ) else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6c59b7b56e..6345d935fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -541,6 +541,7 @@ class SparkRepo @Inject constructor( amountSats: ULong, contact: String?, maxDebitSats: ULong? = null, + tags: List = emptyList(), onBeforeSend: suspend () -> Boolean = { true }, ): Result = withContext(bgDispatcher) { @@ -553,7 +554,7 @@ class SparkRepo @Inject constructor( if (maxDebitSats != null && debitSats > maxDebitSats) throw SparkError.WithdrawalFeeChanged() val earlierTxids = withdrawalTxidsTo(address) if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids) + val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids, tags) cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. @@ -917,7 +918,14 @@ class SparkRepo @Inject constructor( val saved = activityRepo.get().upsertActivity(Activity.Onchain(activity)) .onFailure { Logger.warn("Failed to record Spark withdrawal '$txid'", it, context = TAG) } .isSuccess - if (saved && journal != null) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + if (saved && journal != null) { + // The tags picked on Confirm travel with the journal, so a recovered withdrawal keeps them too. + if (journal.tags.isNotEmpty()) { + activityRepo.get().addTagsToActivity(txid, journal.tags) + .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } + } + cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + } } private suspend fun receivedContact(payment: Payment, paymentHash: String): String? { @@ -960,6 +968,7 @@ data class PendingSparkWithdrawal( val contact: String?, /** Withdrawals to [address] listed before this attempt, which never settle it. */ val earlierTxids: Set = emptySet(), + val tags: List = emptyList(), ) /** What became of a Spark withdrawal attempt, from Spark's payment list. */ diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index ac48de584c..a37228a583 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4140,6 +4140,7 @@ class AppViewModel @Inject constructor( return true } _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + preferSparkWhenSavingsShort(it) if (routePaykitPayment(it) == PaykitRouteOutcome.Refused) return false } if (!bindBitcoinRequestTerms()) return false @@ -4150,6 +4151,17 @@ class AppViewModel @Inject constructor( return true } + /** + * A request skips the amount step, so its source is picked here: Savings only when it covers the amount with its + * fee, else Spending, where the router can take the Spark leg. + */ + private fun preferSparkWhenSavingsShort(route: PaykitRouteUi) { + val state = _sendUiState.value + if (!route.offersSparkLeg || state.payMethod != SendMethod.ONCHAIN || state.hardwareWalletId != null) return + if (walletRepo.balanceState.value.maxSendOnchainSats >= state.amount) return + _sendUiState.update { it.copy(payMethod = SendMethod.LIGHTNING) } + } + private suspend fun bindUsdtRequestTerms(): Boolean { if (!_sendUiState.value.paykitUsesUsdt || !_sendUiState.value.isAmountInputValid) return false paykitPaymentTerms = null @@ -6872,7 +6884,11 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { - val txid = paykitRouteRepo.payServiceLeg(leg, contactPaymentContext?.publicKey) { + val txid = paykitRouteRepo.payServiceLeg( + leg, + contactPaymentContext?.publicKey, + _sendUiState.value.selectedTags, + ) { startSparkOnchainProof(leg, incomingPaymentRequest, preparedPaymentProofRequest, contactPaymentContext) .getOrThrow() true @@ -6885,10 +6901,6 @@ class AppViewModel @Inject constructor( handlePaymentPreparationFailure(it, contactPaymentContext) return } - _sendUiState.value.selectedTags.takeIf { it.isNotEmpty() }?.let { tags -> - activityRepo.addTagsToActivity(txid, tags) - .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } - } incomingPaymentRequest?.let { request -> // The journaled withdrawal and Spark's payment list let a later reconcile finish a proof that fails here. viewModelScope.launch { paykitPaymentProofRepo.completeSparkOnchainPayment(request, txid) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3edb151696..65fa1be48a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -387,6 +387,22 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `tags a recovered withdrawal with the tags picked on confirmation`() = test { + whenever { activityRepo.addTagsToActivity(any(), any(), any()) }.thenReturn(Result.success(Unit)) + cacheData.update { + it.copy( + pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null, tags = listOf("rent")), + ) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + + journaledSpark() + + verify(activityRepo).addTagsToActivity(eq("withdrawal"), eq(listOf("rent")), any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + private suspend fun journaledSpark(): SparkRepo { whenever { cacheStore.update(any()) }.doSuspendableAnswer { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ef04ad7778..37fdbf3701 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -11990,7 +11990,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `spark route pays the contact while spending is the source`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any())).thenReturn(Result.success("txid")) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())) + .thenReturn(Result.success("txid")) setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( SendUiState( @@ -12003,7 +12004,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), any()) } @Test @@ -12024,7 +12025,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull(), any()) + verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull(), any(), any()) } @Test @@ -12162,8 +12163,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) .thenReturn(Result.success(Unit)) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(2) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(3) if (onBeforeSend()) Result.success(txid) else Result.failure(AppError("refused")) } setActiveContactPaymentContext(testPublicKey, privateContext, request) @@ -12197,8 +12198,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any())).thenReturn(Result.success("txid")) - whenever(activityRepo.addTagsToActivity(any(), any(), any())).thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), any())) + .thenReturn(Result.success("txid")) setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( SendUiState( @@ -12212,7 +12213,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(activityRepo).addTagsToActivity(eq("txid"), eq(listOf("rent")), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), any()) } @Test @@ -12226,7 +12227,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) .thenReturn(Result.success(Unit)) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any())) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())) .thenReturn(Result.failure(AppError("send failed"))) whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) setActiveContactPaymentContext(testPublicKey, privateContext, request) @@ -17612,6 +17613,42 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `an onchain request savings cannot cover goes to spark`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 20_000u), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 5_000u, maxSendLightningSats = 50_000u) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + val resolution = CompletableDeferred>() + whenever(privatePaykitRepo.beginPaymentRequest(request)).doSuspendableAnswer { resolution.await() } + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + assertEquals(request, (sut.currentSheet.value as? Sheet.Send)?.preparingRequest) + resolution.complete( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))) + ) + runCurrent() + + verify(paykitRouteRepo).route( + eq(20_000uL), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + any(), + eq(0uL), + eq(true), + ) + } + @Test fun `fixed dollar request accepting USDT opens bitcoin confirmation while USDT is off`() = test { enablePaykitUi() From 32d546dcc65d4e2e0b393482a3e7abb6318c92cc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 03:55:41 +0100 Subject: [PATCH 15/90] test: keep the spark leg for onchain and usdt contacts --- .../viewmodels/AppViewModelSendFlowTest.kt | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 37fdbf3701..2ab57b54fe 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -11251,6 +11251,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `onchain and USDT contact keeps the spark leg whatever the USDT preference`() = test { + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + balanceState.value = BalanceState(maxSendLightningSats = 50_000u) + for (enabled in listOf(true, false)) { + usdtEnabled.value = enabled + sut.openContactPayment( + paymentRequest = REGTEST_ADDRESS, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ), + ) + advanceUntilIdle() + + assertEquals(true, sut.sendUiState.value.paykitRoute?.offersSparkLeg, "USDT enabled: $enabled") + } + } + @Test fun `hardware mixed contact uses only its onchain endpoint`() = test { val bolt11 = "lnbcrt1contactfixed" From adabea8c21d3962ffb911d9fe36c2b313040a40f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 04:04:08 +0100 Subject: [PATCH 16/90] fix: keep an uncertain spark send in flight --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 61 ++++++++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 17 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 74 +++++++++++++++++++ 3 files changed, 143 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a37228a583..df595dafd4 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -225,6 +225,7 @@ import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayPaymentFailedError import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo +import to.bitkit.repositories.SparkWithdrawalOutcome import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -6884,21 +6885,32 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { + var earlierTxids: Set? = null val txid = paykitRouteRepo.payServiceLeg( leg, contactPaymentContext?.publicKey, _sendUiState.value.selectedTags, ) { - startSparkOnchainProof(leg, incomingPaymentRequest, preparedPaymentProofRequest, contactPaymentContext) - .getOrThrow() + val earlier = lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value) + startSparkOnchainProof( + leg = leg, + incomingPaymentRequest = incomingPaymentRequest, + preparedPaymentProofRequest = preparedPaymentProofRequest, + contactPaymentContext = contactPaymentContext, + earlierTxids = earlier, + ).getOrThrow() + earlierTxids = earlier true }.getOrElse { - // A started proof is released only once Spark shows the withdrawal never sent. - incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } - releasePrivatePaymentListIfNeeded(contactPaymentContext) - cancelPaymentProofPreparation(preparedPaymentProofRequest) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) + handleServiceLegFailure( + error = it, + leg = leg, + earlierTxids = earlierTxids, + incomingPaymentRequest = incomingPaymentRequest, + preparedPaymentProofRequest = preparedPaymentProofRequest, + contactPaymentContext = contactPaymentContext, + allowanceAttemptId = allowanceAttemptId, + ) return } incomingPaymentRequest?.let { request -> @@ -6917,6 +6929,36 @@ class AppViewModel @Inject constructor( ) } + /** + * Only a withdrawal Spark shows never sent is a definite failure: it releases the started proof, the private list + * and the allowance attempt. Once a send was attempted and Spark can't tell yet, they stay, as on-chain. + */ + @Suppress("LongParameterList") + private suspend fun handleServiceLegFailure( + error: Throwable, + leg: ServiceRouteLeg, + earlierTxids: Set?, + incomingPaymentRequest: PaykitPaymentRequest?, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } + val unsent = earlierTxids == null || + lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, earlierTxids) == + SparkWithdrawalOutcome.Unsent + if (!unsent) { + Logger.warn("Left a Spark withdrawal with an uncertain send result to Spark", error, context = TAG) + finishManualAllowancePayment(allowanceAttemptId, succeeded = null) + showUnresolvedOnchainSend(null, leg.deliveredSat, incomingPaymentRequest) + return + } + releasePrivatePaymentListIfNeeded(contactPaymentContext) + cancelPaymentProofPreparation(preparedPaymentProofRequest) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(error, contactPaymentContext) + } + /** * Runs once the Spark withdrawal is prepared, right before it sends: checks the request may still be paid, then * marks its on-chain proof started for the leg's address and checks the original payer. @@ -6926,6 +6968,7 @@ class AppViewModel @Inject constructor( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, contactPaymentContext: ContactPaymentContext?, + earlierTxids: Set, ): Result = runSuspendCatching { val request = incomingPaymentRequest ?: return@runSuspendCatching paykitPaymentRequestRepo.ensurePaymentAllowed(request).getOrThrow() @@ -6939,7 +6982,7 @@ class AppViewModel @Inject constructor( amountSats = leg.deliveredSat, privatePaymentListVersion = privateContext?.paymentListVersion, previousPrivatePaymentListVersion = privateContext?.previousPaymentListVersion, - earlierWithdrawalTxids = lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value), + earlierWithdrawalTxids = earlierTxids, ).getOrThrow() paykitPaymentProofRepo.verifyOriginalOnchainPayer(prepared, originalPayer).getOrThrow() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 65fa1be48a..f537794f50 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -403,6 +403,23 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `an older open journal refuses a new withdrawal before its proof can start`() = test { + val sut = journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 5_000uL, null)) } + var checked = false + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { + checked = true + true + }) + + assertIs(result.exceptionOrNull()) + assertFalse(checked) + verify(sparkService, never()).prepareSend(any(), anyOrNull(), anyOrNull()) + assertEquals(5_000uL, cacheData.value.pendingSparkWithdrawal?.amountSats) + } + private suspend fun journaledSpark(): SparkRepo { whenever { cacheStore.update(any()) }.doSuspendableAnswer { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 2ab57b54fe..3ebbd13e53 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -217,6 +217,7 @@ import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo import to.bitkit.repositories.SettledReceiveAddress import to.bitkit.repositories.SettledReceiveInvoice +import to.bitkit.repositories.SparkWithdrawalOutcome import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -12316,6 +12317,79 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SanityWarning.FEE_OVER_HALF_VALUE, sut.sendUiState.value.showSanityWarningDialog) } + @Test + fun `a spark proof whose payer check fails is released so the request can be retried`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ).thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.failure(PaykitPaymentRequestError.RequestUnavailable)) + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(3) + runSuspendCatching { onBeforeSend() }.map { "never" } + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(paykitPaymentProofRepo).releaseUnsentSparkOnchainProof(request) + verify(lightningRepo, never()).sparkWithdrawalOutcome(any(), any(), any()) + verify(privatePaykitRepo).releasePrivatePaymentList(any(), any()) + } + + @Test + fun `an uncertain spark send keeps the request in flight`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unknown) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(3) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + val privateContext = privatePaymentContext(7uL) + whenever(privatePaykitRepo.consumePrivatePaymentList("pubkycontact", privateContext)) + .thenReturn(Result.success(Unit)) + setActiveContactPaymentContext("pubkycontact", privateContext) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) + } + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( service = "spark", endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), From a800647c6b02d4cbf97fc986dbbe7d89c98380ae Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 04:35:37 +0100 Subject: [PATCH 17/90] fix: settle the withdrawal journal only after a fresh sync --- .../java/to/bitkit/repositories/SparkRepo.kt | 30 ++++++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 29 ++++++++++++++++++ 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6345d935fc..8ef57d7531 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -131,6 +131,10 @@ class SparkRepo @Inject constructor( private val sendsInFlight = ConcurrentHashMap.newKeySet() + /** A withdrawal's send call is running, so its journal entry must not be settled before Spark lists it. */ + @Volatile + private var isWithdrawing = 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 @@ -164,12 +168,13 @@ class SparkRepo @Inject constructor( 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() } + val synced = runSuspendCatching { sparkService.syncWallet() } .onSuccess { _state.update { it.copy(hasSynced = true) } } .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } + .isSuccess _exitStateChanged.emit(Unit) refresh() - syncActivities() + syncActivities(settleJournal = synced) }.onFailure { Logger.error("Failed to start Spark wallet", it, context = TAG) } @@ -516,7 +521,7 @@ class SparkRepo @Inject constructor( amountSats: ULong, earlierTxids: Set, ): SparkWithdrawalOutcome = withContext(bgDispatcher) { - if (!_state.value.hasSynced) return@withContext SparkWithdrawalOutcome.Unknown + if (!_state.value.hasSynced || isWithdrawing) return@withContext SparkWithdrawalOutcome.Unknown val txid = sparkService.listPayments().firstNotNullOfOrNull { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@firstNotNullOfOrNull null withdraw.txId.takeIf { @@ -556,9 +561,15 @@ class SparkRepo @Inject constructor( if (!onBeforeSend()) throw PaymentAbortedBeforeSend() val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids, tags) cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } - val payment = runSuspendCatching { sparkService.send(prepared) }.getOrElse { + isWithdrawing = true + val sent = try { + runSuspendCatching { sparkService.send(prepared) } + } finally { + isWithdrawing = false + } + val payment = sent.getOrElse { // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. - runSuspendCatching { sparkService.syncWallet() }.onSuccess { syncActivities() } + runSuspendCatching { sparkService.syncWallet() }.onSuccess { syncActivities(settleJournal = true) } throw it } Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) @@ -809,10 +820,13 @@ class SparkRepo @Inject constructor( .toSet() } - private suspend fun syncActivities() { + /** + * Records Spark's payments as activity. With [settleJournal], after a sync that just succeeded, a journaled + * withdrawal the list still lacks never sent, unless it is still being sent in this process. + */ + private suspend fun syncActivities(settleJournal: Boolean) { sparkService.listPayments().forEach { recordActivity(it) } - // A synced list that still lacks the journaled withdrawal proves the app was killed before Spark sent it. - if (_state.value.hasSynced) { + if (settleJournal && !isWithdrawing) { cacheStore.data.first().pendingSparkWithdrawal?.let { journal -> Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f537794f50..595eeeb699 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -420,6 +420,35 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(5_000uL, cacheData.value.pendingSparkWithdrawal?.amountSats) } + @Test + fun `a foreground during an in-flight withdrawal keeps its journal until spark lists it`() = test { + val sut = journaledSpark() + val sendGate = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { + sendGate.await() + contactWithdrawal() + } + val withdrawal = async { sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") } + runCurrent() + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + + var offline = true + whenever { sparkService.syncWallet() }.thenAnswer { if (offline) throw SdkException.Generic("offline") } + sut.start(0).getOrThrow() + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + offline = false + sut.start(0).getOrThrow() + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + + sendGate.complete(Unit) + assertEquals("withdrawal", withdrawal.await().getOrThrow()) + + assertNull(cacheData.value.pendingSparkWithdrawal) + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) + } + private suspend fun journaledSpark(): SparkRepo { whenever { cacheStore.update(any()) }.doSuspendableAnswer { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) From 127c61745da6a97c155981631dfbb3016cf32f3e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:27:53 +0100 Subject: [PATCH 18/90] fix: block the swipe when a source switch finds no route --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 +- .../viewmodels/AppViewModelSendFlowTest.kt | 94 +++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index df595dafd4..79728778ab 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4414,7 +4414,10 @@ class AppViewModel @Inject constructor( // A source switch on Confirm asks the router again, for a request (no amount step) or a route already decided. if (activeIncomingPaymentRequest() != null || paykitRouteDecided) { _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { - routePaykitPayment(it) + // A refused route leaves no leg or invoice to pay; switching the source again recomputes validity. + if (routePaykitPayment(it) == PaykitRouteOutcome.Refused) { + _sendUiState.update { state -> state.copy(isAmountInputValid = false) } + } } } reviewFundingSourceChange(current, canReviewInPlace, wasReviewed) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3ebbd13e53..a11fe17084 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12297,6 +12297,100 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) } + @Test + fun `a refused reroute on confirmation blocks the swipe before the private list is consumed`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setActiveContactPaymentContext(testPublicKey, privateContext) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark can't cover the fee"))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + sut.setSendEvent(SendEvent.SwipeToPay) + advanceUntilIdle() + // SendConfirmScreen sends PayConfirmed only once the swipe set shouldConfirmPay. + if (sut.sendUiState.value.shouldConfirmPay) sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.isAmountInputValid, "a refused route must keep the swipe disabled") + verify(privatePaykitRepo, never()).consumePrivatePaymentList(any(), any()) + } + + @Test + fun `switching back after a refused reroute pays the contact from its private list`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + stubSuccessfulOnchainSend(leg.endpoint.value, leg.deliveredSat) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setActiveContactPaymentContext(testPublicKey, privateContext) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark can't cover the fee"))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "switching back must re-enable the swipe") + confirmCurrentPayment() + + verify(privatePaykitRepo).consumePrivatePaymentList(testPublicKey, privateContext) + verify(lightningRepo).sendOnChain( + address = eq(leg.endpoint.value), + sats = any(), + speed = anyOrNull(), + utxosToSpend = anyOrNull(), + feeRates = anyOrNull(), + isTransfer = any(), + channelId = anyOrNull(), + isMaxAmount = any(), + tags = any(), + beforeSendAttempt = any(), + onBroadcast = any(), + requestId = anyOrNull(), + orderId = anyOrNull(), + transferContext = anyOrNull(), + payerIdentity = anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + } + @Test fun `spark leg fees count in the payment warnings`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact").copy(deliveredSat = 1_000uL, debitSat = 2_000uL) From 30ca31d918a2ff75bcc680f38d164eda2f28b222 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:27:53 +0100 Subject: [PATCH 19/90] fix: release the private list of an unsent spark withdrawal --- .../repositories/PaykitPaymentProofRepo.kt | 1 + .../PaykitPaymentProofRepoTest.kt | 83 +++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 69b0a1ea75..9f5b2dd55e 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -444,6 +444,7 @@ class PaykitPaymentProofRepo @Inject constructor( is SparkWithdrawalOutcome.Sent -> completeSparkOnchainProofLocked(proof, outcome.txid) SparkWithdrawalOutcome.Unsent -> { Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) + releaseDeniedPrivateConsumption(proof) removeProofsLocked { it == proof } false } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 7e0863be41..5d29bd15c5 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -930,6 +930,89 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() } + @Test + fun `a spark withdrawal proof that never sent gives back its private list on reconcile`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever(privatePaykitRepo.releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL)) + .thenReturn(Result.success(Unit)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + paymentProofRepo().reconcile() + + assertTrue(storedProofs.isEmpty()) + verify(privatePaykitRepo).releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL) + } + + @Test + fun `a spark withdrawal released on reconcile lets the request pay from the private list again`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever(privatePaykitRepo.releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL)) + .thenReturn(Result.success(Unit)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + val relaunched = paymentProofRepo() + relaunched.reconcile() + + relaunched.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + relaunched.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + + assertEquals(7uL, storedProofs.single().privatePaymentListVersion) + verify(privatePaykitRepo, times(1)).releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL) + } + + @Test + fun `a spark withdrawal proof keeps its private list when the release fails on reconcile`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever(privatePaykitRepo.releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL)) + .thenReturn(Result.failure(AppError("homeserver unavailable"))) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + paymentProofRepo().reconcile() + + assertEquals(7uL, storedProofs.single().privatePaymentListVersion) + } + @Test fun `a spark retry decides a lightning proof the node failed`() = test { val record = paymentRequestRecord() From 951c0a69d2350785dc597762a1c4710a420a76e5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:52:22 +0100 Subject: [PATCH 20/90] fix: recheck a spark-routed request's amount before confirm --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 + .../viewmodels/AppViewModelSendFlowTest.kt | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 79728778ab..20650cc26e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4143,6 +4143,8 @@ class AppViewModel @Inject constructor( _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { preferSparkWhenSavingsShort(it) if (routePaykitPayment(it) == PaykitRouteOutcome.Refused) return false + // Validity was set against the source before routing; the route may have moved the payment to Spark. + _sendUiState.update { state -> state.copy(isAmountInputValid = validateAmount(state.amount)) } } if (!bindBitcoinRequestTerms()) return false requireCurrentPaymentPreparation(walletGeneration) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index a11fe17084..1ef0172f70 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -17840,6 +17840,43 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `an onchain request routed to spark opens confirmation with the swipe on`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 20_000uL, debitSat = 20_300uL) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 20_000u), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 5_000u, maxSendLightningSats = 50_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(privatePaykitRepo.beginPaymentRequest(request)).thenReturn( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))), + ) + + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + advanceUntilIdle() + + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertTrue( + sut.sendUiState.value.isAmountInputValid, + "a spark leg that covers the request must enable the swipe", + ) + } + @Test fun `fixed dollar request accepting USDT opens bitcoin confirmation while USDT is off`() = test { enablePaykitUi() From 72ee2a5cd5564d37790b203092415dbecff28d4c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 12:52:24 +0100 Subject: [PATCH 21/90] fix: keep a listed spark withdrawal's journal until it saves --- .../java/to/bitkit/repositories/SparkRepo.kt | 28 +++++++++++-------- .../to/bitkit/repositories/SparkRepoTest.kt | 13 +++++++++ 2 files changed, 29 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 aedb70ff33..93033ebe5f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -865,13 +865,14 @@ class SparkRepo @Inject constructor( * withdrawal the list still lacks never sent, unless it is still being sent in this process. */ private suspend fun syncActivities(settleJournal: Boolean) { - sparkService.listPayments().forEach { recordActivity(it) } - if (settleJournal && !isWithdrawing) { - cacheStore.data.first().pendingSparkWithdrawal?.let { journal -> - Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) - cacheStore.update { it.copy(pendingSparkWithdrawal = null) } - } - } + val payments = sparkService.listPayments() + payments.forEach { recordActivity(it) } + if (!settleJournal || isWithdrawing) return + val journal = cacheStore.data.first().pendingSparkWithdrawal ?: return + // A listed withdrawal whose activity failed to save keeps its journal for the next sync to retry. + if (payments.any { journal.matches(it) }) return + Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) + cacheStore.update { it.copy(pendingSparkWithdrawal = null) } } private suspend fun onSdkEvent(event: SdkEvent) { @@ -950,10 +951,7 @@ class SparkRepo @Inject constructor( val txid = withdraw.txId val existing = (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1 ?.takeIf { it.txType == PaymentType.SENT } - val journal = cacheStore.data.first().pendingSparkWithdrawal?.takeIf { - it.address == withdraw.destinationAddress && it.amountSats == payment.amount.toLong().toULong() && - txid !in it.earlierTxids - } + val journal = cacheStore.data.first().pendingSparkWithdrawal?.takeIf { it.matches(payment) } if (existing == null && journal == null) return val activity = OnchainActivity.create( id = txid, @@ -1023,7 +1021,13 @@ data class PendingSparkWithdrawal( /** Withdrawals to [address] listed before this attempt, which never settle it. */ val earlierTxids: Set = emptySet(), val tags: List = emptyList(), -) +) { + fun matches(payment: Payment): Boolean { + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return false + return address == withdraw.destinationAddress && amountSats == payment.amount.toLong().toULong() && + withdraw.txId !in earlierTxids + } +} /** What became of a Spark withdrawal attempt, from Spark's payment list. */ sealed interface SparkWithdrawalOutcome { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index cc3de395a9..27d15d0dc0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -320,6 +320,19 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(AppError("disk full"))) + + journaledSpark() + + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + } + @Test fun `a withdrawal refused right before it sends writes no journal`() = test { val sut = journaledSpark() From 50209236019e26ee40985503e0be1d21b3864024 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:44:25 +0100 Subject: [PATCH 22/90] fix: keep a starting spark withdrawal's proof from reconcile --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 8 +++++--- .../java/to/bitkit/repositories/SparkRepoTest.kt | 14 ++++++++++++++ 2 files changed, 19 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 7c688a5c7e..c4dc608bef 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -570,11 +570,13 @@ class SparkRepo @Inject constructor( // The user confirmed the leg's debit; a quote that rose since then needs a new confirmation. if (maxDebitSats != null && debitSats > maxDebitSats) throw SparkError.WithdrawalFeeChanged() val earlierTxids = withdrawalTxidsTo(address) - if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids, tags) - cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } + // The proof onBeforeSend starts has no journal yet, so the attempt reads as in flight from here on and + // a reconcile meanwhile never drops that proof as unsent. isWithdrawing = true val sent = try { + if (!onBeforeSend()) throw PaymentAbortedBeforeSend() + val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids, tags) + cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } runSuspendCatching { sparkService.send(prepared) } } finally { isWithdrawing = false diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 7a73b04a5a..eb9e0f9253 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -393,6 +393,20 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a withdrawal whose proof is starting reads as in flight before its journal is written`() = test { + val sut = journaledSpark() + var outcomeWhileStarting: SparkWithdrawalOutcome? = null + + sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { + // A reconcile in this window must not drop the proof the send is about to pay. + outcomeWhileStarting = sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()) + true + }) + + assertEquals(SparkWithdrawalOutcome.Unknown, outcomeWhileStarting) + } + @Test fun `a withdrawal to a contact is not marked as a transfer`() = test { val sent = OnchainActivity.create( From 8c601a0a8b134cd0cca723567edf930325da01b0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:55:57 +0100 Subject: [PATCH 23/90] fix: keep an unlisted spark withdrawal open for a grace period --- .../java/to/bitkit/repositories/SparkRepo.kt | 20 ++++++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 24 +++++++++++++++++++ 2 files changed, 42 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 c4dc608bef..6afd5825b9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -65,6 +65,7 @@ import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import breez_sdk_spark.PaymentType as SparkPaymentType @@ -105,6 +106,9 @@ class SparkRepo @Inject constructor( /** Tries to learn the outcome of a send whose result was lost while Spark cannot list its payments. */ private const val SETTLE_ATTEMPTS = 10 + /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ + private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes + private val SETTLE_RETRY_INTERVAL = 30.seconds /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ @@ -575,7 +579,14 @@ class SparkRepo @Inject constructor( isWithdrawing = true val sent = try { if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - val journal = PendingSparkWithdrawal(address, amountSats, contact, earlierTxids, tags) + val journal = PendingSparkWithdrawal( + address, + amountSats, + contact, + earlierTxids, + tags, + startedAt = clock.now().epochSeconds, + ) cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } runSuspendCatching { sparkService.send(prepared) } } finally { @@ -876,7 +887,8 @@ class SparkRepo @Inject constructor( /** * Records Spark's payments as activity. With [settleJournal], after a sync that just succeeded, a journaled - * withdrawal the list still lacks never sent, unless it is still being sent in this process. + * withdrawal the list still lacks never sent, unless it is still being sent in this process or started less than + * [UNLISTED_WITHDRAWAL_GRACE] ago. */ private suspend fun syncActivities(settleJournal: Boolean) { val payments = sparkService.listPayments() @@ -885,6 +897,8 @@ class SparkRepo @Inject constructor( val journal = cacheStore.data.first().pendingSparkWithdrawal ?: return // A listed withdrawal whose activity failed to save keeps its journal for the next sync to retry. if (payments.any { journal.matches(it) }) return + // Spark may list a withdrawal it just sent only on a later sync, so an unlisted one stays open for a while. + if (clock.now().epochSeconds < journal.startedAt + UNLISTED_WITHDRAWAL_GRACE.inWholeSeconds) return Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } } @@ -1035,6 +1049,8 @@ data class PendingSparkWithdrawal( /** Withdrawals to [address] listed before this attempt, which never settle it. */ val earlierTxids: Set = emptySet(), val tags: List = emptyList(), + /** Epoch seconds the attempt started, which keeps it open while Spark may still list it. */ + val startedAt: Long = 0, ) { fun matches(payment: Payment): Boolean { val withdraw = payment.details as? PaymentDetails.Withdraw ?: return false diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index eb9e0f9253..f331852616 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -369,6 +369,30 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `keeps an unlisted withdrawal open until its grace period passes`() = test { + val sut = journaledSpark() + whenever(sparkService.send(any())).doSuspendableAnswer { throw SdkException.Generic("timeout") } + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertEquals(now.epochSeconds, cacheData.value.pendingSparkWithdrawal?.startedAt) + assertEquals( + SparkWithdrawalOutcome.Unknown, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A sync right after the send may not list the withdrawal yet, so it is never released as unsent", + ) + cacheData.update { + it.copy( + pendingSparkWithdrawal = it.pendingSparkWithdrawal?.copy( + startedAt = now.epochSeconds - 10.minutes.inWholeSeconds, + ), + ) + } + sut.start(0).getOrThrow() + assertNull(cacheData.value.pendingSparkWithdrawal) + } + @Test fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { cacheData.update { From 3543bc81d6798081196ba5c5e7348d8c83f67f0c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:02:14 +0100 Subject: [PATCH 24/90] fix: reroute every source switch after spark finds no route --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 6 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 43 +++++++++++++++++++ 2 files changed, 47 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 39b5692705..da4af41fd0 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -475,7 +475,7 @@ class AppViewModel @Inject constructor( private val processedPayments = mutableSetOf() private val contactPaymentContextLock = Any() - /** The Paykit router picked this payment's way on Continue or a request's confirm step, so a switch reroutes. */ + /** The Paykit router was asked for this payment's way on Continue or a request's confirm, so a switch reroutes. */ @Volatile private var paykitRouteDecided = false private var activeContactPaymentContext: ContactPaymentContext? = null @@ -4709,7 +4709,9 @@ class AppViewModel @Inject constructor( toast(it) return PaykitRouteOutcome.Refused } - paykitRouteDecided = picked !is PaykitRoute.None + // Once the router answered, even with no route, every later source switch asks it again: a stale source + // must never fall through to a payment the router never picked. + paykitRouteDecided = true return when (picked) { is PaykitRoute.Direct -> { payDirectEndpoint(route, picked.endpoint) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 5bdd1358ea..05efa01a62 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12391,6 +12391,49 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `spending retried after a refused reroute and a switch back routes through spark again`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())) + .thenReturn(Result.success("txid")) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setActiveContactPaymentContext(testPublicKey, privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark quote failed"))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + + assertEquals( + leg, + sut.sendUiState.value.routedPaykitRoute?.serviceLeg, + "the quote recovered, so Spark carries it", + ) + confirmCurrentPayment() + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq(testPublicKey), any(), any()) + } + @Test fun `spark leg fees count in the payment warnings`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact").copy(deliveredSat = 1_000uL, debitSat = 2_000uL) From 590f925c3d5e24ce54d38f22c820555d6ef1c6d9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:23:37 +0100 Subject: [PATCH 25/90] fix: settle a spark send's allowance attempt on reconcile --- .../repositories/PaykitAllowanceExecutor.kt | 21 ++++++++++ .../repositories/PaykitPaymentProofRepo.kt | 7 +++- .../PaykitAllowanceExecutorTest.kt | 16 ++++++++ .../PaykitPaymentProofRepoTest.kt | 41 +++++++++++++++++++ 4 files changed, 84 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 2e1123c70d..393d1c4cf6 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -1097,6 +1097,27 @@ class PaykitAllowanceExecutor @Inject constructor( } } + /** + * Records a manual on-chain send of [requestId] that Spark's list later shows sent as succeeded with its + * [transactionId], so an attempt left unknown no longer holds the request. Throws when an outcome could not be + * recorded, so the proof that found it stays for another pass. + */ + suspend fun onchainSendSettled(payerIdentity: String?, requestId: PaykitPaymentRequestId, transactionId: String) { + val identity = activeIdentity?.takeIf { PubkyPublicKeyFormat.matches(it, payerIdentity) } ?: return + withContext(ioDispatcher) { + settleMutex.withLock { + val attempts = localState(identity).journal.filter { + it.requestId == requestId && !it.isAutomatic && it.paymentHash == null && + it.stage in SETTLEABLE_STAGES + } + for (attempt in attempts) { + updateJournalEntry(attempt.attemptId, identity) { it.copy(transactionId = transactionId) } + record(attempt.attemptId, PaymentOutcome.SUCCEEDED, identity) + } + } + } + } + // endregion // region Helpers diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 9f5b2dd55e..2d224a642b 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -440,9 +440,14 @@ class PaykitPaymentProofRepo @Inject constructor( amount, proof.onchainMatchingTransactionIdsBeforeAttempt, ) + // The request's allowance attempt is settled first: a failed ledger write keeps the proof for the next pass. return when (outcome) { - is SparkWithdrawalOutcome.Sent -> completeSparkOnchainProofLocked(proof, outcome.txid) + is SparkWithdrawalOutcome.Sent -> { + allowanceExecutor.get().onchainSendSettled(proof.identity, proof.requestId, outcome.txid) + completeSparkOnchainProofLocked(proof, outcome.txid) + } SparkWithdrawalOutcome.Unsent -> { + allowanceExecutor.get().onchainSendReleased(proof.identity, proof.requestId) Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) releaseDeniedPrivateConsumption(proof) removeProofsLocked { it == proof } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index 03126ce52c..fde2a531df 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -1805,6 +1805,22 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { assertEquals(Stage.FAILED, sut.localState(identity).journal.single().stage) } + @Test + fun `a manual on-chain payment found sent later is recorded succeeded with its txid`() = test { + sut.activate(identity) + val request = fixtures.paymentRequest() + val attemptId = checkNotNull(sut.beginManualPayment(request, fixtures.onchainIdentifier).getOrThrow()) + sut.finishManualPayment(attemptId, PaymentOutcome.UNKNOWN) + recordedOutcomes.clear() + + sut.onchainSendSettled(identity, request.id, "c".repeat(64)) + + assertEquals(listOf(PaymentOutcomeReport(attemptId, PaymentOutcome.SUCCEEDED)), recordedOutcomes) + val entry = sut.localState(identity).journal.single() + assertEquals(Stage.SUCCEEDED, entry.stage) + assertEquals("c".repeat(64), entry.transactionId) + } + @Test fun `manual payment fails when the request is already recorded`() = test { sut.activate(identity) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 5d29bd15c5..5168a1c8a6 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -930,6 +930,47 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() } + @Test + fun `a spark withdrawal that never sent fails its allowance attempt on reconcile`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + whenever(allowanceExecutor.onchainSendReleased(any(), any())).thenThrow(RuntimeException("ledger")) + + paymentProofRepo().reconcile() + assertTrue(storedProofs.single().paymentStarted, "A ledger write that fails keeps the proof for the next pass") + + reset(allowanceExecutor) + paymentProofRepo().reconcile() + + verify(allowanceExecutor).onchainSendReleased(identity, request.id) + assertTrue(storedProofs.isEmpty()) + } + + @Test + fun `a spark withdrawal found sent settles its allowance attempt with the txid on reconcile`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + + paymentProofRepo().reconcile() + + verify(allowanceExecutor).onchainSendSettled(identity, request.id, txid) + } + @Test fun `a spark withdrawal proof that never sent gives back its private list on reconcile`() = test { val record = paymentRequestRecord() From b22c2496cbd9864d8873cb5a6ab9dc6e03fdcd31 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:52:53 +0100 Subject: [PATCH 26/90] fix: resolve a pending spark send once reconcile finds it sent --- .../repositories/PaykitPaymentProofRepo.kt | 3 ++- .../PaykitPaymentProofRepoTest.kt | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 2d224a642b..9dff562b06 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -467,7 +467,8 @@ class PaykitPaymentProofRepo @Inject constructor( onchainAcceptanceVerified = true, ) proofs[index] = completed - return persistAndSubmit(listOf(completed), proofs) + // The pending screen of an uncertain Spark send waits on this resolution. + return persistAndSubmit(listOf(completed), proofs).also { publishOnchainResolution(completed, txid) } } suspend fun completeLightningPayment(paymentHash: String, preimage: String?) = withContext(ioDispatcher) { diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 5168a1c8a6..b365db886d 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -971,6 +971,25 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { verify(allowanceExecutor).onchainSendSettled(identity, request.id, txid) } + @Test + fun `a spark withdrawal found sent on reconcile resolves the pending payment`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + + repo.reconcile() + + val resolution = repo.onchainPaymentResolutions.value.single() + assertEquals(request.id, resolution.requestId) + assertEquals(txid, resolution.transactionId) + } + @Test fun `a spark withdrawal proof that never sent gives back its private list on reconcile`() = test { val record = paymentRequestRecord() From 03f22e60bb21b092dd41802fe90c3150b59d4c0f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:36:32 +0100 Subject: [PATCH 27/90] fix: fail a pending spark send once reconcile finds it unsent --- .../repositories/PaykitPaymentProofRepo.kt | 15 +++++ .../java/to/bitkit/services/SparkService.kt | 3 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 23 ++++++++ .../PaykitPaymentProofRepoTest.kt | 17 ++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 58 +++++++++++++++++++ 5 files changed, 116 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 9dff562b06..d00aafa653 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -120,6 +120,12 @@ data class PaykitOnchainPaymentProofResolution( val amountSats: ULong? = null, ) +/** A request whose uncertain Spark withdrawal Spark showed never sent, so its pending payment can fail. */ +data class PaykitSparkWithdrawalRelease( + val identity: String, + val requestId: PaykitPaymentRequestId, +) + @Singleton class PaykitPaymentProofRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, @@ -186,6 +192,8 @@ class PaykitPaymentProofRepo @Inject constructor( } private val _onchainPaymentResolutions = MutableStateFlow>(emptyList()) val onchainPaymentResolutions = _onchainPaymentResolutions.asStateFlow() + private val _sparkWithdrawalReleases = MutableStateFlow>(emptyList()) + val sparkWithdrawalReleases = _sparkWithdrawalReleases.asStateFlow() suspend fun prepare( request: PaykitPaymentRequest, @@ -451,6 +459,9 @@ class PaykitPaymentProofRepo @Inject constructor( Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) releaseDeniedPrivateConsumption(proof) removeProofsLocked { it == proof } + // The pending screen of an uncertain Spark send waits on this to fail it. + val release = PaykitSparkWithdrawalRelease(proof.identity, proof.requestId) + _sparkWithdrawalReleases.update { if (release in it) it else it + release } false } SparkWithdrawalOutcome.Unknown -> false @@ -1583,6 +1594,10 @@ class PaykitPaymentProofRepo @Inject constructor( } } + fun consumeSparkWithdrawalRelease(release: PaykitSparkWithdrawalRelease) { + _sparkWithdrawalReleases.update { it - release } + } + fun consumeOnchainPaymentResolution(resolution: PaykitOnchainPaymentProofResolution) { _onchainPaymentResolutions.update { it - resolution } } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index fe169f9782..bc7d89ced1 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -300,6 +300,9 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me class WithdrawalPending : SparkError("An earlier Spark withdrawal is still settling") + /** Spark's list shows the withdrawal never went out. */ + class WithdrawalNotSent : SparkError("Spark never sent the withdrawal") + /** * 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. diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index ba2543fc3b..15b145a8c6 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -205,6 +205,7 @@ import to.bitkit.repositories.PaykitPaymentRequestRefreshMode import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTarget import to.bitkit.repositories.PaykitRouteRepo +import to.bitkit.repositories.PaykitSparkWithdrawalRelease import to.bitkit.repositories.PaykitSubscription import to.bitkit.repositories.PaykitSubscriptionDraft import to.bitkit.repositories.PaykitSubscriptionId @@ -792,6 +793,7 @@ class AppViewModel @Inject constructor( observePaykitPaymentRequestConnectivity() observeIncomingPaykitPaymentRequests() observePaykitOnchainPaymentResolution() + observePaykitSparkWithdrawalReleases() observePaykitAllowanceEvents() observeSendEvents() viewModelScope.launch { @@ -1163,6 +1165,27 @@ class AppViewModel @Inject constructor( } } + private fun observePaykitSparkWithdrawalReleases() { + viewModelScope.launch { + combine(paykitPaymentProofRepo.sparkWithdrawalReleases, pubkyRepo.publicKey) { releases, _ -> + releases + }.collect { releases -> + releases.forEach(::handlePaykitSparkWithdrawalRelease) + } + } + } + + private fun handlePaykitSparkWithdrawalRelease(release: PaykitSparkWithdrawalRelease) { + if (!PubkyPublicKeyFormat.matches(pubkyRepo.publicKey.value, release.identity)) return + paykitPaymentProofRepo.consumeSparkWithdrawalRelease(release) + if (uncertainOnchainPaymentRequestId != release.requestId || _currentSheet.value !is Sheet.Send) return + uncertainOnchainPaymentRequestId = null + // Spark never sent it and its proof is released, so the request can be tried again. + setSendEffect( + SendEffect.NavigateToError(SparkError.WithdrawalNotSent().toSendFailureDetails(context)), + ) + } + private fun handlePaykitOnchainPaymentResolution(resolution: PaykitOnchainPaymentProofResolution) { if (!PubkyPublicKeyFormat.matches(pubkyRepo.publicKey.value, resolution.identity)) return if (resolution.walletId != WalletScope.default) { diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index b365db886d..713593c3b2 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -990,6 +990,23 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertEquals(txid, resolution.transactionId) } + @Test + fun `a spark withdrawal found unsent on reconcile fails the pending payment`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + repo.reconcile() + + assertEquals(listOf(PaykitSparkWithdrawalRelease(identity, request.id)), repo.sparkWithdrawalReleases.value) + } + @Test fun `a spark withdrawal proof that never sent gives back its private list on reconcile`() = test { val record = paymentRequestRecord() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index cf9d0f8408..93f3bcb37b 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -61,6 +61,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -192,6 +193,7 @@ import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTarget import to.bitkit.repositories.PaykitRecurrenceUnit import to.bitkit.repositories.PaykitRouteRepo +import to.bitkit.repositories.PaykitSparkWithdrawalRelease import to.bitkit.repositories.PaykitSubscription import to.bitkit.repositories.PaykitSubscriptionId import to.bitkit.repositories.PaykitSubscriptionMetadata @@ -258,6 +260,7 @@ import java.net.URLEncoder import java.nio.charset.StandardCharsets import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -351,6 +354,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitPaymentRequestHistory = MutableStateFlow>(emptyList()) private val paykitSubscriptions = MutableStateFlow>(emptyList()) private val onchainPaymentResolutions = MutableStateFlow>(emptyList()) + private val sparkWithdrawalReleases = MutableStateFlow>(emptyList()) private val proofStateVersion = MutableStateFlow(0L) private val usdtStateVersion = MutableStateFlow(0L) private val surfacedPaykitPaymentRequestIds = mutableSetOf() @@ -833,6 +837,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(paykitPaymentRequestRepo.isExpired(any())).thenReturn(false) whenever(paykitPaymentRequestRepo.isProcessing(any())).thenReturn(false) whenever(paykitPaymentProofRepo.onchainPaymentResolutions).thenReturn(onchainPaymentResolutions) + whenever(paykitPaymentProofRepo.sparkWithdrawalReleases).thenReturn(sparkWithdrawalReleases) whenever(paykitAllowanceRepo.events).thenReturn(MutableSharedFlow()) whenever(paykitAllowanceRepo.isUpdatingFlow).thenReturn(allowanceUpdating) whenever(paykitAllowanceRepo.offersToAnnounce).thenReturn(MutableStateFlow(emptyList())) @@ -12219,6 +12224,59 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `a pending spark send of a request fails once its withdrawal is found unsent`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val release = PaykitSparkWithdrawalRelease(testPublicKey, request.id) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(false) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unknown) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(3) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + + confirmCurrentPayment() + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + pubkyPublicKey.value = testPublicKey + sparkWithdrawalReleases.value = listOf(release) + runCurrent() + + assertIs(effects.last(), "a withdrawal that never sent can be tried again") + verify(paykitPaymentProofRepo).consumeSparkWithdrawalRelease(release) + } + @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 20ac89e4ae025ee079713d7f74e3748152a4a4f3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:48:14 +0100 Subject: [PATCH 28/90] fix: end a spark withdrawal spark returns as failed as a refusal --- .../java/to/bitkit/repositories/SparkRepo.kt | 3 +++ .../to/bitkit/repositories/SparkRepoTest.kt | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1f47a54656..654d2e654e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -604,6 +604,9 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() }.onFailure { Logger.warn("Failed to refresh Spark after withdrawal '${payment.id}'", it, context = TAG) } + // A failed withdrawal paid nothing: its journal closed as recorded, so the caller sees it unsent and + // releases the proof, private list and allowance attempt instead of showing success. + if (payment.status == PaymentStatus.FAILED) throw SparkError.WithdrawalNotSent() (payment.details as? PaymentDetails.Withdraw)?.txId ?: payment.id }.onFailure { Logger.error("Failed to withdraw to a Paykit contact with Spark", 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 f340528104..9ef6827caf 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -485,6 +485,25 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(SparkWithdrawalOutcome.Unknown, outcomeWhileStarting) } + @Test + fun `a withdrawal spark returns as failed is not reported as sent`() = test { + val sut = journaledSpark() + val failed = contactWithdrawal().copy(status = PaymentStatus.FAILED) + whenever(sparkService.send(any())).thenReturn(failed) + whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(failed)) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + assertNull(result.getOrNull()) + assertIs(result.exceptionOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals( + SparkWithdrawalOutcome.Unsent, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "The proof, private list and allowance attempt are released as for any unsent withdrawal", + ) + } + @Test fun `a withdrawal to a contact is not marked as a transfer`() = test { val sent = OnchainActivity.create( From d79cceddf3bb3653c9487732e2a319c5d3699ef5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:03:02 +0100 Subject: [PATCH 29/90] fix: drop a paykit route that returns after its payment changed --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 15 +++++-- .../viewmodels/AppViewModelSendFlowTest.kt | 40 +++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 15b145a8c6..c035444e01 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4165,7 +4165,8 @@ class AppViewModel @Inject constructor( } _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { preferSparkWhenSavingsShort(it) - if (routePaykitPayment(it) == PaykitRouteOutcome.Refused) return false + val outcome = routePaykitPayment(it) + if (outcome == PaykitRouteOutcome.Refused || outcome == PaykitRouteOutcome.Stale) return false // Validity was set against the source before routing; the route may have moved the payment to Spark. _sendUiState.update { state -> state.copy(isAmountInputValid = validateAmount(state.amount)) } } @@ -4691,7 +4692,7 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) return } - PaykitRouteOutcome.Refused -> return + PaykitRouteOutcome.Refused, PaykitRouteOutcome.Stale -> return PaykitRouteOutcome.Direct -> Unit } } @@ -4715,6 +4716,8 @@ class AppViewModel @Inject constructor( */ private suspend fun routePaykitPayment(route: PaykitRouteUi): PaykitRouteOutcome { val state = _sendUiState.value + val generation = sendStateGeneration + val contact = synchronized(contactPaymentContextLock) { activeContactPaymentContext } val fromSpending = state.payMethod == SendMethod.LIGHTNING val lightningSpendable = if (fromSpending) maxSendableLightningSats() else 0uL val onchainSpendable = if (fromSpending) 0uL else walletRepo.balanceState.value.maxSendOnchainSats @@ -4726,6 +4729,12 @@ class AppViewModel @Inject constructor( onchainSpendableSats = onchainSpendable, quoteServiceLegs = fromSpending && route.offersSparkLeg, ) + // A dismissed or replaced payment's route must never land on the one that followed it. + if (generation != sendStateGeneration || + synchronized(contactPaymentContextLock) { activeContactPaymentContext } !== contact + ) { + return PaykitRouteOutcome.Stale + } _sendUiState.update { it.copy(isLoading = false) } val picked = result.getOrElse { Logger.error("Failed to route Paykit payment", it, context = TAG) @@ -9478,7 +9487,7 @@ data class PaykitRouteUi( val serviceLeg: ServiceRouteLeg? = null, ) -private enum class PaykitRouteOutcome { Direct, Leg, Refused } +private enum class PaykitRouteOutcome { Direct, Leg, Refused, Stale } private fun PaykitEndpoint.isOnchain(): Boolean = MethodId.fromRawValue(methodId)?.isOnchain == true diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 93f3bcb37b..cda9444f36 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12277,6 +12277,46 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitPaymentProofRepo).consumeSparkWithdrawalRelease(release) } + @Test + fun `a route that returns after its payment was dismissed never lands on the next payment`() = test { + val legA = sparkRouteLeg("bcrt1qcontacta") + val endpointB = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qcontactb") + val quote = CompletableDeferred>() + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quote.await() } + setActiveContactPaymentContext("pubkycontacta", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = legA.endpoint.value, + amount = legA.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(legA.endpoint), offersSparkLeg = true), + ), + ) + sut.showSheet(Sheet.Send(SendRoute.Amount)) + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + + sut.hideSheet() + setActiveContactPaymentContext("pubkycontactb", privatePaymentContext(8uL)) + val stateB = SendUiState( + address = endpointB.value, + amount = 2_000uL, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(endpointB), offersSparkLeg = true), + ) + setSendState(stateB) + quote.complete(Result.success(PaykitRoute.Service(legA))) + advanceUntilIdle() + + assertEquals( + stateB.paykitRoute, + sut.sendUiState.value.paykitRoute, + "contact A's quote must not route B's payment", + ) + assertEquals(endpointB.value, sut.sendUiState.value.address) + } + @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 4439a24758321a2b3ad7a741726d9490dd6ba088 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:13:00 +0100 Subject: [PATCH 30/90] fix: settle an uncertain spark send to a contact from its journal --- .../to/bitkit/repositories/LightningRepo.kt | 3 + .../java/to/bitkit/repositories/SparkRepo.kt | 19 +++++++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 47 ++++++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 29 ++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 55 +++++++++++++++++++ 5 files changed, 149 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 f4bb5e63ca..a76f8f9f09 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -152,6 +152,9 @@ class LightningRepo @Inject constructor( /** Whether Spark synced its payments since it connected, so its payment list is complete. */ val isSparkSynced: Flow get() = sparkRepo.state.map { it.hasSynced }.distinctUntilChanged() + /** How each journaled Spark contact withdrawal closed. */ + val sparkWithdrawalSettlements: Flow get() = sparkRepo.withdrawalSettlements + private val scope = appScope(bgDispatcher, TAG) private val _eventHandlers = ConcurrentHashMap.newKeySet() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 654d2e654e..44b35d1322 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -163,6 +163,10 @@ class SparkRepo @Inject constructor( val nodeEvents: SharedFlow = _nodeEvents.asSharedFlow() private val _exitStateChanged = MutableSharedFlow(extraBufferCapacity = 1) + private val _withdrawalSettlements = MutableSharedFlow(extraBufferCapacity = 8) + + /** How each journaled contact withdrawal closed, which a pending send screen waits on. */ + val withdrawalSettlements: SharedFlow = _withdrawalSettlements.asSharedFlow() /** Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. */ val exitStateChanged: SharedFlow = _exitStateChanged.asSharedFlow() @@ -906,6 +910,7 @@ class SparkRepo @Inject constructor( if (clock.now().epochSeconds < journal.startedAt + UNLISTED_WITHDRAWAL_GRACE.inWholeSeconds) return Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, null)) } private suspend fun onSdkEvent(event: SdkEvent) { @@ -1014,6 +1019,13 @@ class SparkRepo @Inject constructor( .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } } cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + _withdrawalSettlements.emit( + SparkWithdrawalSettlement( + journal.address, + journal.amountSats, + txid.takeIf { payment.status != PaymentStatus.FAILED }, + ), + ) } } @@ -1068,6 +1080,13 @@ data class PendingSparkWithdrawal( } } +/** A journaled withdrawal to [address] closed: sent as [txid], or never sent when [txid] is null. */ +data class SparkWithdrawalSettlement( + val address: String, + val amountSats: ULong, + val txid: String?, +) + /** What became of a Spark withdrawal attempt, from Spark's payment list. */ sealed interface SparkWithdrawalOutcome { data class Sent(val txid: String) : SparkWithdrawalOutcome diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c035444e01..f9b4c0758b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -227,6 +227,7 @@ import to.bitkit.repositories.QuickPayPaymentFailedError import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo import to.bitkit.repositories.SparkWithdrawalOutcome +import to.bitkit.repositories.SparkWithdrawalSettlement import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -560,6 +561,10 @@ class AppViewModel @Inject constructor( private var deferredSubscriptionNotification: SubscriptionNotificationTarget? = null private var requestedPaymentRequestTags: ImmutableList = persistentListOf() private var uncertainOnchainPaymentRequestId: PaykitPaymentRequestId? = null + + /** The address and amount of the uncertain Spark withdrawal to a contact a pending screen waits on. */ + @Volatile + private var uncertainSparkWithdrawal: Pair? = null private var isPresentingPaymentRequest = false private val isPaymentRequestPollingStopped = MutableStateFlow(false) private var isPaymentRequestOverlayVisible = false @@ -794,6 +799,7 @@ class AppViewModel @Inject constructor( observeIncomingPaykitPaymentRequests() observePaykitOnchainPaymentResolution() observePaykitSparkWithdrawalReleases() + observeSparkWithdrawalSettlements() observePaykitAllowanceEvents() observeSendEvents() viewModelScope.launch { @@ -1165,6 +1171,31 @@ class AppViewModel @Inject constructor( } } + private fun observeSparkWithdrawalSettlements() { + viewModelScope.launch { + lightningRepo.sparkWithdrawalSettlements.collect(::handleSparkWithdrawalSettlement) + } + } + + private fun handleSparkWithdrawalSettlement(settlement: SparkWithdrawalSettlement) { + if (uncertainSparkWithdrawal != (settlement.address to settlement.amountSats)) return + uncertainSparkWithdrawal = null + if (_currentSheet.value !is Sheet.Send) return + val txid = settlement.txid + if (txid != null) { + onSendSuccess(sparkWithdrawalSent(txid, settlement.amountSats)) + return + } + setSendEffect(SendEffect.NavigateToError(SparkError.WithdrawalNotSent().toSendFailureDetails(context))) + } + + private fun sparkWithdrawalSent(txid: String, amountSats: ULong) = NewTransactionSheetDetails( + type = NewTransactionSheetType.ONCHAIN, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = txid, + sats = amountSats.toLong(), + ) + private fun observePaykitSparkWithdrawalReleases() { viewModelScope.launch { combine(paykitPaymentProofRepo.sparkWithdrawalReleases, pubkyRepo.publicKey) { releases, _ -> @@ -6932,6 +6963,7 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { + uncertainSparkWithdrawal = null var earlierTxids: Set? = null val txid = paykitRouteRepo.payServiceLeg( leg, @@ -6991,12 +7023,19 @@ class AppViewModel @Inject constructor( allowanceAttemptId: String?, ) { incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } - val unsent = earlierTxids == null || - lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, earlierTxids) == - SparkWithdrawalOutcome.Unsent - if (!unsent) { + val outcome = earlierTxids?.let { + lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, it) + } + if (outcome is SparkWithdrawalOutcome.Sent && incomingPaymentRequest == null) { + // Spark already lists it, so a contact payment without a request has no proof left to wait on. + finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = outcome.txid) + onSendSuccess(sparkWithdrawalSent(outcome.txid, leg.deliveredSat)) + return + } + if (outcome != null && outcome != SparkWithdrawalOutcome.Unsent) { Logger.warn("Left a Spark withdrawal with an uncertain send result to Spark", error, context = TAG) finishManualAllowancePayment(allowanceAttemptId, succeeded = null) + if (incomingPaymentRequest == null) uncertainSparkWithdrawal = leg.endpoint.value to leg.deliveredSat showUnresolvedOnchainSend(null, leg.deliveredSat, incomingPaymentRequest) return } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 9ef6827caf..7c952f052e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -34,6 +34,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -447,6 +448,34 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a journal that closes tells the pending send how its withdrawal ended`() = test { + val settlements = mutableListOf() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = createSut() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + sut.withdrawalSettlements.collect { settlements += it } + } + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + whenever(sparkService.isConnected).thenReturn(true) + + sut.start(0).getOrThrow() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 5_000uL, null)) } + sut.start(0).getOrThrow() + + assertEquals( + listOf( + SparkWithdrawalSettlement("bcrt1qcontact", 20_000uL, "withdrawal"), + SparkWithdrawalSettlement("bcrt1qcontact", 5_000uL, null), + ), + settlements, + ) + } + @Test fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { cacheData.update { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index cda9444f36..60c038feda 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -220,6 +220,7 @@ import to.bitkit.repositories.SamRockRepo import to.bitkit.repositories.SettledReceiveAddress import to.bitkit.repositories.SettledReceiveInvoice import to.bitkit.repositories.SparkWithdrawalOutcome +import to.bitkit.repositories.SparkWithdrawalSettlement import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -355,6 +356,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitSubscriptions = MutableStateFlow>(emptyList()) private val onchainPaymentResolutions = MutableStateFlow>(emptyList()) private val sparkWithdrawalReleases = MutableStateFlow>(emptyList()) + private val sparkWithdrawalSettlements = MutableSharedFlow(extraBufferCapacity = 8) private val proofStateVersion = MutableStateFlow(0L) private val usdtStateVersion = MutableStateFlow(0L) private val surfacedPaykitPaymentRequestIds = mutableSetOf() @@ -735,6 +737,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(lightningRepo.isRecoveryMode).thenReturn(isRecoveryMode) whenever(lightningRepo.isSparkReady).thenReturn(isSparkReady) + whenever(lightningRepo.sparkWithdrawalSettlements).thenReturn(sparkWithdrawalSettlements) whenever(lightningRepo.nodeEventUpdates).thenReturn(nodeEventUpdates) whenever(lightningRepo.nodeEvents).thenReturn(nodeEventUpdates.map { it.event }) whenever(hwWalletRepo.receivedTxs).thenReturn(hwReceivedTxs) @@ -12317,6 +12320,58 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(endpointB.value, sut.sendUiState.value.address) } + @Test + fun `an uncertain spark send to a contact that spark already lists opens success`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Sent("ab".repeat(32))) + + assertEquals(SendEffect.PaymentSuccess, effects.last()) + assertEquals("ab".repeat(32), sut.successSendUiState.value.paymentHashOrTxId) + } + + @Test + fun `an uncertain spark send to a contact settles from the spark journal`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement("bcrt1qother", leg.deliveredSat, null)) + runCurrent() + assertIs(effects.last(), "another withdrawal's close leaves the screen") + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + runCurrent() + + assertIs(effects.last(), "a withdrawal that never sent can be tried again") + } + + private suspend fun TestScope.uncertainContactSparkSend( + leg: ServiceRouteLeg, + outcome: SparkWithdrawalOutcome, + ): List { + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(outcome) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(3) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + confirmCurrentPayment() + return effects + } + @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 5584e40bc467dcbe1760e04fd6563c7931338a4d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:17:11 +0100 Subject: [PATCH 31/90] fix: settle an expired spark withdrawal journal on each sync --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 2 ++ .../java/to/bitkit/repositories/SparkRepoTest.kt | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 44b35d1322..63fa629798 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -919,6 +919,8 @@ class SparkRepo @Inject constructor( is SdkEvent.Synced -> { _state.update { it.copy(hasSynced = true) } refresh() + // A journal left open past its grace period would block every later withdrawal until a restart. + if (cacheStore.data.first().pendingSparkWithdrawal != null) syncActivities(settleJournal = true) } is SdkEvent.PaymentSucceeded -> onPayment(event.payment) is SdkEvent.PaymentFailed -> onPayment(event.payment) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 7c952f052e..452ca3ae19 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -476,6 +476,18 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `a sync in a long foreground session closes an expired unlisted withdrawal`() = test { + val sut = journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertNull(cacheData.value.pendingSparkWithdrawal, "An expired journal must not block later withdrawals") + assertNull(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull() as? SparkError.WithdrawalPending) + } + @Test fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { cacheData.update { From 0c74a5b9dcf29474a24f811f31e05d74681d6b5f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:50:25 +0100 Subject: [PATCH 32/90] fix: keep an unselected lnurl's limits off a spark leg --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 34 +++++++++-------- .../viewmodels/AppViewModelSendFlowTest.kt | 38 +++++++++++++++++++ 2 files changed, 57 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 2fef6902e4..2210c83550 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4259,7 +4259,9 @@ class AppViewModel @Inject constructor( val state = _sendUiState.value if (state.paykitUsesUsdt) return false val lnurl = state.lnurl as? LnurlParams.LnurlPay - if (state.payMethod == SendMethod.LIGHTNING && lnurl != null && state.amount < lnurl.data.minSendableSat()) { + if (state.payMethod == SendMethod.LIGHTNING && lnurl != null && state.routedPaykitRoute?.serviceLeg == null && + state.amount < lnurl.data.minSendableSat() + ) { return false } return reviewPaykitAmount() @@ -4700,23 +4702,11 @@ class AppViewModel @Inject constructor( if (!prepareCoinSelection()) return val lnurl = _sendUiState.value.lnurl - if (lnurl is LnurlParams.LnurlPay) { - val minSendable = lnurl.data.minSendableSat() - if (_sendUiState.value.amount < minSendable) { - toast( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.wallet__lnurl_pay__error_min__title), - description = context.getString(R.string.wallet__lnurl_pay__error_min__description) - .replace("{amount}", formatMoneyValue(minSendable)), - testTag = "LnurlPayAmountTooLowToast", - ) - return - } - } if (lnurl is LnurlParams.LnurlWithdraw) { setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } + // A Spark leg pays the on-chain endpoint, so the unselected LNURL's limits never apply to it. _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { when (routePaykitPayment(it)) { PaykitRouteOutcome.Leg -> { @@ -4727,6 +4717,19 @@ class AppViewModel @Inject constructor( PaykitRouteOutcome.Direct -> Unit } } + if (lnurl is LnurlParams.LnurlPay) { + val minSendable = lnurl.data.minSendableSat() + if (_sendUiState.value.amount < minSendable) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__lnurl_pay__error_min__title), + description = context.getString(R.string.wallet__lnurl_pay__error_min__description) + .replace("{amount}", formatMoneyValue(minSendable)), + testTag = "LnurlPayAmountTooLowToast", + ) + return + } + } _sendUiState.update { it.copy(isLoading = true) } try { @@ -6499,7 +6502,8 @@ class AppViewModel @Inject constructor( val amount = _sendUiState.value.amount val lnurl = _sendUiState.value.lnurl - val isLnurlPay = lnurl is LnurlParams.LnurlPay + // A Spark leg pays the on-chain endpoint, so it fetches no invoice from the unselected LNURL. + val isLnurlPay = lnurl is LnurlParams.LnurlPay && _sendUiState.value.routedPaykitRoute?.serviceLeg == null if (isLnurlPay) { val amountMsats = lnurl.data.callbackAmountMsats(amount) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 7a79de18f4..c250171c79 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12372,6 +12372,44 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return effects } + @Test + fun `a spark leg to the onchain endpoint ignores the unselected lnurl's limits`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val lnurl = LnurlPayData( + uri = "lnurl1contact", + callback = "https://example.com/callback", + minSendable = 5_000_000uL, + maxSendable = 100_000_000uL, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())) + .thenReturn(Result.success("txid")) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + lnurl = LnurlParams.LnurlPay(lnurl), + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg, "the lnurl's minimum is not the leg's") + confirmCurrentPayment() + + verify(lightningRepo, never()).fetchLnurlInvoice(any(), any(), anyOrNull()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), any()) + } + @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 4bd0732bf1865898e17e9581235028e6ae8b6072 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:55:53 +0100 Subject: [PATCH 33/90] fix: keep a spark withdrawal journal until spark lists it --- .../java/to/bitkit/repositories/SparkRepo.kt | 16 ++++++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 16047ac95a..23f5155853 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -953,7 +953,7 @@ class SparkRepo @Inject constructor( } is SdkEvent.PaymentSucceeded -> onPayment(event.payment) is SdkEvent.PaymentFailed -> onPayment(event.payment) - is SdkEvent.PaymentPending -> recordActivity(event.payment) + is SdkEvent.PaymentPending -> recordActivity(event.payment, settlesJournal = false) is SdkEvent.UnclaimedDeposits -> Logger.warn( "Found '${event.unclaimedDeposits.size}' unclaimed Spark deposits", context = TAG, @@ -972,7 +972,7 @@ class SparkRepo @Inject constructor( // 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) + recordActivity(payment, settlesJournal = false) payment.failedSendHash()?.let { hash -> val latest = lightningSend(hash) val isReleased = latest == SparkLightningSend.NotFound || @@ -982,8 +982,12 @@ class SparkRepo @Inject constructor( payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } - private suspend fun recordActivity(payment: Payment) { - (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it) } + /** + * Records [payment] as activity. Only Spark's list or its send response [settlesJournal]: a payment event can come + * before the list holds the withdrawal, which recovery reads, so its journal stays open until the list shows it. + */ + private suspend fun recordActivity(payment: Payment, settlesJournal: Boolean = true) { + (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return @@ -1025,7 +1029,7 @@ class SparkRepo @Inject constructor( * Records a withdrawal to a Paykit contact as an on-chain send, settling the journal entry it matches. Transfers to * Savings have no row here: the node lists their arrival as the transfer. */ - private suspend fun recordWithdrawal(payment: Payment, withdraw: PaymentDetails.Withdraw) { + private suspend fun recordWithdrawal(payment: Payment, withdraw: PaymentDetails.Withdraw, settlesJournal: Boolean) { val txid = withdraw.txId val existing = (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1 ?.takeIf { it.txType == PaymentType.SENT } @@ -1048,7 +1052,7 @@ class SparkRepo @Inject constructor( val saved = activityRepo.get().upsertActivity(Activity.Onchain(activity)) .onFailure { Logger.warn("Failed to record Spark withdrawal '$txid'", it, context = TAG) } .isSuccess - if (saved && journal != null) { + if (saved && journal != null && settlesJournal) { // The tags picked on Confirm travel with the journal, so a recovered withdrawal keeps them too. if (journal.tags.isNotEmpty()) { activityRepo.get().addTagsToActivity(txid, journal.tags) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 65a44a57bd..94839ff7ab 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -546,6 +546,27 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull() as? SparkError.WithdrawalPending) } + @Test + fun `a payment event keeps the journal until spark lists the withdrawal`() = test { + val sut = journaledSpark() + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + + sparkEvents.emit(SdkEvent.PaymentSucceeded(contactWithdrawal())) + runCurrent() + + verify(activityRepo).upsertActivity(any()) + assertEquals( + SparkWithdrawalOutcome.Unknown, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A list that lags the event must not read the withdrawal as unsent", + ) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + sut.start(0).getOrThrow() + assertNull(cacheData.value.pendingSparkWithdrawal) + } + @Test fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { cacheData.update { From 55e49919ba29f64a79a0bda367f2f005893dd233 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:38:46 +0100 Subject: [PATCH 34/90] fix: drop a late spark settlement once its send sheet closed --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 23 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 2210c83550..fd33ffffab 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5390,6 +5390,8 @@ class AppViewModel @Inject constructor( ) { isSubmittingPaymentRequest = false uncertainOnchainPaymentRequestId = null + // A closed send never takes a late Spark settlement onto the next one. + uncertainSparkWithdrawal = null val interruptedRequest = synchronized(contactPaymentContextLock) { val request = activeContactPaymentContext?.incomingPaymentRequest if (request != null && !retryIncomingRequest) completePaymentRequestPresentation(request) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index c250171c79..125f1dafca 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12345,13 +12345,34 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertIs(effects.last(), "a withdrawal that never sent can be tried again") } + @Test + fun `a late spark settlement leaves a send sheet opened after its pending one closed`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + sut.hideSheet() + runCurrent() + sut.showSheet(Sheet.Send(SendRoute.Amount)) + val before = effects.size + + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + runCurrent() + + assertEquals(before, effects.size, "the settlement belongs to the closed pending screen") + } + private suspend fun TestScope.uncertainContactSparkSend( leg: ServiceRouteLeg, outcome: SparkWithdrawalOutcome, + whileOutcomeIsRead: suspend () -> Unit = {}, ): List { whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) - .thenReturn(outcome) + .doSuspendableAnswer { + whileOutcomeIsRead() + outcome + } whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())).doSuspendableAnswer { val onBeforeSend = it.getArgument Boolean>(3) onBeforeSend() From 31298c49bf1ac91b572b314630a3445a3ccf2c52 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:44:43 +0100 Subject: [PATCH 35/90] fix: register an uncertain spark send before reading its outcome --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 17 ++++++++++++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index fd33ffffab..01a42d328f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -565,6 +565,10 @@ class AppViewModel @Inject constructor( /** The address and amount of the uncertain Spark withdrawal to a contact a pending screen waits on. */ @Volatile private var uncertainSparkWithdrawal: Pair? = null + + /** The settlement that last closed [uncertainSparkWithdrawal]. */ + @Volatile + private var lastSparkWithdrawalSettlement: SparkWithdrawalSettlement? = null private var isPresentingPaymentRequest = false private val isPaymentRequestPollingStopped = MutableStateFlow(false) private var isPaymentRequestOverlayVisible = false @@ -1180,6 +1184,7 @@ class AppViewModel @Inject constructor( private fun handleSparkWithdrawalSettlement(settlement: SparkWithdrawalSettlement) { if (uncertainSparkWithdrawal != (settlement.address to settlement.amountSats)) return uncertainSparkWithdrawal = null + lastSparkWithdrawalSettlement = settlement if (_currentSheet.value !is Sheet.Send) return val txid = settlement.txid if (txid != null) { @@ -7034,9 +7039,20 @@ class AppViewModel @Inject constructor( allowanceAttemptId: String?, ) { incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } + // Registered before the outcome is read, so a journal that closes meanwhile still reaches this send. + val attempt = leg.endpoint.value to leg.deliveredSat + if (incomingPaymentRequest == null && earlierTxids != null) uncertainSparkWithdrawal = attempt val outcome = earlierTxids?.let { lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, it) } + if (incomingPaymentRequest == null && earlierTxids != null && uncertainSparkWithdrawal != attempt) { + Logger.info("Settled a Spark withdrawal while its outcome was read", context = TAG) + if (lastSparkWithdrawalSettlement?.txid == null) releasePrivatePaymentListIfNeeded(contactPaymentContext) + return + } + if (outcome == SparkWithdrawalOutcome.Unsent || outcome is SparkWithdrawalOutcome.Sent) { + uncertainSparkWithdrawal = null + } if (outcome is SparkWithdrawalOutcome.Sent && incomingPaymentRequest == null) { // Spark already lists it, so a contact payment without a request has no proof left to wait on. finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = outcome.txid) @@ -7046,7 +7062,6 @@ class AppViewModel @Inject constructor( if (outcome != null && outcome != SparkWithdrawalOutcome.Unsent) { Logger.warn("Left a Spark withdrawal with an uncertain send result to Spark", error, context = TAG) finishManualAllowancePayment(allowanceAttemptId, succeeded = null) - if (incomingPaymentRequest == null) uncertainSparkWithdrawal = leg.endpoint.value to leg.deliveredSat showUnresolvedOnchainSend(null, leg.deliveredSat, incomingPaymentRequest) return } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 125f1dafca..bf08069a76 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12362,6 +12362,22 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(before, effects.size, "the settlement belongs to the closed pending screen") } + @Test + fun `a journal that settles while the outcome is read still resolves the send`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) { + sut.showSheet(Sheet.Send(SendRoute.Confirm)) + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + // Reading the outcome suspends, so the settlement is handled before it returns. + yield() + } + + assertIs( + effects.last(), + "the screen must not stay pending after the journal closed", + ) + } + private suspend fun TestScope.uncertainContactSparkSend( leg: ServiceRouteLeg, outcome: SparkWithdrawalOutcome, From 2b34a6523b2838b46af81424b867e6c4bee54ab7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 21:38:50 +0100 Subject: [PATCH 36/90] fix: open success for a request's spark send spark already lists --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 +- .../viewmodels/AppViewModelSendFlowTest.kt | 64 +++++++++++++++++++ 2 files changed, 69 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 01a42d328f..af261b804c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7053,8 +7053,11 @@ class AppViewModel @Inject constructor( if (outcome == SparkWithdrawalOutcome.Unsent || outcome is SparkWithdrawalOutcome.Sent) { uncertainSparkWithdrawal = null } - if (outcome is SparkWithdrawalOutcome.Sent && incomingPaymentRequest == null) { - // Spark already lists it, so a contact payment without a request has no proof left to wait on. + if (outcome is SparkWithdrawalOutcome.Sent) { + // Spark already lists it, so the send succeeded: its proof's resolution may have gone by already. + incomingPaymentRequest?.let { request -> + viewModelScope.launch { paykitPaymentProofRepo.completeSparkOnchainPayment(request, outcome.txid) } + } finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = outcome.txid) onSendSuccess(sparkWithdrawalSent(outcome.txid, leg.deliveredSat)) return diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index bf08069a76..9764223197 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12447,6 +12447,70 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), any()) } + @Test + fun `a request's spark send that reconcile finds sent opens success`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val txid = "ab".repeat(32) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.consumeOnchainPaymentResolution(any())).then { call -> + onchainPaymentResolutions.update { it - call.getArgument(0) } + } + // Reconcile completes the proof and publishes its only resolution before the send is marked uncertain. + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).doSuspendableAnswer { + onchainPaymentResolutions.value = listOf( + PaykitOnchainPaymentProofResolution(testPublicKey, request.id, txid), + ) + yield() + false + } + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(3) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + pubkyPublicKey.value = testPublicKey + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + incomingPaymentRequestId = request.id, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + sut.showSheet(Sheet.Send(SendRoute.Confirm)) + + confirmCurrentPayment() + + assertEquals( + listOf(SendEffect.PaymentSuccess), + effects, + "Spark lists it, so the request never waits on Pending", + ) + } + @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 9ab62cf26798630e8559cddc827716405335351e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:09:36 +0100 Subject: [PATCH 37/90] fix: clear a spark withdrawal journal only while it is still open --- .../java/to/bitkit/repositories/SparkRepo.kt | 9 +++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 18 ++++++++++++++++++ 2 files changed, 25 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 46405c29d8..ee1bb4938e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -934,10 +934,15 @@ class SparkRepo @Inject constructor( // Spark may list a withdrawal it just sent only on a later sync, so an unlisted one stays open for a while. if (clock.now().epochSeconds < journal.startedAt + UNLISTED_WITHDRAWAL_GRACE.inWholeSeconds) return Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) - cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + clearJournal(journal) _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, null)) } + /** Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. */ + private suspend fun clearJournal(journal: PendingSparkWithdrawal) { + cacheStore.update { if (it.pendingSparkWithdrawal == journal) it.copy(pendingSparkWithdrawal = null) else it } + } + private suspend fun releaseFailedSends(payments: List) { // 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. @@ -1072,7 +1077,7 @@ class SparkRepo @Inject constructor( activityRepo.get().addTagsToActivity(txid, journal.tags) .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } } - cacheStore.update { it.copy(pendingSparkWithdrawal = null) } + clearJournal(journal) _withdrawalSettlements.emit( SparkWithdrawalSettlement( journal.address, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5a98d313ad..7c1b9b9dde 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -603,6 +603,24 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a stale settle never clears a newer withdrawal's journal`() = test { + val newer = PendingSparkWithdrawal("bcrt1qcontact", 30_000uL, "pubkycontact", startedAt = now.epochSeconds) + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + // Another settle closes the older journal and the newer withdrawal writes its own while this one saves. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + cacheData.update { it.copy(pendingSparkWithdrawal = newer) } + Result.success(Unit) + } + + journaledSpark() + + assertEquals(newer, cacheData.value.pendingSparkWithdrawal, "Losing the newer journal could pay it twice") + } + @Test fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { cacheData.update { From 3a77a655458389b82a1d96c3a164a0a371acbe78 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:23:59 +0100 Subject: [PATCH 38/90] chore: log private payment list publication --- .../main/java/to/bitkit/repositories/PrivatePaykitRepo.kt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index 451ec44ef4..d122f22463 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -1228,6 +1228,10 @@ class PrivatePaykitRepo @Inject constructor( if (!isCurrentPublication(generation, identity, requireImmediatePublication)) return@withLock if (lightningRefresh?.isStillCurrent?.invoke() == false) return@withLock if (publication.updates.isEmpty()) { + Logger.debug( + "Skipped private payment list publication during '$reason': no list changed", + context = TAG, + ) schedulePendingPrivateMessageDrainRetries(reason, links.linkRetryKeys, identity = identity) if (requireImmediatePublication) publication.firstError?.let { throw it } return@withLock @@ -1238,6 +1242,10 @@ class PrivatePaykitRepo @Inject constructor( clearUnlistedLinkedPeers = false, deferDuringPayment = publicationPriority == Priority.Background, ) + Logger.debug( + "Published private payment lists to '${publication.updates.size}' contacts during '$reason'", + context = TAG, + ) val deliveryError = applyPrivatePaymentListDeliveryReport(report, reason, publicationWindow) val firstError = publication.firstError ?: deliveryError val retryKeys = (links.linkRetryKeys + privatePaymentListDeliveryRetryKeys(report)).distinct() From e329c2528e31d6e6872cc78e0d84a175f3212355 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 03:08:31 +0100 Subject: [PATCH 39/90] fix: keep a dismissed payment request from popping up again A rejected or canceled request left the surfaced set as soon as it left pending, so the sheet opened again whenever a later SDK read listed it as proposed. Declined requests now stay marked while their history entry remains. --- .../repositories/PaykitPaymentRequestRepo.kt | 21 ++++++++++++++++++- .../PaykitPaymentRequestRepoTest.kt | 21 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt index 4e92b203ae..f698394451 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt @@ -338,6 +338,11 @@ class PaykitPaymentRequestRepo @Inject constructor( /** Maximum number of concurrent public capability lookups per discovery. */ private const val PAYMENT_REQUEST_DISCOVERY_CONCURRENCY = 8 + + private val DECLINED_STATES = setOf( + PaymentRequestLifecycleState.REJECTED, + PaymentRequestLifecycleState.CANCELED, + ) } private val operationMutex = Mutex() @@ -1801,6 +1806,7 @@ class PaykitPaymentRequestRepo @Inject constructor( listOf(updatedRequest) + requests.filterNot { it.id == current.id } } _pendingRequests.update { requests -> requests.filterNot { it.id == current.id } } + if (resultingState in DECLINED_STATES) markPresentedLocked(current.id) discardExpiredRequestsLocked() if (resultingState == PaymentRequestLifecycleState.ACCEPTED) { scheduleAcceptedResponse(current.counterparty) @@ -2028,8 +2034,21 @@ class PaykitPaymentRequestRepo @Inject constructor( .onFailure { Logger.warn("Failed to prune accepted Paykit payment requests", it, context = TAG) } } + private suspend fun markPresentedLocked(id: PaykitPaymentRequestId) { + if (id in presentedRequestIds) return + presentedRequestIds = presentedRequestIds + id + val identity = activeIdentity ?: return + runSuspendCatching { presentationStore.save(identity, presentedRequestIds) } + .onFailure { Logger.warn("Failed to persist surfaced Paykit payment requests", it, context = TAG) } + } + + // A request the user declined stays marked while the SDK still lists it, + // so it never pops up again if a later read reports it as proposed. private suspend fun prunePresentedRequestIds(requests: List) { - val requestIds = requests.mapTo(mutableSetOf()) { it.id } + val declinedIds = _paymentRequestHistory.value + .filter { it.direction == PaykitPaymentRequestDirection.Incoming && it.lifecycleState in DECLINED_STATES } + .map { it.id } + val requestIds = requests.mapTo(mutableSetOf()) { it.id } + declinedIds val prunedIds = presentedRequestIds.intersect(requestIds) if (prunedIds == presentedRequestIds) return presentedRequestIds = prunedIds diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt index 148d9dc9ae..8d09efbac8 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt @@ -2466,6 +2466,27 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { verifyBlocking(paykitSdkService) { processPendingPrivateMessages() } } + @Test + fun `dismissed request is not presented again when the sdk lists it as proposed again`() = test { + val record = paymentRequestRecord() + whenever(paykitSdkService.allPaymentRequests(anyOrNull())).thenReturn(listOf(record)) + whenever(paykitSdkService.rejectPaymentRequest(COUNTERPARTY, PAYMENT_REQUEST_ID)).thenReturn(record) + sut.refresh().getOrThrow() + val request = sut.pendingRequests.value.single() + assertTrue(sut.markPresented(request)) + + sut.dismiss(request).getOrThrow() + whenever(paykitSdkService.allPaymentRequests(anyOrNull())) + .thenReturn(listOf(paymentRequestRecord(state = PaymentRequestLifecycleState.REJECTED))) + sut.refresh().getOrThrow() + assertTrue(sut.pendingRequests.value.isEmpty()) + + whenever(paykitSdkService.allPaymentRequests(anyOrNull())).thenReturn(listOf(record)) + sut.refresh().getOrThrow() + assertEquals(request.id, sut.pendingRequests.value.single().id) + assertTrue(sut.automaticPendingRequests().isEmpty()) + } + @Test fun `surfaced request stays pending and is excluded from automatic presentation`() = test { whenever(paykitSdkService.allPaymentRequests(anyOrNull())).thenReturn(listOf(paymentRequestRecord())) From de768f876cb0131923d1ec970a45eb4c3477c213 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:22:46 +0100 Subject: [PATCH 40/90] fix: announce a spark withdrawal's settlement only when its journal closes A stale settle left the newer journal open but still emitted its settlement, which a retry to the same address and amount read as its own. --- .../java/to/bitkit/repositories/SparkRepo.kt | 36 ++++++++++++------- .../to/bitkit/repositories/SparkRepoTest.kt | 36 +++++++++++++++++++ 2 files changed, 59 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9832c22b75..8f0cb90422 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -966,13 +966,22 @@ class SparkRepo @Inject constructor( // Spark may list a withdrawal it just sent only on a later sync, so an unlisted one stays open for a while. if (clock.now().epochSeconds < journal.startedAt + UNLISTED_WITHDRAWAL_GRACE.inWholeSeconds) return Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) - clearJournal(journal) - _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, null)) + if (clearJournal(journal)) { + _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, null)) + } } - /** Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. */ - private suspend fun clearJournal(journal: PendingSparkWithdrawal) { - cacheStore.update { if (it.pendingSparkWithdrawal == journal) it.copy(pendingSparkWithdrawal = null) else it } + /** + * Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. Returns + * whether it cleared it: only then is the settlement this attempt's to announce. + */ + private suspend fun clearJournal(journal: PendingSparkWithdrawal): Boolean { + var cleared = false + cacheStore.update { + cleared = it.pendingSparkWithdrawal == journal + if (cleared) it.copy(pendingSparkWithdrawal = null) else it + } + return cleared } private suspend fun releaseFailedSends(payments: List) { @@ -1113,14 +1122,15 @@ class SparkRepo @Inject constructor( activityRepo.get().addTagsToActivity(txid, journal.tags) .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } } - clearJournal(journal) - _withdrawalSettlements.emit( - SparkWithdrawalSettlement( - journal.address, - journal.amountSats, - txid.takeIf { payment.status != PaymentStatus.FAILED }, - ), - ) + if (clearJournal(journal)) { + _withdrawalSettlements.emit( + SparkWithdrawalSettlement( + journal.address, + journal.amountSats, + txid.takeIf { payment.status != PaymentStatus.FAILED }, + ), + ) + } } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 033aae9e4a..bd6fe2807b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -637,6 +637,42 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(newer, cacheData.value.pendingSparkWithdrawal, "Losing the newer journal could pay it twice") } + @Test + fun `a stale settle never tells the newer withdrawal's send it ended`() = test { + // A retry to the same address and amount, so a settlement for the older one would read as the newer one's. + val newer = PendingSparkWithdrawal( + "bcrt1qcontact", + 20_000uL, + "pubkycontact", + earlierTxids = setOf("withdrawal"), + startedAt = now.epochSeconds, + ) + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + // Another settle closes the older journal and the newer withdrawal writes its own while this one saves. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + cacheData.update { it.copy(pendingSparkWithdrawal = newer) } + Result.success(Unit) + } + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + whenever(sparkService.isConnected).thenReturn(true) + val settlements = mutableListOf() + val sut = createSut() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + sut.withdrawalSettlements.collect { settlements += it } + } + + sut.start(0).getOrThrow() + + assertEquals(newer, cacheData.value.pendingSparkWithdrawal) + assertEquals(emptyList(), settlements, "The older txid would settle the newer send still in flight") + } + @Test fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { cacheData.update { From 7521d5ff8f2b8faf83c193b5da80b0d64626e031 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 17:25:44 +0100 Subject: [PATCH 41/90] fix: check the quote deadline right before a spark withdrawal sends --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 5 +- .../java/to/bitkit/repositories/SparkRepo.kt | 6 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 1 + .../to/bitkit/repositories/SparkRepoTest.kt | 23 ++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 60 ++++++++++++------- 5 files changed, 70 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index b85e46b901..0005509f06 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -15,6 +15,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton +import kotlin.time.Instant /** * Picks how to pay a Paykit contact through bitkit-core's Paykit router: directly from a balance the wallet holds, @@ -65,12 +66,13 @@ class PaykitRouteRepo @Inject constructor( /** * Runs a service leg the router picked to the [contact] and returns the txid that pays them; [onBeforeSend] runs - * once the leg is prepared, right before it sends. + * once the leg is prepared, right before it sends; past [paymentDeadlineAt] it sends nothing. */ suspend fun payServiceLeg( leg: ServiceRouteLeg, contact: String?, tags: List = emptyList(), + paymentDeadlineAt: Instant? = null, onBeforeSend: suspend () -> Boolean = { true }, ): Result = when (leg.service) { SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw( @@ -79,6 +81,7 @@ class PaykitRouteRepo @Inject constructor( contact = contact, maxDebitSats = leg.debitSat, tags = tags, + paymentDeadlineAt = paymentDeadlineAt, onBeforeSend = onBeforeSend, ) else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2168db4ed3..ed9954b0b0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -616,7 +616,8 @@ class SparkRepo @Inject constructor( /** * Withdraws exactly [amountSats] to a Paykit [contact]'s on-chain [address] at medium speed and returns the * withdrawal's txid. A journal entry written before the send lets the next start settle a withdrawal the app was - * killed during, from Spark's payment list, and refuses another withdrawal until then. + * killed during, from Spark's payment list, and refuses another withdrawal until then. Past [paymentDeadlineAt], + * it sends nothing. */ suspend fun withdraw( address: String, @@ -624,6 +625,7 @@ class SparkRepo @Inject constructor( contact: String?, maxDebitSats: ULong? = null, tags: List = emptyList(), + paymentDeadlineAt: Instant? = null, onBeforeSend: suspend () -> Boolean = { true }, ): Result = withContext(bgDispatcher) { @@ -640,6 +642,8 @@ class SparkRepo @Inject constructor( isWithdrawing = true val sent = try { if (!onBeforeSend()) throw PaymentAbortedBeforeSend() + // A quote can expire while the request and its allowance are checked, so it is checked last. + ensurePaymentDeadline(paymentDeadlineAt) val journal = PendingSparkWithdrawal( address, amountSats, diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 8d2486fcdc..51eee7b887 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6986,6 +6986,7 @@ class AppViewModel @Inject constructor( leg, contactPaymentContext?.publicKey, _sendUiState.value.selectedTags, + incomingPaymentRequest?.submissionDeadline(paykitPaymentTerms), ) { val earlier = lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value) startSparkOnchainProof( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index bff94e08c0..edeb05d219 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -99,7 +99,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 } @@ -869,6 +869,27 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a withdrawal whose deadline passes before it sends never leaves`() = test { + val sut = journaledSpark() + + val result = sut.withdraw( + "bcrt1qcontact", + 20_000uL, + null, + paymentDeadlineAt = now + 1.minutes, + onBeforeSend = { + // The quote's deadline passes while the allowance and the request are checked. + now += 2.minutes + true + }, + ) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + @Test fun `a withdrawal whose proof is starting reads as in flight before its journal is written`() = test { val sut = journaledSpark() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3f96ba8ee4..1ad476b3d2 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12080,7 +12080,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `spark route pays the contact while spending is the source`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any())) .thenReturn(Result.success("txid")) setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( @@ -12094,7 +12094,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()) } @Test @@ -12115,7 +12115,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull(), any(), any()) + verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull(), any(), anyOrNull(), any()) } @Test @@ -12236,9 +12236,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { fun `spark route pays an onchain request and completes its proof`() = test { val leg = sparkRouteLeg("bcrt1qroutedrequest") val txid = "ab".repeat(32) + val deadline = Instant.parse("2099-01-01T00:00:00Z") val request = paymentRequest().copy( amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + paymentDeadlineAt = deadline, ) val privateContext = privatePaymentContext(7uL) whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) @@ -12253,8 +12255,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) .thenReturn(Result.success(Unit)) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(3) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) if (onBeforeSend()) Result.success(txid) else Result.failure(AppError("refused")) } setActiveContactPaymentContext(testPublicKey, privateContext, request) @@ -12283,6 +12287,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) verify(paykitPaymentProofRepo).completeSparkOnchainPayment(request, txid) } + // Spark checks the request's deadline right before it sends. + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq(testPublicKey), any(), eq(deadline), any()) } @Test @@ -12309,8 +12315,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) .thenReturn(Result.success(Unit)) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(3) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) onBeforeSend() Result.failure(AppError("send outcome lost")) } @@ -12447,8 +12455,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whileOutcomeIsRead() outcome } - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(3) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) onBeforeSend() Result.failure(AppError("send outcome lost")) } @@ -12483,7 +12493,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 10_000u) whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) .thenReturn(Result.success(PaykitRoute.Service(leg))) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any())) .thenReturn(Result.success("txid")) setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( @@ -12502,7 +12512,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() verify(lightningRepo, never()).fetchLnurlInvoice(any(), any(), anyOrNull()) - verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()) } @Test @@ -12539,8 +12549,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { yield() false } - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(3) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) onBeforeSend() Result.failure(AppError("send outcome lost")) } @@ -12572,7 +12584,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `spark route saves the tags picked on confirmation`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), any())) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), anyOrNull(), any())) .thenReturn(Result.success("txid")) setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( @@ -12587,7 +12599,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmCurrentPayment() - verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), anyOrNull(), any()) } @Test @@ -12601,7 +12613,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) .thenReturn(Result.success(Unit)) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any())) .thenReturn(Result.failure(AppError("send failed"))) whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) setActiveContactPaymentContext(testPublicKey, privateContext, request) @@ -12746,7 +12758,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { fun `spending retried after a refused reroute and a switch back routes through spark again`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any())) .thenReturn(Result.success("txid")) whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) @@ -12782,7 +12794,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { "the quote recovered, so Spark carries it", ) confirmCurrentPayment() - verify(paykitRouteRepo).payServiceLeg(eq(leg), eq(testPublicKey), any(), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()) } @Test @@ -12825,8 +12837,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) .thenReturn(Result.failure(PaykitPaymentRequestError.RequestUnavailable)) whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(3) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) runSuspendCatching { onBeforeSend() }.map { "never" } } setActiveContactPaymentContext(testPublicKey, privateContext, request) @@ -12854,8 +12868,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) .thenReturn(SparkWithdrawalOutcome.Unknown) - whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), any())).doSuspendableAnswer { - val onBeforeSend = it.getArgument Boolean>(3) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) onBeforeSend() Result.failure(AppError("send outcome lost")) } From d15dc9f149e1c7c28a8ebd9eeaf462294607e67d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:28:05 +0100 Subject: [PATCH 42/90] fix: release a spark proof refused at its deadline at once --- .../repositories/PaykitPaymentProofRepo.kt | 38 ++++++++++++--- .../java/to/bitkit/viewmodels/AppViewModel.kt | 16 +++++++ .../PaykitPaymentProofRepoTest.kt | 17 +++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 48 +++++++++++++++++++ 4 files changed, 112 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index d00aafa653..069e89e012 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -438,6 +438,26 @@ class PaykitPaymentProofRepo @Inject constructor( }.getOrDefault(false) } + /** + * Releases the started Spark proof of [request] for a withdrawal Spark refused before its journal was written, so + * nothing left the wallet and no listing is needed; returns whether it did. + */ + suspend fun releaseRefusedSparkOnchainProof(request: PaykitPaymentRequest): Boolean = withContext(ioDispatcher) { + val identity = currentIdentity() ?: return@withContext false + runSuspendCatching { + operationMutex.withLock { + val proof = loadProofs().lastOrNull { + PubkyPublicKeyFormat.matches(it.identity, identity) && it.requestId == request.id && + it.sparkWithdrawal && it.paymentStarted && it.proofData == null + } ?: return@withLock false + releaseUnsentSparkOnchainProofLocked(proof) + true + } + }.onFailure { + Logger.warn("Failed to release a refused Spark withdrawal proof", it, context = TAG) + }.getOrDefault(false) + } + /** Settles a started Spark proof from Spark's list: completed by its own withdrawal, removed when it never sent. */ private suspend fun reconcileSparkOnchainProof(proof: PendingPaykitPaymentProof): Boolean { if (!proof.paymentStarted || proof.proofData != null) return false @@ -455,19 +475,23 @@ class PaykitPaymentProofRepo @Inject constructor( completeSparkOnchainProofLocked(proof, outcome.txid) } SparkWithdrawalOutcome.Unsent -> { - allowanceExecutor.get().onchainSendReleased(proof.identity, proof.requestId) - Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) - releaseDeniedPrivateConsumption(proof) - removeProofsLocked { it == proof } - // The pending screen of an uncertain Spark send waits on this to fail it. - val release = PaykitSparkWithdrawalRelease(proof.identity, proof.requestId) - _sparkWithdrawalReleases.update { if (release in it) it else it + release } + releaseUnsentSparkOnchainProofLocked(proof) false } SparkWithdrawalOutcome.Unknown -> false } } + private suspend fun releaseUnsentSparkOnchainProofLocked(proof: PendingPaykitPaymentProof) { + allowanceExecutor.get().onchainSendReleased(proof.identity, proof.requestId) + Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) + releaseDeniedPrivateConsumption(proof) + removeProofsLocked { it == proof } + // The pending screen of an uncertain Spark send waits on this to fail it. + val release = PaykitSparkWithdrawalRelease(proof.identity, proof.requestId) + _sparkWithdrawalReleases.update { if (release in it) it else it + release } + } + private suspend fun completeSparkOnchainProofLocked(proof: PendingPaykitPaymentProof, txid: String): Boolean { val proofs = loadProofs().toMutableList() val index = proofs.indexOf(proof) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 51eee7b887..5188735cfa 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -265,6 +265,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.Bip21Utils import to.bitkit.utils.Logger import to.bitkit.utils.NetworkValidationHelper +import to.bitkit.utils.ServiceError import to.bitkit.utils.jsonLogOf import to.bitkit.utils.timedsheets.TimedSheetManager import to.bitkit.utils.timedsheets.sheets.AppUpdateTimedSheet @@ -7040,6 +7041,12 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { + // Spark refuses a send past its deadline before writing its journal, so nothing left and no listing is needed. + if (error is ServiceError.PaymentDeadlineExpired) { + incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseRefusedSparkOnchainProof(it) } + failServiceLegBeforeSend(error, preparedPaymentProofRequest, contactPaymentContext, allowanceAttemptId) + return + } incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } // Registered before the outcome is read, so a journal that closes meanwhile still reaches this send. val attempt = leg.endpoint.value to leg.deliveredSat @@ -7070,6 +7077,15 @@ class AppViewModel @Inject constructor( showUnresolvedOnchainSend(null, leg.deliveredSat, incomingPaymentRequest) return } + failServiceLegBeforeSend(error, preparedPaymentProofRequest, contactPaymentContext, allowanceAttemptId) + } + + private suspend fun failServiceLegBeforeSend( + error: Throwable, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(preparedPaymentProofRequest) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 713593c3b2..ed4bbfaa09 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -930,6 +930,23 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() } + @Test + fun `a spark withdrawal refused before its journal releases its proof without reading spark`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + + assertTrue(repo.releaseRefusedSparkOnchainProof(request)) + + assertTrue(storedProofs.isEmpty()) + verify(lightningRepo, never()).sparkWithdrawalOutcome(any(), any(), any()) + verify(allowanceExecutor).onchainSendReleased(identity, request.id) + } + @Test fun `a spark withdrawal that never sent fails its allowance attempt on reconcile`() = test { val record = paymentRequestRecord() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 1ad476b3d2..fef40b6b8e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12602,6 +12602,54 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), anyOrNull(), any()) } + @Test + fun `a spark leg refused at its deadline releases the request proof without a spark sync`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + // Spark hasn't synced, so it can't yet say the withdrawal never sent. + whenever(lightningRepo.sparkWithdrawalOutcome(any(), any(), any())).thenReturn(SparkWithdrawalOutcome.Unknown) + whenever(paykitPaymentProofRepo.releaseRefusedSparkOnchainProof(request)).thenReturn(true) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + onBeforeSend() + Result.failure(ServiceError.PaymentDeadlineExpired()) + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(paykitPaymentProofRepo).releaseRefusedSparkOnchainProof(request) + verify(lightningRepo, never()).sparkWithdrawalOutcome(any(), any(), any()) + } + @Test fun `a failed spark leg releases a request proof spark never sent`() = test { val leg = sparkRouteLeg("bcrt1qroutedrequest") From 13d95cb4bfaee0d9ce24a4b0cb7daa642123fc97 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 20:19:10 +0100 Subject: [PATCH 43/90] fix: keep a spark withdrawal journal until a sync reaches spark --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 20 +++++++++++++++++++ 2 files changed, 24 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 10e1596e33..eb4af8734a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -203,11 +203,12 @@ class SparkRepo @Inject constructor( } val connected = sparkService.connect(walletIndex) importRestoredExitState(walletIndex) - // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. + // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. A + // sync that never reached Spark still returns, so only one that did may drop an unlisted withdrawal. val synced = runSuspendCatching { sparkService.syncWallet() } - .onSuccess { if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } } .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } - .isSuccess + .isSuccess && hasSyncedSince(null) + if (synced) _state.update { it.copy(hasSynced = true) } if (connected) _exitStateGeneration.update { it + 1 } refresh() // Only a full sync settles a pending withdrawal journal, so the sync runs until the journal clears. Only a diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 93ca56e010..0f4518cf20 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 java.math.BigInteger import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -783,6 +784,25 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `keeps a journaled withdrawal while the sync on start never reached spark`() = test { + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + whenever(sparkService.isConnected).thenReturn(true) + // The sync call returns, but Spark could not reach its operators, so its list may lack the withdrawal. + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncError = SyncError.Network("operators unreachable"))) + + createSut().start(0).getOrThrow() + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "A sync that never reached Spark can't show it never sent", + ) + } + @Test fun `keeps an unlisted withdrawal open until its grace period passes`() = test { val sut = journaledSpark() From 4369e44d331da0ddba8e312556a94625a3d97066 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 22:07:46 +0100 Subject: [PATCH 44/90] fix: price a spark-funded onchain request at its onchain rate --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 8 +++- .../viewmodels/AppViewModelSendFlowTest.kt | 47 +++++++++++++++++++ 2 files changed, 53 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 8d4a8615c6..8ffa7dd1f1 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5921,8 +5921,12 @@ class AppViewModel @Inject constructor( ): MethodId = when (source) { SendFundingSource.Usdt -> MethodId.UsdtArbitrum SendFundingSource.Spending -> routedPaykitRoute?.serviceLeg?.let { MethodId.fromRawValue(it.endpoint.methodId) } - ?: when (lnurl) { - is LnurlParams.LnurlPay -> MethodId.Lnurl + ?: when { + lnurl is LnurlParams.LnurlPay -> MethodId.Lnurl + // With no Lightning payment to make, Spending funds the Spark leg to the on-chain endpoint, so it takes + // that endpoint's price before the router picks the leg. + decodedInvoice == null && paykitRoute?.offersSparkLeg == true && address.isNotEmpty() -> + PublicPaykitRepo.onchainMethodId(address) else -> MethodId.Bolt11 } SendFundingSource.Savings, is SendFundingSource.Hardware -> PublicPaykitRepo.onchainMethodId(address) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 0799c51f34..918a1a9a9e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -18418,6 +18418,53 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `an onchain dollar request priced for onchain only goes to spark at its onchain rate`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_500uL, debitSat = 2_800uL) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.USD, 250u), + pricing = PaykitRequestPricing( + PaymentConversion.Fixed( + listOf(ConversionRate(MethodId.P2wpkh.rawValue.substringBeforeLast("-"), "0.00001")), + ), + ), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 0u, maxSendLightningSats = 50_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(privatePaykitRepo.beginPaymentRequest(request)).thenReturn( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))), + ) + + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.paykitRateUnavailable) + assertEquals(2_500uL, sut.sendUiState.value.amount) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertTrue(sut.sendUiState.value.isAmountInputValid) + verify(paykitRouteRepo).route( + eq(2_500uL), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + any(), + eq(0uL), + eq(true), + ) + } + @Test fun `fixed dollar request accepting USDT opens bitcoin confirmation while USDT is off`() = test { enablePaykitUi() From 33db490d72a0a41a8c11f20a18f440729248ac04 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 22:07:46 +0100 Subject: [PATCH 45/90] fix: keep a failed spark withdrawal open after a sync that never reached spark --- .../java/to/bitkit/repositories/SparkRepo.kt | 13 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 46 +++++++++++++++++++ 2 files changed, 56 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 eb4af8734a..031a867746 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -695,8 +695,11 @@ class SparkRepo @Inject constructor( isWithdrawing = false } val payment = sent.getOrElse { - // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. - runSuspendCatching { sparkService.syncWallet() }.onSuccess { syncActivities(settleJournal = true) } + // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. A + // sync that never reached Spark still returns, so only one done after the failure drops it. + val failedAt = clock.now().epochSeconds.toULong() + runSuspendCatching { sparkService.syncWallet() } + .onSuccess { syncActivities(settleJournal = hasSyncedSince(failedAt)) } throw it } Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) @@ -1136,7 +1139,11 @@ class SparkRepo @Inject constructor( _state.update { it.copy(hasSynced = true) } refresh() // A journal left open past its grace period would block every later withdrawal until a restart. - if (cacheStore.data.first().pendingSparkWithdrawal != null) syncActivities(settleJournal = true) + // Spark emits Synced after a sync that never reached it too, so only one since the journal + // drops it. + cacheStore.data.first().pendingSparkWithdrawal?.let { + syncActivities(settleJournal = hasSyncedSince(it.startedAt.toULong())) + } } is SdkEvent.PaymentSucceeded -> onPayment(event.payment) is SdkEvent.PaymentFailed -> onPayment(event.payment) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0f4518cf20..6f2c6e8a67 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 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock +import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -827,6 +828,29 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `keeps an aged failed withdrawal's journal while the sync after it never reached spark`() = test { + val sut = journaledSpark() + whenever(sparkService.send(any())).doSuspendableAnswer { + now += 11.minutes + throw SdkException.Generic("timeout") + } + // The sync call returns, but the SDK keeps the failed Spark sync in its info. + whenever { sparkService.getInfo() }.thenReturn( + info(50_000uL).copy( + lastSyncError = SyncError.Network("operators unreachable"), + lastSyncedAt = (now + 1.hours).epochSeconds.toULong(), + ) + ) + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "A sync that never reached Spark can't show the aged withdrawal was never sent", + ) + } + @Test fun `a journal that closes tells the pending send how its withdrawal ended`() = test { val settlements = mutableListOf() @@ -859,6 +883,7 @@ class SparkRepoTest : BaseUnitTest() { fun `a sync in a long foreground session closes an expired unlisted withdrawal`() = test { val sut = journaledSpark() cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL).copy(lastSyncedAt = now.epochSeconds.toULong())) sparkEvents.emit(SdkEvent.Synced) runCurrent() @@ -867,6 +892,27 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull() as? SparkError.WithdrawalPending) } + @Test + fun `a synced event after a sync that never reached spark keeps an expired unlisted withdrawal`() = test { + journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + // Spark emits Synced after a sync whose Spark leg failed too, and keeps that failure in its info. + whenever { sparkService.getInfo() }.thenReturn( + info(50_000uL).copy( + lastSyncError = SyncError.Network("operators unreachable"), + lastSyncedAt = now.epochSeconds.toULong(), + ) + ) + + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "A sync that never reached Spark can't show the withdrawal was never sent", + ) + } + @Test fun `a payment event keeps the journal until spark lists the withdrawal`() = test { val sut = journaledSpark() From 81fdf504f7e999532abc44f5eff7265152c7f788 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:13:23 +0100 Subject: [PATCH 46/90] fix: keep an accepted spark withdrawal sent after a restart --- .../main/java/to/bitkit/data/CacheStore.kt | 3 ++ .../java/to/bitkit/repositories/SparkRepo.kt | 36 +++++++++++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 33 +++++++++++++++++ 3 files changed, 62 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 33c0523bc5..78871e4f11 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -19,6 +19,7 @@ import to.bitkit.models.NewTransactionSheetDetails import to.bitkit.models.QuickPayLedger import to.bitkit.models.WalletScope import to.bitkit.repositories.PendingSparkWithdrawal +import to.bitkit.repositories.SentSparkWithdrawal import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton @@ -296,6 +297,8 @@ data class AppCacheData( val pendingLightningMessages: Map = mapOf(), /** A Spark withdrawal to a Paykit contact that started, kept until Spark's payment list settles it. */ val pendingSparkWithdrawal: PendingSparkWithdrawal? = null, + /** The latest Spark withdrawals to Paykit contacts that settled as sent, so a restart never reads one as unsent. */ + val sentSparkWithdrawals: List = listOf(), /** 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. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index a9d331b89f..0b991d84db 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -110,6 +110,9 @@ class SparkRepo @Inject constructor( /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes + /** How many sent contact withdrawals stay recorded for a request proof to complete from. */ + private const val MAX_SENT_WITHDRAWALS = 20 + private val SETTLE_RETRY_INTERVAL = 30.seconds /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ @@ -650,6 +653,10 @@ class SparkRepo @Inject constructor( amountSats: ULong, earlierTxids: Set, ): SparkWithdrawalOutcome = withContext(bgDispatcher) { + // A withdrawal recorded as sent stays sent, also once Spark's list lacks it after a restart. + cacheStore.data.first().sentSparkWithdrawals.firstOrNull { + it.address == address && it.amountSats == amountSats && it.txid !in earlierTxids + }?.let { return@withContext SparkWithdrawalOutcome.Sent(it.txid) } if (!_state.value.hasSynced || isWithdrawing) return@withContext SparkWithdrawalOutcome.Unknown val txid = sparkService.listPayments().firstNotNullOfOrNull { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@firstNotNullOfOrNull null @@ -1133,11 +1140,17 @@ class SparkRepo @Inject constructor( * Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. Returns * whether it cleared it: only then is the settlement this attempt's to announce. */ - private suspend fun clearJournal(journal: PendingSparkWithdrawal): Boolean { + private suspend fun clearJournal(journal: PendingSparkWithdrawal, sentTxid: String? = null): Boolean { var cleared = false cacheStore.update { cleared = it.pendingSparkWithdrawal == journal - if (cleared) it.copy(pendingSparkWithdrawal = null) else it + if (!cleared) return@update it + // The request's proof completes after the journal clears, so the sent withdrawal it records outlives it. + val sent = sentTxid?.let { txid -> SentSparkWithdrawal(journal.address, journal.amountSats, txid) } + it.copy( + pendingSparkWithdrawal = null, + sentSparkWithdrawals = (it.sentSparkWithdrawals + listOfNotNull(sent)).takeLast(MAX_SENT_WITHDRAWALS), + ) } return cleared } @@ -1335,14 +1348,9 @@ class SparkRepo @Inject constructor( activityRepo.get().addTagsToActivity(txid, journal.tags) .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } } - if (clearJournal(journal)) { - _withdrawalSettlements.emit( - SparkWithdrawalSettlement( - journal.address, - journal.amountSats, - txid.takeIf { payment.status != PaymentStatus.FAILED }, - ), - ) + val sentTxid = txid.takeIf { payment.status != PaymentStatus.FAILED } + if (clearJournal(journal, sentTxid)) { + _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, sentTxid)) } } return true @@ -1399,6 +1407,14 @@ data class PendingSparkWithdrawal( } } +/** A withdrawal to a Paykit contact that Spark sent as [txid]. */ +@Serializable +data class SentSparkWithdrawal( + val address: String, + val amountSats: ULong, + val txid: String, +) + /** A journaled withdrawal to [address] closed: sent as [txid], or never sent when [txid] is null. */ data class SparkWithdrawalSettlement( val address: String, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2e283fce3b..4aba8d897e 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 java.math.BigInteger import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -773,6 +774,38 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `an accepted withdrawal stays sent after a restart whose list lacks it`() = test { + journaledSpark().also { whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) } + .withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + assertNull(cacheData.value.pendingSparkWithdrawal) + // After a restart before the request's proof completed, Spark's list lacks the withdrawal. + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + val restarted = createSut() + + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncError = SyncError.Network("operators unreachable"))) + restarted.start(0).getOrThrow() + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A failed sync after the restart must not release a request Spark accepted", + ) + + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + restarted.start(0).getOrThrow() + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A list that lacks an accepted withdrawal is no proof it never sent", + ) + assertNotEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, setOf("withdrawal")), + "An earlier attempt's withdrawal never settles a new one", + ) + } + @Test fun `refuses a withdrawal while an earlier one is unsettled`() = test { val sut = journaledSpark() From 0f5d7e531af0b17d92e3df6cca6a5ea546673c3c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:27:58 +0100 Subject: [PATCH 47/90] fix: drop a paykit route quote once its amount or source changed --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 ++++ .../viewmodels/AppViewModelSendFlowTest.kt | 32 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 8ffa7dd1f1..4a35da016d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4776,6 +4776,13 @@ class AppViewModel @Inject constructor( ) { return PaykitRouteOutcome.Stale } + // An amount a rate refresh wrote, or a source picked, while the router answered needs a new route. + val current = _sendUiState.value + if (current.amount != state.amount || current.payMethod != state.payMethod) { + paykitRouteDecided = false + _sendUiState.update { it.copy(isLoading = false) } + return PaykitRouteOutcome.Stale + } _sendUiState.update { it.copy(isLoading = false) } val picked = result.getOrElse { Logger.error("Failed to route Paykit payment", it, context = TAG) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 918a1a9a9e..fe0552d5db 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12413,6 +12413,38 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(endpointB.value, sut.sendUiState.value.address) } + @Test + fun `a route quoted for an amount that changed meanwhile never lands`() = test { + val leg = sparkRouteLeg("bcrt1qcontact") + val quote = CompletableDeferred>() + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quote.await() } + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + val route = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = route, + ), + ) + sut.showSheet(Sheet.Send(SendRoute.Amount)) + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + + // A request's rate refresh writes a new amount while Spark quotes the old one. + setSendState(sut.sendUiState.value.copy(amount = 2_000uL)) + quote.complete(Result.success(PaykitRoute.Service(leg))) + advanceUntilIdle() + + assertNull( + sut.sendUiState.value.paykitRoute?.serviceLeg, + "a leg quoted for the old amount must not pay the new one", + ) + assertEquals(2_000uL, sut.sendUiState.value.amount) + } + @Test fun `an uncertain spark send to a contact that spark already lists opens success`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 5bac80a3073b46fbca2cea3dfde5d6563d5bee7d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:43:38 +0100 Subject: [PATCH 48/90] fix: restore the endpoint a paykit reroute picks --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 9 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 68 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 4a35da016d..baf4385ee9 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4124,6 +4124,8 @@ class AppViewModel @Inject constructor( endpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } .map { PaykitEndpoint(methodId = it.methodId.rawValue, value = it.value) }, offersSparkLeg = offersSparkLeg, + invoice = invoice, + lnurl = lnurl, ).takeIf { it.endpoints.isNotEmpty() } val payMethod = if (offersSparkLeg && !canUseOnchain) { SendMethod.LIGHTNING @@ -4842,13 +4844,16 @@ class AppViewModel @Inject constructor( address = endpoint.value, paykitRoute = route.copy(serviceLeg = null), ) + // An earlier pick cleared the other Lightning endpoint, so the picked one comes back from the route. endpoint.methodId == MethodId.Lnurl.rawValue -> it.copy( payMethod = SendMethod.LIGHTNING, decodedInvoice = null, + lnurl = route.lnurl ?: it.lnurl, paykitRoute = route.copy(serviceLeg = null), ) else -> it.copy( payMethod = SendMethod.LIGHTNING, + decodedInvoice = route.invoice ?: it.decodedInvoice, lnurl = null, paykitRoute = route.copy(serviceLeg = null), ) @@ -9585,13 +9590,15 @@ data class SendUiState( /** * A contact payment bitkit-core's router picks the way for: the contact's bitcoin endpoints, whether a Spark leg may - * reach its on-chain ones, and the leg once the router picked one. + * reach its on-chain ones, the leg once the router picked one, and the decoded invoice and LNURL a Direct pick pays. */ @Stable data class PaykitRouteUi( val endpoints: List, val offersSparkLeg: Boolean = false, val serviceLeg: ServiceRouteLeg? = null, + val invoice: LightningInvoice? = null, + val lnurl: LnurlParams.LnurlPay? = null, ) private enum class PaykitRouteOutcome { Direct, Leg, Refused, Stale } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index fe0552d5db..865bfbd31c 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12167,6 +12167,38 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) } + @Test + fun `a reroute from lnurl back to bolt11 pays the contact's invoice`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.decodedInvoice) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(3_000u) + + assertEquals(bolt11.value, sut.sendUiState.value.decodedInvoice?.bolt11) + assertNull(sut.sendUiState.value.lnurl) + } + + @Test + fun `a reroute from bolt11 back to lnurl pays the contact's lnurl`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.lnurl) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + continueWithAmount(3_000u) + + assertEquals(lnurl.value, (sut.sendUiState.value.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + assertNull(sut.sendUiState.value.decodedInvoice) + } + @Test fun `router direct pays the onchain endpoint it picks from savings`() = test { val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") @@ -13001,6 +13033,42 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } + private suspend fun TestScope.openLightningContact(): Pair { + val bolt11 = "lnbcrt1contactreroute" + val lnurl = LnurlPayData( + uri = "lnurl1contactreroute", + callback = "https://example.com/pay", + minSendable = 1_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + stubLightningScan(bolt11, amountSats = 0u) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(lightningRepo.canSend(any())).thenReturn(true) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + sut.openContactPayment( + paymentRequest = bolt11, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Bolt11, bolt11, rawPayload = ""), + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + // A USDT endpoint has the router pick the contact's bitcoin endpoint. + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ), + ) + advanceUntilIdle() + return PaykitEndpoint(MethodId.Bolt11.rawValue, bolt11) to PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri) + } + + private fun TestScope.continueWithAmount(amount: ULong) { + sut.setSendEvent(SendEvent.AmountChange(amount)) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + } + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( service = "spark", endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), From 2674c84ef2bd1f10c10ac9af9c6f621d4b8c06ac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:46:20 +0100 Subject: [PATCH 49/90] fix: weigh a spark withdrawal leg against the whole balance --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 7 +++++-- app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt | 7 +++++++ 2 files changed, 12 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 4fc2bcc498..7324204698 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -255,6 +255,9 @@ class SparkRepo @Inject constructor( fun canSend(amountSats: ULong): Boolean = _state.value.isReady && _state.value.sendableSats >= amountSats + /** A withdrawal's debit already holds its fees, so it is weighed against the whole balance. */ + private fun canWithdraw(debitSats: ULong): Boolean = _state.value.isReady && _state.value.balanceSats >= debitSats + suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { runSuspendCatching { sparkService.receiveBolt11(amountSats, description, expirySecs) } @@ -638,13 +641,13 @@ class SparkRepo @Inject constructor( suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result = withContext(bgDispatcher) { runSuspendCatching { - if (!canSend(amountSats)) return@runSuspendCatching null + if (!canWithdraw(amountSats)) return@runSuspendCatching null val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote // Spark charges its fee and the L1 broadcast fee on top of what reaches the contact. val speed = quote.speedMedium val debitSats = amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() - if (quote.isEstimate || !canSend(debitSats)) return@runSuspendCatching null + if (quote.isEstimate || !canWithdraw(debitSats)) return@runSuspendCatching null ServiceRouteLeg( service = ROUTE_SERVICE, endpoint = endpoint, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index eb6cdbccbd..5e63ddb539 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -758,6 +758,13 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(null, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()) } + @Test + fun `quotes a route leg whose debit takes the whole balance`() = test { + val sut = readySpark(balanceSats = 20_500uL) + + assertEquals(20_500uL, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()?.debitSat) + } + @Test fun `records a withdrawal to a contact with its contact and fee`() = test { val sut = journaledSpark() From 352a1296570e6e9ad8731b8051874c168c6761ed Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:46:26 +0100 Subject: [PATCH 50/90] fix: keep a cached spark withdrawal from settling a retry --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 11 ++++++++--- .../java/to/bitkit/repositories/SparkRepoTest.kt | 15 +++++++++++++++ 2 files changed, 23 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 7324204698..551dbb356b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -659,11 +659,16 @@ class SparkRepo @Inject constructor( } } - /** Txids of the withdrawals Spark lists to [address], so a new attempt to it can tell its own withdrawal apart. */ + /** + * Txids of the withdrawals Spark lists or the app recorded as sent to [address], so a new attempt to it can tell + * its own withdrawal apart, also while Spark's list lacks one after a restart. + */ suspend fun withdrawalTxidsTo(address: String): Set = withContext(bgDispatcher) { - sparkService.listPayments().mapNotNull { payment -> + val listed = sparkService.listPayments().mapNotNull { payment -> (payment.details as? PaymentDetails.Withdraw)?.takeIf { it.destinationAddress == address }?.txId - }.toSet() + } + val recorded = cacheStore.data.first().sentSparkWithdrawals.filter { it.address == address }.map { it.txid } + (listed + recorded).toSet() } /** diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5e63ddb539..11b6fa8afe 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -814,6 +814,21 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `a cached withdrawal never settles a retry after a restart whose list lacks it`() = test { + journaledSpark().also { whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) } + .withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + val restarted = createSut().also { it.start(0).getOrThrow() } + + val earlierTxids = restarted.withdrawalTxidsTo("bcrt1qcontact") + + assertNotEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, earlierTxids), + ) + } + @Test fun `refuses a withdrawal while an earlier one is unsettled`() = test { val sut = journaledSpark() From 47296c6d64f81ea67a68b1fa2fbde0e6abff95d3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:46:33 +0100 Subject: [PATCH 51/90] fix: check a spark withdrawal's deadline after its journal --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 +- .../java/to/bitkit/repositories/SparkRepoTest.kt | 16 ++++++++++++++++ 3 files changed, 23 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 551dbb356b..c44ce19fda 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -729,7 +729,7 @@ class SparkRepo @Inject constructor( isWithdrawing = true val sent = try { if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - // A quote can expire while the request and its allowance are checked, so it is checked last. + // A quote can expire while the request and its allowance are checked. ensurePaymentDeadline(paymentDeadlineAt) val journal = PendingSparkWithdrawal( address, @@ -740,6 +740,11 @@ class SparkRepo @Inject constructor( startedAt = clock.now().epochSeconds, ) cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } + // Saving the journal suspends, so the deadline is checked last, before the send. + runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { + clearJournal(journal) + throw it + } runSuspendCatching { sparkService.send(prepared) } } finally { isWithdrawing = false diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index baf4385ee9..5193af6467 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7057,7 +7057,7 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { - // Spark refuses a send past its deadline before writing its journal, so nothing left and no listing is needed. + // Spark refuses a send past its deadline before it sends and clears its journal, so no listing is needed. if (error is ServiceError.PaymentDeadlineExpired) { incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseRefusedSparkOnchainProof(it) } failServiceLegBeforeSend(error, preparedPaymentProofRequest, contactPaymentContext, allowanceAttemptId) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 11b6fa8afe..9d5f68f280 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1143,6 +1143,22 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a withdrawal whose deadline passes while its journal is written never leaves`() = test { + val sut = journaledSpark() + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + if (cacheData.value.pendingSparkWithdrawal != null) now += 2.minutes + } + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, paymentDeadlineAt = now + 1.minutes) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + @Test fun `a withdrawal whose proof is starting reads as in flight before its journal is written`() = test { val sut = journaledSpark() From 62c64240a6104617aa53ad7517977d080ba1d1a1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:46:33 +0100 Subject: [PATCH 52/90] fix: keep a spark withdrawal's journal until its tags save --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 8 ++++++-- .../java/to/bitkit/repositories/SparkRepoTest.kt | 12 ++++++++++++ 2 files changed, 18 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 c44ce19fda..e9b319312a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1398,9 +1398,13 @@ class SparkRepo @Inject constructor( unsavedPayments.remove(payment.id) if (journal != null && settlesJournal) { // The tags picked on Confirm travel with the journal, so a recovered withdrawal keeps them too. + // A failed tag write keeps the journal, so the next refresh tags it again. if (journal.tags.isNotEmpty()) { - activityRepo.get().addTagsToActivity(txid, journal.tags) - .onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) } + activityRepo.get().addTagsToActivity(txid, journal.tags).onFailure { + Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) + unsavedPayments.add(payment.id) + return false + } } val sentTxid = txid.takeIf { payment.status != PaymentStatus.FAILED } if (clearJournal(journal, sentTxid)) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 9d5f68f280..28ac298b74 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1253,6 +1253,18 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) } + @Test + fun `keeps the journal when the withdrawal's tags fail to save`() = test { + val sut = journaledSpark() + whenever { activityRepo.addTagsToActivity(any(), any(), any()) } + .thenReturn(Result.failure(AppError("disk full"))) + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact", tags = listOf("rent")).getOrThrow() + + assertEquals(listOf("rent"), cacheData.value.pendingSparkWithdrawal?.tags) + } + @Test fun `an earlier withdrawal to the same address never settles a new attempt`() = test { whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) From eee7d239fcd661b817f4b64a58502f21d0223d46 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:46:56 +0100 Subject: [PATCH 53/90] refactor: drop a private list release that never runs --- app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 6 ------ 1 file changed, 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 5193af6467..00c08dbe33 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -566,10 +566,6 @@ class AppViewModel @Inject constructor( /** The address and amount of the uncertain Spark withdrawal to a contact a pending screen waits on. */ @Volatile private var uncertainSparkWithdrawal: Pair? = null - - /** The settlement that last closed [uncertainSparkWithdrawal]. */ - @Volatile - private var lastSparkWithdrawalSettlement: SparkWithdrawalSettlement? = null private var isPresentingPaymentRequest = false private val isPaymentRequestPollingStopped = MutableStateFlow(false) private var isPaymentRequestOverlayVisible = false @@ -1185,7 +1181,6 @@ class AppViewModel @Inject constructor( private fun handleSparkWithdrawalSettlement(settlement: SparkWithdrawalSettlement) { if (uncertainSparkWithdrawal != (settlement.address to settlement.amountSats)) return uncertainSparkWithdrawal = null - lastSparkWithdrawalSettlement = settlement if (_currentSheet.value !is Sheet.Send) return val txid = settlement.txid if (txid != null) { @@ -7072,7 +7067,6 @@ class AppViewModel @Inject constructor( } if (incomingPaymentRequest == null && earlierTxids != null && uncertainSparkWithdrawal != attempt) { Logger.info("Settled a Spark withdrawal while its outcome was read", context = TAG) - if (lastSparkWithdrawalSettlement?.txid == null) releasePrivatePaymentListIfNeeded(contactPaymentContext) return } if (outcome == SparkWithdrawalOutcome.Unsent || outcome is SparkWithdrawalOutcome.Sent) { From 6056afe53113f340abe1f69a79298d3a8b4f9035 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:47:15 +0100 Subject: [PATCH 54/90] refactor: hold paykit route endpoints in an immutable list --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 +- .../viewmodels/AppViewModelSendFlowTest.kt | 48 +++++++++---------- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 00c08dbe33..e5bddfa1d8 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4117,7 +4117,8 @@ class AppViewModel @Inject constructor( paykitRouteDecided = false val route = PaykitRouteUi( endpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } - .map { PaykitEndpoint(methodId = it.methodId.rawValue, value = it.value) }, + .map { PaykitEndpoint(methodId = it.methodId.rawValue, value = it.value) } + .toImmutableList(), offersSparkLeg = offersSparkLeg, invoice = invoice, lnurl = lnurl, @@ -9588,7 +9589,7 @@ data class SendUiState( */ @Stable data class PaykitRouteUi( - val endpoints: List, + val endpoints: ImmutableList, val offersSparkLeg: Boolean = false, val serviceLeg: ServiceRouteLeg? = null, val invoice: LightningInvoice? = null, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 865bfbd31c..6af6da4a6a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12115,7 +12115,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { address = leg.endpoint.value, amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12136,7 +12136,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12155,7 +12155,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { SendUiState( amount = 1_000u, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(bolt11, onchain)), + paykitRoute = PaykitRouteUi(persistentListOf(bolt11, onchain)), ), ) @@ -12210,7 +12210,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { SendUiState( amount = 1_000u, payMethod = SendMethod.ONCHAIN, - paykitRoute = PaykitRouteUi(listOf(bolt11, onchain)), + paykitRoute = PaykitRouteUi(persistentListOf(bolt11, onchain)), ), ) @@ -12231,7 +12231,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { SendUiState( amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), ), ) @@ -12278,7 +12278,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { SendUiState( amount = 1_000u, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(onchain), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(onchain), offersSparkLeg = true), ), ) @@ -12327,7 +12327,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12388,7 +12388,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) val effects = mutableListOf() @@ -12418,7 +12418,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { address = legA.endpoint.value, amount = legA.deliveredSat, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(legA.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(legA.endpoint), offersSparkLeg = true), ), ) sut.showSheet(Sheet.Send(SendRoute.Amount)) @@ -12431,7 +12431,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { address = endpointB.value, amount = 2_000uL, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(endpointB), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(endpointB), offersSparkLeg = true), ) setSendState(stateB) quote.complete(Result.success(PaykitRoute.Service(legA))) @@ -12452,7 +12452,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 10_000u) whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quote.await() } setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) - val route = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true) + val route = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true) setSendState( SendUiState( address = leg.endpoint.value, @@ -12559,7 +12559,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { address = leg.endpoint.value, amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) val effects = mutableListOf() @@ -12593,7 +12593,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, lnurl = LnurlParams.LnurlPay(lnurl), - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), ), ) @@ -12656,7 +12656,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, incomingPaymentRequestId = request.id, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) val effects = mutableListOf() @@ -12684,7 +12684,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, selectedTags = persistentListOf("rent"), - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12730,7 +12730,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12762,7 +12762,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12784,7 +12784,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), ), ) sut.setSendEvent(SendEvent.AmountContinue) @@ -12815,7 +12815,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), ), ) sut.setSendEvent(SendEvent.AmountContinue) @@ -12853,7 +12853,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), ), ) sut.setSendEvent(SendEvent.AmountContinue) @@ -12908,7 +12908,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), ), ) sut.setSendEvent(SendEvent.AmountContinue) @@ -12946,7 +12946,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, isAmountInputValid = true, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -12989,7 +12989,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, isPaymentRequest = true, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) @@ -13023,7 +13023,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { address = leg.endpoint.value, amount = leg.deliveredSat, payMethod = SendMethod.LIGHTNING, - paykitRoute = PaykitRouteUi(listOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) From 82c446d89fff0ef7dbae82a762ff93cbe2fff6a7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:52:41 +0100 Subject: [PATCH 55/90] fix: hide boost on a pending spark withdrawal --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 9 +++++++++ .../ui/screens/wallets/activity/ActivityDetailScreen.kt | 8 +++++++- .../java/to/bitkit/viewmodels/ActivityDetailViewModel.kt | 4 ++++ .../bitkit/repositories/ActivityDetailViewModelTest.kt | 1 + .../test/java/to/bitkit/repositories/SparkRepoTest.kt | 9 +++++++++ 5 files changed, 30 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 e9b319312a..eb970891bb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -671,6 +671,15 @@ class SparkRepo @Inject constructor( (listed + recorded).toSet() } + /** Whether [txid] is a Spark withdrawal, which LDK never held and so cannot boost. */ + suspend fun isWithdrawal(txid: String): Boolean = withContext(bgDispatcher) { + if (cacheStore.data.first().sentSparkWithdrawals.any { it.txid == txid }) return@withContext true + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments for '$txid'", it, context = TAG) } + .getOrDefault(emptyList()) + .any { (it.details as? PaymentDetails.Withdraw)?.txId == txid } + } + /** * What became of an attempt to withdraw exactly [amountSats] to [address]: sent once Spark's synced list holds a * withdrawal to it that is not one of [earlierTxids], unsent once Spark synced and no journaled withdrawal to diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt index e1f923fbb6..be9ba8b3dc 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt @@ -188,11 +188,13 @@ fun ActivityDetailScreen( val boostSheetVisible by detailViewModel.boostSheetVisible.collectAsStateWithLifecycle() var showAddTagSheet by remember { mutableStateOf(false) } var isCpfpChild by remember { mutableStateOf(false) } + var isSparkWithdrawal by remember { mutableStateOf(false) } var boostTxDoesExist by remember { mutableStateOf>(persistentMapOf()) } LaunchedEffect(item) { if (item is Activity.Onchain) { isCpfpChild = detailViewModel.isCpfpChildTransaction(item.v1.txId) + isSparkWithdrawal = detailViewModel.isSparkWithdrawal(item.v1.txId) boostTxDoesExist = if (item.v1.boostTxIds.isNotEmpty()) { detailViewModel.getBoostTxDoesExist(item.v1.boostTxIds) } else { @@ -200,6 +202,7 @@ fun ActivityDetailScreen( } } else { isCpfpChild = false + isSparkWithdrawal = false boostTxDoesExist = persistentMapOf() } } @@ -246,6 +249,7 @@ fun ActivityDetailScreen( detailViewModel = detailViewModel, isCpfpChild = isCpfpChild, isHardware = uiState.isHardwareActivity, + isSparkWithdrawal = isSparkWithdrawal, showContactActions = isPaykitEnabled && (!uiState.isHardwareActivity || assignedContact != null), boostTxDoesExist = boostTxDoesExist, @@ -339,6 +343,7 @@ private fun ActivityDetailContent( detailViewModel: ActivityDetailViewModel? = null, isCpfpChild: Boolean = false, isHardware: Boolean = false, + isSparkWithdrawal: Boolean = false, showContactActions: Boolean = true, boostTxDoesExist: ImmutableMap = persistentMapOf(), onCopy: (String) -> Unit, @@ -676,7 +681,8 @@ private fun ActivityDetailContent( } } } - val shouldEnable = shouldEnableBoostButton(item, isCpfpChild, isHardware, boostTxDoesExist) + val shouldEnable = !isSparkWithdrawal && + shouldEnableBoostButton(item, isCpfpChild, isHardware, boostTxDoesExist) PrimaryButton( text = stringResource( if (hasCompletedBoost) { diff --git a/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt index 737ecec921..b71432a92a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt @@ -33,6 +33,7 @@ import to.bitkit.models.WalletScope import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.utils.Logger import javax.inject.Inject @@ -46,6 +47,7 @@ class ActivityDetailViewModel @Inject constructor( private val blocktankRepo: BlocktankRepo, private val hwWalletRepo: HwWalletRepo, private val transferRepo: TransferRepo, + private val sparkRepo: SparkRepo, ) : ViewModel() { private val _txDetails = MutableStateFlow(null) val txDetails = _txDetails.asStateFlow() @@ -270,6 +272,8 @@ class ActivityDetailViewModel @Inject constructor( suspend fun getBoostTxDoesExist(boostTxIds: List): ImmutableMap = activityRepo.getBoostTxDoesExist(boostTxIds, currentWalletId).toImmutableMap() + suspend fun isSparkWithdrawal(txId: String): Boolean = sparkRepo.isWithdrawal(txId) + suspend fun isCpfpChildTransaction(txId: String): Boolean { return activityRepo.isCpfpChildTransaction(txId, currentWalletId) } diff --git a/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt b/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt index 7af4df3e8d..5b933f2e12 100644 --- a/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt @@ -65,6 +65,7 @@ class ActivityDetailViewModelTest : BaseUnitTest() { settingsStore = settingsStore, hwWalletRepo = hwWalletRepo, transferRepo = transferRepo, + sparkRepo = mock(), ) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 28ac298b74..c6e576d627 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -765,6 +765,15 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(20_500uL, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()?.debitSat) } + @Test + fun `tells a spark withdrawal from a transaction ldk holds`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = readySpark(balanceSats = 50_000uL) + + assertTrue(sut.isWithdrawal("withdrawal")) + assertFalse(sut.isWithdrawal("ldk-send")) + } + @Test fun `records a withdrawal to a contact with its contact and fee`() = test { val sut = journaledSpark() From cf8840ea4bd738bf49303c1907ecc56b47d53ce3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 10:59:14 +0100 Subject: [PATCH 56/90] fix: settle a deleted spark withdrawal it cannot tag --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 10 ++++++---- .../java/to/bitkit/repositories/SparkRepoTest.kt | 13 +++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index eb970891bb..bf02d8636e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -674,6 +674,7 @@ class SparkRepo @Inject constructor( /** Whether [txid] is a Spark withdrawal, which LDK never held and so cannot boost. */ suspend fun isWithdrawal(txid: String): Boolean = withContext(bgDispatcher) { if (cacheStore.data.first().sentSparkWithdrawals.any { it.txid == txid }) return@withContext true + if (!_state.value.isReady) return@withContext false runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments for '$txid'", it, context = TAG) } .getOrDefault(emptyList()) @@ -1397,9 +1398,10 @@ class SparkRepo @Inject constructor( seenAt = existing?.seenAt, ) // The journal stays until the activity is saved, so a failed save is retried from Spark's list and on refresh. - val saved = activityRepo.get().upsertActivity(Activity.Onchain(activity)) + val upserted = activityRepo.get().upsertActivity(Activity.Onchain(activity)) .onFailure { Logger.warn("Failed to record Spark withdrawal '$txid'", it, context = TAG) } - .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + val isDeleted = upserted.exceptionOrNull() is ActivityDeletedError + val saved = upserted.isSuccess || isDeleted if (!saved) { unsavedPayments.add(payment.id) return false @@ -1407,8 +1409,8 @@ class SparkRepo @Inject constructor( unsavedPayments.remove(payment.id) if (journal != null && settlesJournal) { // The tags picked on Confirm travel with the journal, so a recovered withdrawal keeps them too. - // A failed tag write keeps the journal, so the next refresh tags it again. - if (journal.tags.isNotEmpty()) { + // A failed tag write keeps the journal, so the next refresh tags it again; a deleted activity takes none. + if (journal.tags.isNotEmpty() && !isDeleted) { activityRepo.get().addTagsToActivity(txid, journal.tags).onFailure { Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) unsavedPayments.add(payment.id) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c6e576d627..60ae38b129 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1274,6 +1274,19 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf("rent"), cacheData.value.pendingSparkWithdrawal?.tags) } + @Test + fun `settles the journal of a deleted withdrawal it cannot tag`() = test { + val sut = journaledSpark() + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(ActivityDeletedError("withdrawal"))) + whenever { activityRepo.addTagsToActivity(any(), any(), any()) } + .thenReturn(Result.failure(AppError("not found"))) + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact", tags = listOf("rent")).getOrThrow() + + assertNull(cacheData.value.pendingSparkWithdrawal) + } + @Test fun `an earlier withdrawal to the same address never settles a new attempt`() = test { whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) From 801b660901863bda67eb5a61f341f987ea2ad4f6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:13:19 +0100 Subject: [PATCH 57/90] fix: keep a spark send pending when its outcome read fails --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../bitkit/viewmodels/AppViewModelSendFlowTest.kt | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index e5bddfa1d8..220ff3369a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7064,7 +7064,9 @@ class AppViewModel @Inject constructor( val attempt = leg.endpoint.value to leg.deliveredSat if (incomingPaymentRequest == null && earlierTxids != null) uncertainSparkWithdrawal = attempt val outcome = earlierTxids?.let { - lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, it) + runSuspendCatching { lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, it) } + .onFailure { Logger.warn("Failed to read a Spark withdrawal outcome", it, context = TAG) } + .getOrDefault(SparkWithdrawalOutcome.Unknown) } if (incomingPaymentRequest == null && earlierTxids != null && uncertainSparkWithdrawal != attempt) { Logger.info("Settled a Spark withdrawal while its outcome was read", context = TAG) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6af6da4a6a..a5c32e5438 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12535,6 +12535,21 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `a failed spark outcome read leaves the send pending until its journal settles`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) { + throw AppError("payment list read failed") + } + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + runCurrent() + + assertIs(effects.last(), "a withdrawal that never sent can be tried again") + } + private suspend fun TestScope.uncertainContactSparkSend( leg: ServiceRouteLeg, outcome: SparkWithdrawalOutcome, From ed3bffc4795f9a1d052d80ee3a687be36809b774 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:18:19 +0100 Subject: [PATCH 58/90] fix: validate a spark withdrawal against its debit and spark's balance --- .../to/bitkit/repositories/LightningRepo.kt | 3 ++ .../java/to/bitkit/repositories/SparkRepo.kt | 2 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 15 ++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 34 +++++++++++++++++++ 4 files changed, 53 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 5b5d2bc31a..562dc74918 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2579,6 +2579,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) + /** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */ + fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats) + fun canSend(amountSats: ULong): Boolean { val state = _lightningState.value if (sparkRepo.canSend(amountSats)) return true diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index bf02d8636e..f2d9dda1e5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -256,7 +256,7 @@ class SparkRepo @Inject constructor( fun canSend(amountSats: ULong): Boolean = _state.value.isReady && _state.value.sendableSats >= amountSats /** A withdrawal's debit already holds its fees, so it is weighed against the whole balance. */ - private fun canWithdraw(debitSats: ULong): Boolean = _state.value.isReady && _state.value.balanceSats >= debitSats + fun canWithdraw(debitSats: ULong): Boolean = _state.value.isReady && _state.value.balanceSats >= debitSats suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 220ff3369a..6e9b9a06a6 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4802,6 +4802,7 @@ class AppViewModel @Inject constructor( lightningFeeSats = (picked.leg.debitSat - picked.leg.deliveredSat).toLong(), ) } + _sendUiState.update { it.copy(isAmountInputValid = validateAmount(it.amount)) } PaykitRouteOutcome.Leg } is PaykitRoute.None -> { @@ -4986,6 +4987,7 @@ class AppViewModel @Inject constructor( return when (payMethod) { SendMethod.LIGHTNING -> { + sparkWithdrawalValidity(amount)?.let { return it } val maxSendable = maxSendableLightningSats() when (val lnurl = _sendUiState.value.lnurl) { null -> amount <= maxSendable && lightningRepo.canSend(amount) @@ -5006,6 +5008,19 @@ class AppViewModel @Inject constructor( } } + /** + * A Spark withdrawal is paid from Spark's whole balance, so Lightning's limit never applies to it: a quoted leg is + * valid only when its debit fits, and before the quote an amount Spark's balance covers lets Continue ask for one. + * Null leaves the amount to the Lightning checks. + */ + private fun sparkWithdrawalValidity(amount: ULong): Boolean? { + val state = _sendUiState.value + val route = state.paykitRoute?.takeIf { state.routesPaykitPayment && it.offersSparkLeg } ?: return null + val leg = route.serviceLeg?.takeIf { it.deliveredSat == amount } + if (leg != null) return lightningRepo.canWithdrawWithSpark(leg.debitSat) + return true.takeIf { lightningRepo.canWithdrawWithSpark(amount) } + } + private fun maxSendableLightningSats(): ULong { val max = walletRepo.balanceState.value.maxSendLightningSats val fee = _sendUiState.value.estimatedRoutingFee diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index a5c32e5438..d9cde9b590 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12222,6 +12222,38 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(REGTEST_ADDRESS, sut.sendUiState.value.address) } + @Test + fun `a spark withdrawal is weighed against spark's balance, not the lightning limit`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact").copy(deliveredSat = 999_000uL, debitSat = 999_500uL) + balanceState.value = BalanceState(maxSendLightningSats = 997_506u) + whenever(lightningRepo.canWithdrawWithSpark(leg.deliveredSat)).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(leg.debitSat)).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "continue asks spark for a quote") + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertTrue(sut.sendUiState.value.isAmountInputValid, "the quoted debit fits spark's balance") + + whenever(lightningRepo.canWithdrawWithSpark(leg.debitSat)).thenReturn(false) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.isAmountInputValid, "a debit past spark's balance can't be swiped") + } + @Test fun `router service leg opens the confirm screen with the leg's fee`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") @@ -18511,6 +18543,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) balanceState.value = BalanceState(maxSendOnchainSats = 5_000u, maxSendLightningSats = 50_000u) whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) .thenReturn(Result.success(PaykitRoute.Service(leg))) @@ -18553,6 +18586,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) balanceState.value = BalanceState(maxSendOnchainSats = 0u, maxSendLightningSats = 50_000u) whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) .thenReturn(Result.success(PaykitRoute.Service(leg))) From 7ff99a2486a7b46f14345435125695dfee858cc5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:42:05 +0100 Subject: [PATCH 59/90] fix: check a rerouted lnurl's minimum before confirm --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 6 +++-- .../viewmodels/AppViewModelSendFlowTest.kt | 22 +++++++++++++++++++ 2 files changed, 26 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 6e9b9a06a6..4648357d9c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4722,8 +4722,10 @@ class AppViewModel @Inject constructor( PaykitRouteOutcome.Direct -> Unit } } - if (lnurl is LnurlParams.LnurlPay) { - val minSendable = lnurl.data.minSendableSat() + // The route can restore an LNURL a BOLT11 pick cleared, so its minimum is read after routing. + val payLnurl = _sendUiState.value.lnurl + if (payLnurl is LnurlParams.LnurlPay) { + val minSendable = payLnurl.data.minSendableSat() if (_sendUiState.value.amount < minSendable) { toast( type = Toast.ToastType.ERROR, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d9cde9b590..00b97a6da3 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12199,6 +12199,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.sendUiState.value.decodedInvoice) } + @Test + fun `a reroute from bolt11 to lnurl below its minimum shows the minimum toast`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__title)).thenReturn("Amount Too Low") + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__description)).thenReturn("Min {amount}") + whenever(formatMoneyValue(1_000uL)).thenReturn("1000") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.lnurl) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + sut.sendEffect.test { + continueWithAmount(500u) + + assertEquals(lnurl.value, (sut.sendUiState.value.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + expectNoEvents() + } + verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooLowToast", it.testTag) }) + } + @Test fun `router direct pays the onchain endpoint it picks from savings`() = test { val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") From c73f0cddd3b5f04a550628ed92c4643fbb6fed22 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:09:18 +0100 Subject: [PATCH 60/90] fix: check a rerouted lnurl's maximum before confirm --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 11 +++++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 22 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 4648357d9c..1808dfdeda 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4722,7 +4722,7 @@ class AppViewModel @Inject constructor( PaykitRouteOutcome.Direct -> Unit } } - // The route can restore an LNURL a BOLT11 pick cleared, so its minimum is read after routing. + // The route can restore an LNURL a BOLT11 pick cleared, so its limits are read after routing. val payLnurl = _sendUiState.value.lnurl if (payLnurl is LnurlParams.LnurlPay) { val minSendable = payLnurl.data.minSendableSat() @@ -4736,6 +4736,15 @@ class AppViewModel @Inject constructor( ) return } + if (_sendUiState.value.amount > payLnurl.data.maxSendableSat()) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__lnurl_pay__error_max__title), + description = context.getString(R.string.wallet__lnurl_pay__error_max__description), + testTag = "LnurlPayAmountTooHighToast", + ) + return + } } _sendUiState.update { it.copy(isLoading = true) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 00b97a6da3..ea9d875fbf 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12221,6 +12221,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooLowToast", it.testTag) }) } + @Test + fun `a reroute from bolt11 to lnurl above its maximum shows the maximum toast`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(context.getString(R.string.wallet__lnurl_pay__error_max__title)).thenReturn("Amount Too High") + whenever(context.getString(R.string.wallet__lnurl_pay__error_max__description)).thenReturn("Max") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.lnurl) + + balanceState.value = BalanceState(maxSendLightningSats = 200_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + sut.sendEffect.test { + continueWithAmount(150_000u) + + assertEquals(lnurl.value, (sut.sendUiState.value.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + expectNoEvents() + } + verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooHighToast", it.testTag) }) + } + @Test fun `router direct pays the onchain endpoint it picks from savings`() = test { val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") From 46424572d68c28c2a94a3306024d9a5bda939ce2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:15:57 +0100 Subject: [PATCH 61/90] fix: offer the spark leg when lightning pays the lnurl minimum --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 10 ++-- .../viewmodels/AppViewModelSendFlowTest.kt | 46 +++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1808dfdeda..abbac9edbc 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4113,7 +4113,7 @@ class AppViewModel @Inject constructor( walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) // The Spark leg stays offered beside USDT, so switching such a contact to Spending can still route through it. - val offersSparkLeg = offersSparkLeg(payment, address, canUseLightning) + val offersSparkLeg = offersSparkLeg(payment, address) paykitRouteDecided = false val route = PaykitRouteUi( endpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } @@ -4288,8 +4288,12 @@ class AppViewModel @Inject constructor( return !canUseBitcoin && balance > 0u } - private fun offersSparkLeg(payment: ContactPaymentContext, address: String, canPayDirectly: Boolean): Boolean { - if (!paykitRouteRepo.canRouteThroughSpark || canPayDirectly || address.isEmpty()) return false + /** + * Offered whatever Lightning can pay when the payment opens: an amount entered later can pass Lightning's limit, + * and the router still prefers a direct payment that works. + */ + private fun offersSparkLeg(payment: ContactPaymentContext, address: String): Boolean { + if (!paykitRouteRepo.canRouteThroughSpark || address.isEmpty()) return false return payment.endpoints.any { it.methodId.isOnchain } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ea9d875fbf..d5abdbdba2 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12298,6 +12298,52 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertFalse(sut.sendUiState.value.isAmountInputValid, "a debit past spark's balance can't be swiped") } + @Test + fun `a contact whose lnurl minimum lightning pays still takes spark past the lightning limit`() = test { + val lnurl = LnurlPayData( + uri = "lnurl1sparkpastlimit", + callback = "https://example.com/pay", + minSendable = 1_000_000u, + maxSendable = 2_000_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 999_000uL, debitSat = 999_500uL) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(leg.deliveredSat)).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(leg.debitSat)).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + balanceState.value = BalanceState(maxSendLightningSats = 997_506u) + usdtEnabled.value = false + sut.openContactPayment( + paymentRequest = lnurl.uri, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ), + ) + advanceUntilIdle() + + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "spark covers what lightning can't") + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + verify(paykitRouteRepo).route(any(), any(), any(), any(), eq(true)) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + } + @Test fun `router service leg opens the confirm screen with the leg's fee`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 218000b5713ea7103059eac64aa757f14a5e42b6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:43:04 +0100 Subject: [PATCH 62/90] fix: skip the spark quote when lightning pays a contact --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 23 ++--- .../repositories/PaykitRouteRepoTest.kt | 84 +++++++++++++++++++ 2 files changed, 97 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 0005509f06..1ac1b863e5 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -20,7 +20,7 @@ import kotlin.time.Instant /** * Picks how to pay a Paykit contact through bitkit-core's Paykit router: directly from a balance the wallet holds, * or through a Spark withdrawal to the contact's on-chain endpoint when no balance reaches the contact. The router - * makes no network calls; the app quotes each Spark leg and runs the one the router returns. + * makes no network calls; the app quotes each Spark leg only when no balance pays, and runs the one the router returns. */ @Singleton class PaykitRouteRepo @Inject constructor( @@ -43,16 +43,19 @@ class PaykitRouteRepo @Inject constructor( quoteServiceLegs: Boolean, ): Result = withContext(ioDispatcher) { runSuspendCatching { - paykitRoutePayment( - request = PaykitRouteRequest( - amountSat = amountSats, - contactEndpoints = endpoints, - lightningSpendableSat = lightningSpendableSats, - onchainSpendableSat = onchainSpendableSats, - serviceLegs = if (quoteServiceLegs) serviceLegs(endpoints, amountSats) else emptyList(), - ), - network = Env.network.toCoreNetwork(), + val request = PaykitRouteRequest( + amountSat = amountSats, + contactEndpoints = endpoints, + lightningSpendableSat = lightningSpendableSats, + onchainSpendableSat = onchainSpendableSats, + serviceLegs = emptyList(), ) + val network = Env.network.toCoreNetwork() + // The router pays directly before it weighs any leg, so legs are quoted only when no balance pays. + val route = paykitRoutePayment(request, network) + if (!quoteServiceLegs || route !is PaykitRoute.None) return@runSuspendCatching route + val legs = serviceLegs(endpoints, amountSats) + if (legs.isEmpty()) route else paykitRoutePayment(request.copy(serviceLegs = legs), network) } } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt new file mode 100644 index 0000000000..964c9c96ce --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt @@ -0,0 +1,84 @@ +package to.bitkit.repositories + +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaykitRouteRequest +import com.synonym.bitkitcore.ServiceRouteLeg +import com.synonym.bitkitcore.paykitRoutePayment +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.MockedStatic +import org.mockito.Mockito.mockStatic +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +class PaykitRouteRepoTest : BaseUnitTest() { + private val sparkRepo = mock() + private val sut = PaykitRouteRepo(testDispatcher, sparkRepo) + + private val lightning = PaykitEndpoint(methodId = MethodId.Lnurl.rawValue, value = "lnurl1contact") + private val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qcontact") + private lateinit var core: MockedStatic<*> + + @Before + fun setUp() { + // Stands in for bitkit-core's router: Lightning pays directly when it covers the amount, before any leg. + core = mockStatic(Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt")) + core.`when` { paykitRoutePayment(any(), any()) }.thenAnswer { + val request = it.getArgument(0) + when { + request.lightningSpendableSat >= request.amountSat -> PaykitRoute.Direct(request.contactEndpoints[0]) + request.serviceLegs.isNotEmpty() -> PaykitRoute.Service(request.serviceLegs[0]) + else -> PaykitRoute.None("No balance can reach an endpoint this contact accepts.") + } + } + } + + @After + fun tearDown() = core.close() + + @Test + fun `a contact lightning can pay routes direct without a spark quote`() = test { + whenever(sparkRepo.withdrawalRouteLeg(any(), any())).thenReturn(Result.success(null)) + + val route = sut.route( + amountSats = 1_000uL, + endpoints = listOf(lightning, onchain), + lightningSpendableSats = 5_000uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ).getOrThrow() + + assertEquals(PaykitRoute.Direct(lightning), route) + verify(sparkRepo, never()).withdrawalRouteLeg(any(), any()) + } + + @Test + fun `an amount past lightning's limit takes the quoted spark leg`() = test { + val leg = ServiceRouteLeg( + service = SparkRepo.ROUTE_SERVICE, + endpoint = onchain, + deliveredSat = 10_000uL, + debitSat = 10_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + whenever(sparkRepo.withdrawalRouteLeg(onchain, leg.deliveredSat)).thenReturn(Result.success(leg)) + + val route = sut.route( + amountSats = leg.deliveredSat, + endpoints = listOf(lightning, onchain), + lightningSpendableSats = 5_000uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ).getOrThrow() + + assertEquals(PaykitRoute.Service(leg), route) + } +} From 3d586937afed6cc6129ad95e23184f245ca37e70 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:09:47 +0100 Subject: [PATCH 63/90] fix: route mixed bitcoin contacts through spark --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 3 +- .../viewmodels/AppViewModelSendFlowTest.kt | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index abbac9edbc..bdc057bb69 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5291,9 +5291,10 @@ class AppViewModel @Inject constructor( } } + /** Any on-chain endpoint lets Spark pay an amount the contact's Lightning endpoints or Savings can't. */ private fun requiresPaykitServiceRoute(payment: ContactPaymentContext): Boolean { if (!paykitRouteRepo.canRouteThroughSpark) return false - return payment.endpoints.isNotEmpty() && payment.endpoints.all { it.methodId.isOnchain } + return payment.endpoints.any { it.methodId.isOnchain } } private fun requiresPaykitAssetSelection(payment: ContactPaymentContext): Boolean = diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d5abdbdba2..8bd44013c7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12344,6 +12344,74 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) } + @Test + fun `a mixed contact below its lnurl minimum takes spark's onchain leg`() = test { + openMixedContact() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "spark covers what the lnurl minimum refuses") + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg, "the spark onchain leg pays") + assertEquals(SendEffect.NavigateToConfirm, expectMostRecentItem()) + } + verify(toastManager, never()).enqueue(any()) + } + + @Test + fun `a mixed contact lightning can pay routes direct`() = test { + val lnurl = openMixedContact() + val direct = PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(direct))) + + continueWithAmount(6_000u) + + verify(paykitRouteRepo).route(eq(6_000uL), any(), any(), any(), any()) + assertNull(sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + } + + /** A contact offering LNURL with a 5,000-sat minimum and on-chain, no USDT, with Spark funded and Savings empty. */ + private suspend fun TestScope.openMixedContact(): LnurlPayData { + val lnurl = LnurlPayData( + uri = "lnurl1mixedcontact", + callback = "https://example.com/pay", + minSendable = 5_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + usdtEnabled.value = false + sut.openContactPayment( + paymentRequest = lnurl.uri, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ), + ) + advanceUntilIdle() + return lnurl + } + @Test fun `router service leg opens the confirm screen with the leg's fee`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From db166254ab5999ec2a0d06cc5c53bc5431785b77 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:28:00 +0100 Subject: [PATCH 64/90] fix: hold a pending spark withdrawal until spark completes it --- .../java/to/bitkit/repositories/SparkRepo.kt | 26 ++++++++----- .../java/to/bitkit/services/SparkService.kt | 3 ++ .../to/bitkit/repositories/SparkRepoTest.kt | 38 +++++++++++++++++++ 3 files changed, 57 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7a422c0ef6..fd7c428a5b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -688,8 +688,8 @@ class SparkRepo @Inject constructor( /** * What became of an attempt to withdraw exactly [amountSats] to [address]: sent once Spark's synced list holds a - * withdrawal to it that is not one of [earlierTxids], unsent once Spark synced and no journaled withdrawal to - * [address] is still settling, else unknown. + * completed withdrawal to it that is not one of [earlierTxids], unsent once Spark synced and no journaled or + * pending withdrawal to [address] is still settling, else unknown. */ suspend fun withdrawalOutcome( address: String, @@ -701,15 +701,17 @@ class SparkRepo @Inject constructor( it.address == address && it.amountSats == amountSats && it.txid !in earlierTxids }?.let { return@withContext SparkWithdrawalOutcome.Sent(it.txid) } if (!_state.value.hasSynced || isWithdrawing) return@withContext SparkWithdrawalOutcome.Unknown - val txid = sparkService.listPayments().firstNotNullOfOrNull { payment -> - val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@firstNotNullOfOrNull null - withdraw.txId.takeIf { - payment.status != PaymentStatus.FAILED && withdraw.destinationAddress == address && - payment.amount.toLong().toULong() == amountSats && it !in earlierTxids - } + val attempts = sparkService.listPayments().filter { payment -> + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@filter false + withdraw.destinationAddress == address && payment.amount.toLong().toULong() == amountSats && + withdraw.txId !in earlierTxids } + // Spark keeps a withdrawal pending until its provider accepts the payout, which can still fail it. + val txid = attempts.firstOrNull { it.status == PaymentStatus.COMPLETED } + ?.let { (it.details as PaymentDetails.Withdraw).txId } when { txid != null -> SparkWithdrawalOutcome.Sent(txid) + attempts.any { it.status == PaymentStatus.PENDING } -> SparkWithdrawalOutcome.Unknown cacheStore.data.first().pendingSparkWithdrawal?.address == address -> SparkWithdrawalOutcome.Unknown else -> SparkWithdrawalOutcome.Unsent } @@ -780,6 +782,9 @@ class SparkRepo @Inject constructor( // A failed withdrawal paid nothing: its journal closed as recorded, so the caller sees it unsent and // releases the proof, private list and allowance attempt instead of showing success. if (payment.status == PaymentStatus.FAILED) throw SparkError.WithdrawalNotSent() + // One still pending can fail until its provider accepts the payout, so its outcome stays unknown, on + // the pending screen, until its journal settles. + if (payment.status != PaymentStatus.COMPLETED) throw SparkError.WithdrawalNotCompleted() (payment.details as? PaymentDetails.Withdraw)?.txId ?: payment.id }.onFailure { Logger.error("Failed to withdraw to a Paykit contact with Spark", it, context = TAG) @@ -1419,7 +1424,8 @@ class SparkRepo @Inject constructor( return false } unsavedPayments.remove(payment.id) - if (journal != null && settlesJournal) { + // A pending withdrawal can still fail, so only a completed or failed one closes its journal. + if (journal != null && settlesJournal && payment.status != PaymentStatus.PENDING) { // The tags picked on Confirm travel with the journal, so a recovered withdrawal keeps them too. // A failed tag write keeps the journal, so the next refresh tags it again; a deleted activity takes none. if (journal.tags.isNotEmpty() && !isDeleted) { @@ -1429,7 +1435,7 @@ class SparkRepo @Inject constructor( return false } } - val sentTxid = txid.takeIf { payment.status != PaymentStatus.FAILED } + val sentTxid = txid.takeIf { payment.status == PaymentStatus.COMPLETED } if (clearJournal(journal, sentTxid)) { _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, sentTxid)) } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 4b093d29fe..240512f5f1 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -308,6 +308,9 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me /** Spark's list shows the withdrawal never went out. */ class WithdrawalNotSent : SparkError("Spark never sent the withdrawal") + /** Spark returned the withdrawal as pending, which it can still fail, so its outcome is not known yet. */ + class WithdrawalNotCompleted : SparkError("Spark has not completed the withdrawal yet") + /** * 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. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5577d94a79..14f00a94b7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1202,6 +1202,44 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `a pending withdrawal stays open until spark completes it`() = test { + val sut = journaledSpark() + val pending = contactWithdrawal().copy(status = PaymentStatus.PENDING) + whenever(sparkService.send(any())).thenReturn(pending) + whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(pending)) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + assertNull(result.getOrNull(), "Spark can still fail a withdrawal until its provider accepts the payout") + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + assertEquals(SparkWithdrawalOutcome.Unknown, sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet())) + + whenever(sparkService.listPayments()).thenReturn(listOf(contactWithdrawal())) + sut.start(0).getOrThrow() + + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + ) + } + + @Test + fun `a pending withdrawal spark later fails closes as unsent`() = test { + val sut = journaledSpark() + val pending = contactWithdrawal().copy(status = PaymentStatus.PENDING) + whenever(sparkService.send(any())).thenReturn(pending) + whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(pending)) + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + whenever(sparkService.listPayments()).thenReturn(listOf(pending.copy(status = PaymentStatus.FAILED))) + sut.start(0).getOrThrow() + + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals(SparkWithdrawalOutcome.Unsent, sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet())) + } + @Test fun `a withdrawal to a contact is not marked as a transfer`() = test { val sent = OnchainActivity.create( From 76ed400261032f3e45fabb34336bafe920e44637 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:39:21 +0100 Subject: [PATCH 65/90] fix: close a spark withdrawal spark refuses before sending at once --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 14 +++++++++++--- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 +++-- .../java/to/bitkit/repositories/SparkRepoTest.kt | 15 +++++++++++++++ .../bitkit/viewmodels/AppViewModelSendFlowTest.kt | 12 +++++++++++- 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index fd7c428a5b..25f86aedc5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -744,11 +744,12 @@ class SparkRepo @Inject constructor( // The proof onBeforeSend starts has no journal yet, so the attempt reads as in flight from here on and // a reconcile meanwhile never drops that proof as unsent. isWithdrawing = true + var journal: PendingSparkWithdrawal? = null val sent = try { if (!onBeforeSend()) throw PaymentAbortedBeforeSend() // A quote can expire while the request and its allowance are checked. ensurePaymentDeadline(paymentDeadlineAt) - val journal = PendingSparkWithdrawal( + val opened = PendingSparkWithdrawal( address, amountSats, contact, @@ -756,10 +757,11 @@ class SparkRepo @Inject constructor( tags, startedAt = clock.now().epochSeconds, ) - cacheStore.update { it.copy(pendingSparkWithdrawal = journal) } + journal = opened + cacheStore.update { it.copy(pendingSparkWithdrawal = opened) } // Saving the journal suspends, so the deadline is checked last, before the send. runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { - clearJournal(journal) + clearJournal(opened) throw it } runSuspendCatching { sparkService.send(prepared) } @@ -767,6 +769,12 @@ class SparkRepo @Inject constructor( isWithdrawing = false } val payment = sent.getOrElse { + // Spark selects the leaves to spend before anything goes to the operators, so a short balance left + // nothing and the journal closes at once, as on the Lightning rail. + if (it is SdkException.InsufficientFunds) { + clearJournal(journal) + throw SparkError.SendRefused("Spark balance can't cover the withdrawal", it) + } // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. A // sync that never reached Spark still returns, so only one done after the failure drops it. val failedAt = clock.now().epochSeconds.toULong() diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index bdc057bb69..50f398b4fe 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7084,8 +7084,9 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { - // Spark refuses a send past its deadline before it sends and clears its journal, so no listing is needed. - if (error is ServiceError.PaymentDeadlineExpired) { + // Spark refuses a send past its deadline, or one its balance can't cover, before it sends and clears its + // journal, so no listing is needed. + if (error is ServiceError.PaymentDeadlineExpired || error is SparkError.SendRefused) { incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseRefusedSparkOnchainProof(it) } failServiceLegBeforeSend(error, preparedPaymentProofRequest, contactPaymentContext, allowanceAttemptId) return diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 14f00a94b7..33f883bee0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -53,6 +53,7 @@ import org.lightningdevkit.ldknode.Event 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 @@ -1240,6 +1241,20 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(SparkWithdrawalOutcome.Unsent, sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet())) } + @Test + fun `a withdrawal spark refuses for its balance closes its journal at once`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } + clearInvocations(sparkService) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + // Spark picks the leaves to spend before anything reaches its operators, so nothing left the wallet. + assertIs(result.exceptionOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + verify(sparkService, never()).syncWallet() + } + @Test fun `a withdrawal to a contact is not marked as a transfer`() = test { val sent = OnchainActivity.create( diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 8bd44013c7..d011f470eb 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -238,6 +238,7 @@ import to.bitkit.services.NodeServiceFgState import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.services.PaykitSdkService import to.bitkit.services.PendingChannelMigration +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.ui.Routes import to.bitkit.ui.components.Sheet @@ -12900,6 +12901,15 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `a spark leg refused at its deadline releases the request proof without a spark sync`() = test { + refuseSparkLeg(ServiceError.PaymentDeadlineExpired()) + } + + @Test + fun `a spark leg spark refuses before sending releases the request proof without a spark sync`() = test { + refuseSparkLeg(SparkError.SendRefused("Spark balance can't cover the withdrawal")) + } + + private suspend fun TestScope.refuseSparkLeg(error: Throwable) { val leg = sparkRouteLeg("bcrt1qroutedrequest") val request = paymentRequest().copy( amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), @@ -12926,7 +12936,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ).doSuspendableAnswer { val onBeforeSend = it.getArgument Boolean>(4) onBeforeSend() - Result.failure(ServiceError.PaymentDeadlineExpired()) + Result.failure(error) } setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( From b6dba158583b20ed490f8fb41738fbec5af623e2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:44:25 +0100 Subject: [PATCH 66/90] fix: refuse a second spark withdrawal while one prepares --- .../java/to/bitkit/repositories/SparkRepo.kt | 28 ++++++++++++------- .../to/bitkit/repositories/SparkRepoTest.kt | 22 +++++++++++++++ 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 25f86aedc5..505169ba37 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -164,6 +164,9 @@ class SparkRepo @Inject constructor( @Volatile private var isWithdrawing = false + /** A withdrawal to a contact holds the one journal slot, from before it prepares until its send call returns. */ + private val isClaimingWithdrawal = AtomicBoolean(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 @@ -734,18 +737,22 @@ class SparkRepo @Inject constructor( ): Result = withContext(bgDispatcher) { runSuspendCatching { - if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() - val prepared = sparkService.prepareSend(address, amountSats) - val speed = prepared.withdrawalQuote().speedMedium - val debitSats = amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() - // The user confirmed the leg's debit; a quote that rose since then needs a new confirmation. - if (maxDebitSats != null && debitSats > maxDebitSats) throw SparkError.WithdrawalFeeChanged() - val earlierTxids = withdrawalTxidsTo(address) - // The proof onBeforeSend starts has no journal yet, so the attempt reads as in flight from here on and - // a reconcile meanwhile never drops that proof as unsent. - isWithdrawing = true + // Claimed before anything suspends, so a second withdrawal started while this one prepares is refused + // instead of overwriting its journal. + if (!isClaimingWithdrawal.compareAndSet(false, true)) throw SparkError.WithdrawalPending() var journal: PendingSparkWithdrawal? = null val sent = try { + if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() + val prepared = sparkService.prepareSend(address, amountSats) + val speed = prepared.withdrawalQuote().speedMedium + val debitSats = + amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() + // The user confirmed the leg's debit; a quote that rose since then needs a new confirmation. + if (maxDebitSats != null && debitSats > maxDebitSats) throw SparkError.WithdrawalFeeChanged() + val earlierTxids = withdrawalTxidsTo(address) + // The proof onBeforeSend starts has no journal yet, so the attempt reads as in flight from here on + // and a reconcile meanwhile never drops that proof as unsent. + isWithdrawing = true if (!onBeforeSend()) throw PaymentAbortedBeforeSend() // A quote can expire while the request and its allowance are checked. ensurePaymentDeadline(paymentDeadlineAt) @@ -767,6 +774,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.send(prepared) } } finally { isWithdrawing = false + isClaimingWithdrawal.set(false) } val payment = sent.getOrElse { // Spark selects the leaves to spend before anything goes to the operators, so a short balance left diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 33f883bee0..a656f28be6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1399,6 +1399,28 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(5_000uL, cacheData.value.pendingSparkWithdrawal?.amountSats) } + @Test + fun `a second withdrawal started while the first prepares is refused`() = test { + val sut = journaledSpark() + val prepared = sparkService.prepareSend("bcrt1qcontact", 20_000uL, null) + val prepareGate = CompletableDeferred() + whenever { sparkService.prepareSend(eq("bcrt1qcontact"), eq(20_000uL), anyOrNull()) }.doSuspendableAnswer { + prepareGate.await() + prepared + } + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + val first = async { sut.withdraw("bcrt1qcontact", 20_000uL, "first") } + runCurrent() + + val second = async { sut.withdraw("bcrt1qcontact", 20_000uL, "second") } + runCurrent() + prepareGate.complete(Unit) + + assertIs(second.await().exceptionOrNull()) + assertEquals("withdrawal", first.await().getOrThrow()) + verify(sparkService, times(1)).send(any()) + } + @Test fun `a foreground during an in-flight withdrawal keeps its journal until spark lists it`() = test { val sut = journaledSpark() From a4a35f6bebe665c2502663d12e4d9c1917faf571 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:49:03 +0100 Subject: [PATCH 67/90] fix: keep boost on the savings receipt of a spark withdrawal --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 8 ++++++-- .../screens/wallets/activity/ActivityDetailScreen.kt | 5 ++++- .../to/bitkit/viewmodels/ActivityDetailViewModel.kt | 2 +- .../java/to/bitkit/repositories/SparkRepoTest.kt | 12 ++++++++++-- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 505169ba37..5764bf3ac1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -679,8 +679,12 @@ class SparkRepo @Inject constructor( (listed + recorded).toSet() } - /** Whether [txid] is a Spark withdrawal, which LDK never held and so cannot boost. */ - suspend fun isWithdrawal(txid: String): Boolean = withContext(bgDispatcher) { + /** + * Whether [txid] is the sent side of a Spark withdrawal, which LDK never held and so cannot boost. Savings owns the + * output a withdrawal to it pays, so its receipt, not [isSent], can be boosted. + */ + suspend fun isWithdrawal(txid: String, isSent: Boolean): Boolean = withContext(bgDispatcher) { + if (!isSent) return@withContext false if (cacheStore.data.first().sentSparkWithdrawals.any { it.txid == txid }) return@withContext true if (!_state.value.isReady) return@withContext false runSuspendCatching { sparkService.listPayments() } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt index be9ba8b3dc..cc3fdc36b4 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt @@ -194,7 +194,10 @@ fun ActivityDetailScreen( LaunchedEffect(item) { if (item is Activity.Onchain) { isCpfpChild = detailViewModel.isCpfpChildTransaction(item.v1.txId) - isSparkWithdrawal = detailViewModel.isSparkWithdrawal(item.v1.txId) + isSparkWithdrawal = detailViewModel.isSparkWithdrawal( + item.v1.txId, + isSent = item.v1.txType == PaymentType.SENT, + ) boostTxDoesExist = if (item.v1.boostTxIds.isNotEmpty()) { detailViewModel.getBoostTxDoesExist(item.v1.boostTxIds) } else { diff --git a/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt index b71432a92a..85f6732e2e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt @@ -272,7 +272,7 @@ class ActivityDetailViewModel @Inject constructor( suspend fun getBoostTxDoesExist(boostTxIds: List): ImmutableMap = activityRepo.getBoostTxDoesExist(boostTxIds, currentWalletId).toImmutableMap() - suspend fun isSparkWithdrawal(txId: String): Boolean = sparkRepo.isWithdrawal(txId) + suspend fun isSparkWithdrawal(txId: String, isSent: Boolean): Boolean = sparkRepo.isWithdrawal(txId, isSent) suspend fun isCpfpChildTransaction(txId: String): Boolean { return activityRepo.isCpfpChildTransaction(txId, currentWalletId) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a656f28be6..b5d60dac39 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -772,8 +772,16 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) val sut = readySpark(balanceSats = 50_000uL) - assertTrue(sut.isWithdrawal("withdrawal")) - assertFalse(sut.isWithdrawal("ldk-send")) + assertTrue(sut.isWithdrawal("withdrawal", isSent = true)) + assertFalse(sut.isWithdrawal("ldk-send", isSent = true)) + } + + @Test + fun `the savings receipt of a spark withdrawal stays boostable`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = readySpark(balanceSats = 50_000uL) + + assertFalse(sut.isWithdrawal("withdrawal", isSent = false), "Savings owns the output the withdrawal pays") } @Test From bd4b7273de194d1cd32f35808264daafa2c8806e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:56:55 +0100 Subject: [PATCH 68/90] fix: keep an lnurl its limits refuse out of the contact route --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 69 ++++++++++++------- .../viewmodels/AppViewModelSendFlowTest.kt | 41 ++++++++++- 2 files changed, 83 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 50f398b4fe..4d60a791bd 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4728,28 +4728,7 @@ class AppViewModel @Inject constructor( } // The route can restore an LNURL a BOLT11 pick cleared, so its limits are read after routing. val payLnurl = _sendUiState.value.lnurl - if (payLnurl is LnurlParams.LnurlPay) { - val minSendable = payLnurl.data.minSendableSat() - if (_sendUiState.value.amount < minSendable) { - toast( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.wallet__lnurl_pay__error_min__title), - description = context.getString(R.string.wallet__lnurl_pay__error_min__description) - .replace("{amount}", formatMoneyValue(minSendable)), - testTag = "LnurlPayAmountTooLowToast", - ) - return - } - if (_sendUiState.value.amount > payLnurl.data.maxSendableSat()) { - toast( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.wallet__lnurl_pay__error_max__title), - description = context.getString(R.string.wallet__lnurl_pay__error_max__description), - testTag = "LnurlPayAmountTooHighToast", - ) - return - } - } + if (payLnurl is LnurlParams.LnurlPay && !validateLnurlAmount(payLnurl, _sendUiState.value.amount)) return _sendUiState.update { it.copy(isLoading = true) } try { @@ -4764,9 +4743,35 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) } + /** Shows [lnurl]'s too-low or too-high toast when [amount] is outside its limits; true when it accepts it. */ + private suspend fun validateLnurlAmount(lnurl: LnurlParams.LnurlPay, amount: ULong): Boolean { + val minSendable = lnurl.data.minSendableSat() + if (amount < minSendable) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__lnurl_pay__error_min__title), + description = context.getString(R.string.wallet__lnurl_pay__error_min__description) + .replace("{amount}", formatMoneyValue(minSendable)), + testTag = "LnurlPayAmountTooLowToast", + ) + return false + } + if (amount > lnurl.data.maxSendableSat()) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__lnurl_pay__error_max__title), + description = context.getString(R.string.wallet__lnurl_pay__error_max__description), + testTag = "LnurlPayAmountTooHighToast", + ) + return false + } + return true + } + /** - * Asks bitkit-core's router how to pay the contact from the selected source: Spending offers every endpoint and a - * Spark leg to on-chain ones, Savings only the on-chain endpoints. Direct pays the endpoint it names. + * Asks bitkit-core's router how to pay the contact from the selected source: Spending offers every endpoint but an + * LNURL whose limits refuse the amount, and a Spark leg to on-chain ones; Savings only the on-chain endpoints. + * Direct pays the endpoint it names. */ private suspend fun routePaykitPayment(route: PaykitRouteUi): PaykitRouteOutcome { val state = _sendUiState.value @@ -4776,9 +4781,15 @@ class AppViewModel @Inject constructor( val lightningSpendable = if (fromSpending) maxSendableLightningSats() else 0uL val onchainSpendable = if (fromSpending) 0uL else walletRepo.balanceState.value.maxSendOnchainSats _sendUiState.update { it.copy(isLoading = true) } + // An LNURL whose limits refuse the amount must never win over an affordable Spark leg. + val refusingLnurl = route.lnurl?.takeIf { fromSpending && !it.accepts(state.amount) } val result = paykitRouteRepo.route( amountSats = state.amount, - endpoints = if (fromSpending) route.endpoints else route.endpoints.filter { it.isOnchain() }, + endpoints = when { + !fromSpending -> route.endpoints.filter { it.isOnchain() } + refusingLnurl != null -> route.endpoints.filterNot { it.methodId == MethodId.Lnurl.rawValue } + else -> route.endpoints + }, lightningSpendableSats = lightningSpendable, onchainSpendableSats = onchainSpendable, quoteServiceLegs = fromSpending && route.offersSparkLeg, @@ -4825,6 +4836,11 @@ class AppViewModel @Inject constructor( _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } // The router's reason is English for the log: the app tells a short balance from an unusable contact. val isBalanceShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() + // The router never saw an LNURL whose limits refuse the amount, so its limit says why. + if (!isBalanceShort && refusingLnurl != null) { + validateLnurlAmount(refusingLnurl, state.amount) + return PaykitRouteOutcome.Refused + } toast( type = Toast.ToastType.ERROR, title = context.getString( @@ -9634,6 +9650,9 @@ private enum class PaykitRouteOutcome { Direct, Leg, Refused, Stale } private fun PaykitEndpoint.isOnchain(): Boolean = MethodId.fromRawValue(methodId)?.isOnchain == true +private fun LnurlParams.LnurlPay.accepts(amount: ULong): Boolean = + amount in data.minSendableSat()..data.maxSendableSat() + @Immutable data class OnchainFeeUi( val rate: FeeRate = FeeRate.fromSpeed(TransactionSpeed.default()), diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d011f470eb..233054e78f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -723,8 +723,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val fromSpending = it.getArgument(3) == 0L val picked = endpoints.firstOrNull { endpoint -> MethodId.fromRawValue(endpoint.methodId)?.isOnchain != fromSpending - } ?: endpoints.first() - PaykitRoute.Direct(picked) + } ?: endpoints.firstOrNull() + picked?.let { endpoint -> PaykitRoute.Direct(endpoint) } ?: PaykitRoute.None("No endpoint") } whenever(connectionRecovery.currentGeneration()).thenAnswer { walletGeneration } whenever(connectionRecovery.isCurrentGeneration(anyOrNull())).thenAnswer { @@ -12367,6 +12367,41 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(toastManager, never()).enqueue(any()) } + @Test + fun `a mixed contact below its lnurl minimum offers the router only its onchain endpoint`() = test { + openMixedContact() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + continueWithAmount(leg.deliveredSat) + + // An LNURL whose minimum refuses the amount would win over an affordable Spark leg. + verify(paykitRouteRepo).route( + eq(leg.deliveredSat), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + any(), + any(), + any(), + ) + } + + @Test + fun `a mixed contact no route pays below its lnurl minimum shows the lnurl minimum`() = test { + openMixedContact() + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__title)).thenReturn("Amount Too Low") + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__description)).thenReturn("Min {amount}") + whenever(formatMoneyValue(5_000uL)).thenReturn("5000") + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark can't cover the fee"))) + + continueWithAmount(2_000u) + + verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooLowToast", it.testTag) }) + } + @Test fun `a mixed contact lightning can pay routes direct`() = test { val lnurl = openMixedContact() @@ -19099,6 +19134,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.canSend(any())).thenReturn(true) whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + // Below the minimum, the router gets no endpoint and the LNURL's minimum toast names the amount. + whenever(formatMoneyValue(any())).thenReturn("1,000 sats") for ((cents, route) in listOf(50uL to SendRoute.Amount, 250uL to SendRoute.Confirm)) { val request = paymentRequest().copy( amount = PaykitAmount(PaykitAsset.USD, cents), From 5a168c59ea4e7dff2946e196d6f6cfeb2a975e8c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:01:26 +0100 Subject: [PATCH 69/90] fix: show a short balance when the spark fee does not fit --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 24 +++++++++++++++---- .../java/to/bitkit/repositories/SparkRepo.kt | 6 +++-- .../java/to/bitkit/services/SparkService.kt | 3 +++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 19 ++++++++++----- .../repositories/PaykitRouteRepoTest.kt | 19 +++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 2 +- .../viewmodels/AppViewModelSendFlowTest.kt | 21 ++++++++++++++++ 7 files changed, 80 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 1ac1b863e5..00faaaf57d 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -11,6 +11,7 @@ import to.bitkit.di.IoDispatcher import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching import to.bitkit.models.toCoreNetwork +import to.bitkit.services.SparkError import to.bitkit.utils.AppError import to.bitkit.utils.Logger import javax.inject.Inject @@ -35,6 +36,10 @@ class PaykitRouteRepo @Inject constructor( val canRouteThroughSpark: Boolean get() = sparkRepo.state.value.let { it.isReady && it.sendableSats > 0uL } + /** + * Fails with [SparkError.WithdrawalOverBalance] when no route pays because Spark's balance covers the amount but + * not the withdrawal fee on top, so the app tells a short balance from a contact it can't pay. + */ suspend fun route( amountSats: ULong, endpoints: List, @@ -54,17 +59,26 @@ class PaykitRouteRepo @Inject constructor( // The router pays directly before it weighs any leg, so legs are quoted only when no balance pays. val route = paykitRoutePayment(request, network) if (!quoteServiceLegs || route !is PaykitRoute.None) return@runSuspendCatching route - val legs = serviceLegs(endpoints, amountSats) - if (legs.isEmpty()) route else paykitRoutePayment(request.copy(serviceLegs = legs), network) + val quotes = serviceLegQuotes(endpoints, amountSats) + val legs = quotes.mapNotNull { it.getOrNull() } + if (legs.isNotEmpty()) { + return@runSuspendCatching paykitRoutePayment(request.copy(serviceLegs = legs), network) + } + if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalOverBalance }) { + throw SparkError.WithdrawalOverBalance() + } + route } } /** Spark withdrawals to the contact's on-chain endpoints, each quoted with its fee. */ - private suspend fun serviceLegs(endpoints: List, amountSats: ULong): List = - endpoints.filter { MethodId.fromRawValue(it.methodId)?.isOnchain == true }.mapNotNull { endpoint -> + private suspend fun serviceLegQuotes( + endpoints: List, + amountSats: ULong, + ): List> = + endpoints.filter { MethodId.fromRawValue(it.methodId)?.isOnchain == true }.map { endpoint -> sparkRepo.withdrawalRouteLeg(endpoint, amountSats) .onFailure { Logger.warn("No Spark route to '${endpoint.methodId}'", it, context = TAG) } - .getOrNull() } /** diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 5764bf3ac1..89e663411c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -644,7 +644,8 @@ class SparkRepo @Inject constructor( /** * A Paykit route that withdraws exactly [amountSats] to the contact's on-chain [endpoint] at medium speed, with - * Spark's fee on top, or null while Spark cannot send it. bitkit-core weighs it against the Pubky Swaps providers. + * Spark's fee on top, or null while Spark cannot send it. Fails with [SparkError.WithdrawalOverBalance] when the + * balance covers the amount but not the fee on top. bitkit-core weighs it against the Pubky Swaps providers. */ suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result = withContext(bgDispatcher) { @@ -655,7 +656,8 @@ class SparkRepo @Inject constructor( // Spark charges its fee and the L1 broadcast fee on top of what reaches the contact. val speed = quote.speedMedium val debitSats = amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() - if (quote.isEstimate || !canWithdraw(debitSats)) return@runSuspendCatching null + if (quote.isEstimate) return@runSuspendCatching null + if (!canWithdraw(debitSats)) throw SparkError.WithdrawalOverBalance() ServiceRouteLeg( service = ROUTE_SERVICE, endpoint = endpoint, diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 240512f5f1..cd5a8869fe 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -305,6 +305,9 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me class WithdrawalPending : SparkError("An earlier Spark withdrawal is still settling") + /** Spark could withdraw to the contact, but its balance can't cover the amount plus the withdrawal fee. */ + class WithdrawalOverBalance : SparkError("Spark balance can't cover the withdrawal and its fee") + /** Spark's list shows the withdrawal never went out. */ class WithdrawalNotSent : SparkError("Spark never sent the withdrawal") diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 4d60a791bd..712fca7e15 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4808,10 +4808,16 @@ class AppViewModel @Inject constructor( return PaykitRouteOutcome.Stale } _sendUiState.update { it.copy(isLoading = false) } - val picked = result.getOrElse { - Logger.error("Failed to route Paykit payment", it, context = TAG) - toast(it) - return PaykitRouteOutcome.Refused + // Spark could reach the contact, but not with the withdrawal fee on top, so no route pays for want of balance. + val isLegOverBalance = result.exceptionOrNull() is SparkError.WithdrawalOverBalance + val picked = if (isLegOverBalance) { + PaykitRoute.None("Spark balance can't cover the withdrawal and its fee") + } else { + result.getOrElse { + Logger.error("Failed to route Paykit payment", it, context = TAG) + toast(it) + return PaykitRouteOutcome.Refused + } } // Once the router answered, even with no route, every later source switch asks it again: a stale source // must never fall through to a payment the router never picked. @@ -4835,12 +4841,13 @@ class AppViewModel @Inject constructor( Logger.warn("Found no Paykit route: '${picked.reason}'", context = TAG) _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } // The router's reason is English for the log: the app tells a short balance from an unusable contact. - val isBalanceShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() + val isAmountShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() // The router never saw an LNURL whose limits refuse the amount, so its limit says why. - if (!isBalanceShort && refusingLnurl != null) { + if (!isAmountShort && refusingLnurl != null) { validateLnurlAmount(refusingLnurl, state.amount) return PaykitRouteOutcome.Refused } + val isBalanceShort = isAmountShort || isLegOverBalance toast( type = Toast.ToastType.ERROR, title = context.getString( diff --git a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt index 964c9c96ce..cef81262cb 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt @@ -15,8 +15,10 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals +import kotlin.test.assertIs class PaykitRouteRepoTest : BaseUnitTest() { private val sparkRepo = mock() @@ -81,4 +83,21 @@ class PaykitRouteRepoTest : BaseUnitTest() { assertEquals(PaykitRoute.Service(leg), route) } + + @Test + fun `a spark leg whose fee the balance can't cover routes as a short balance`() = test { + whenever(sparkRepo.withdrawalRouteLeg(onchain, 9_000uL)) + .thenReturn(Result.failure(SparkError.WithdrawalOverBalance())) + + val route = sut.route( + amountSats = 9_000uL, + endpoints = listOf(onchain), + // The stand-in router pays any endpoint directly from Lightning, so none is offered. + lightningSpendableSats = 0uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ) + + assertIs(route.exceptionOrNull()) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b5d60dac39..2dc91f8ceb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -757,7 +757,7 @@ class SparkRepoTest : BaseUnitTest() { fun `offers no route leg the balance cannot cover with its fee`() = test { val sut = readySpark(balanceSats = 20_499uL) - assertEquals(null, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()) + assertIs(sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull()) } @Test diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 233054e78f..b5e8fbd98b 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12495,6 +12495,27 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `a spark leg whose fee the balance can't cover says the balance is short`() = test { + // A Spark-only wallet with 10,000 sendable pays an on-chain-only contact 9,000, and the leg fee is about 2,190. + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.failure(SparkError.WithdrawalOverBalance())) + setSendState( + SendUiState( + amount = 9_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(onchain), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(toastManager).enqueue(check { assertEquals("PaykitRouteBalanceToast", it.testTag) }) + } + private suspend fun TestScope.routerNone(maxSendLightningSats: ULong) { val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") balanceState.value = BalanceState(maxSendLightningSats = maxSendLightningSats) From 7374cec387e5d15955e83935cc9c992cea6067cb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:14:17 +0100 Subject: [PATCH 70/90] fix: keep confirm closed for a request past the lnurl maximum --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 12 +++-- .../viewmodels/AppViewModelSendFlowTest.kt | 47 +++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 712fca7e15..cc29465140 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4265,7 +4265,7 @@ class AppViewModel @Inject constructor( if (state.paykitUsesUsdt) return false val lnurl = state.lnurl as? LnurlParams.LnurlPay if (state.payMethod == SendMethod.LIGHTNING && lnurl != null && state.routedPaykitRoute?.serviceLeg == null && - state.amount < lnurl.data.minSendableSat() + !lnurl.accepts(state.amount) ) { return false } @@ -4482,8 +4482,14 @@ class AppViewModel @Inject constructor( // A source switch on Confirm asks the router again, for a request (no amount step) or a route already decided. if (activeIncomingPaymentRequest() != null || paykitRouteDecided) { _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { - // A refused route leaves no leg or invoice to pay; switching the source again recomputes validity. - if (routePaykitPayment(it) == PaykitRouteOutcome.Refused) { + // A refused route leaves no leg or invoice to pay, and a picked LNURL past its limits can't be paid; + // switching the source again recomputes validity. + val outcome = routePaykitPayment(it) + val routed = _sendUiState.value + val lnurl = routed.lnurl as? LnurlParams.LnurlPay + val isPastLnurlLimits = outcome == PaykitRouteOutcome.Direct && lnurl != null && + routed.payMethod == SendMethod.LIGHTNING && !lnurl.accepts(routed.amount) + if (outcome == PaykitRouteOutcome.Refused || isPastLnurlLimits) { _sendUiState.update { state -> state.copy(isAmountInputValid = false) } } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index b5e8fbd98b..14972ce157 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12448,6 +12448,53 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return lnurl } + @Test + fun `a request above a routed lnurl's maximum does not open a swipeable confirm`() = test { + val lnurl = LnurlPayData( + uri = "lnurl1requestpastmax", + callback = "https://example.com/pay", + minSendable = 1_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + val endpoints = listOf( + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 150_000uL), + acceptedPaymentEndpointIdentifiers = endpoints.map { it.methodId.rawValue }, + ) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(150_000uL)).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri)))) + balanceState.value = BalanceState(maxSendLightningSats = 200_000u) + usdtEnabled.value = false + + sut.openContactPayment(lnurl.uri, testPublicKey, incomingPaymentRequest = request, endpoints = endpoints) + advanceUntilIdle() + + val state = sut.sendUiState.value + assertEquals(150_000uL, state.amount) + assertEquals(lnurl.uri, (state.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + assertNull(state.routedPaykitRoute?.serviceLeg) + assertFalse( + sut.currentSheet.value == Sheet.Send(SendRoute.Confirm) && state.isAmountInputValid, + "confirm opened swipeable for 150,000 sats past the lnurl's 100,000-sat maximum " + + "(sheet=${sut.currentSheet.value}, isAmountInputValid=${state.isAmountInputValid})", + ) + } + @Test fun `router service leg opens the confirm screen with the leg's fee`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") From 5042f416fc898366b97281fed60f3e692f36485a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:29:51 +0100 Subject: [PATCH 71/90] fix: let savings pay a contact below its lnurl minimum --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 9 +++++++-- .../viewmodels/AppViewModelSendFlowTest.kt | 19 +++++++++++++++++++ 2 files changed, 26 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 114c06fedf..32630fcb90 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4737,9 +4737,14 @@ class AppViewModel @Inject constructor( PaykitRouteOutcome.Direct -> Unit } } - // The route can restore an LNURL a BOLT11 pick cleared, so its limits are read after routing. + // The route can restore an LNURL a BOLT11 pick cleared, so its limits are read after routing. An on-chain + // pick keeps the contact's LNURL in state, and its limits never apply to that payment. val payLnurl = _sendUiState.value.lnurl - if (payLnurl is LnurlParams.LnurlPay && !validateLnurlAmount(payLnurl, _sendUiState.value.amount)) return + if (payLnurl is LnurlParams.LnurlPay && _sendUiState.value.payMethod == SendMethod.LIGHTNING && + !validateLnurlAmount(payLnurl, _sendUiState.value.amount) + ) { + return + } _sendUiState.update { it.copy(isLoading = true) } try { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 17fc85ec4a..332d86244d 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12549,6 +12549,25 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooLowToast", it.testTag) }) } + @Test + fun `a savings payment to a mixed contact below its lnurl minimum is not blocked by the lnurl`() = test { + openMixedContact() + balanceState.value = BalanceState(maxSendLightningSats = 100_000u, maxSendOnchainSats = 100_000u) + whenever(formatMoneyValue(any())).thenReturn("5,000 sats") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS)))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + + sut.sendEffect.test { + continueWithAmount(2_000u) + + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + verify(toastManager, never()).enqueue(argThat { testTag == "LnurlPayAmountTooLowToast" }) + assertEquals(SendEffect.NavigateToConfirm, expectMostRecentItem()) + } + } + @Test fun `a mixed contact lightning can pay routes direct`() = test { val lnurl = openMixedContact() From eb6e8e1efef5ae5a464fed8d5c345127c7ccd9f8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:55:18 +0100 Subject: [PATCH 72/90] fix: leave an open contact withdrawal off spark's transfers to savings --- .../java/to/bitkit/repositories/SparkRepo.kt | 5 ++++- .../to/bitkit/repositories/SparkRepoTest.kt | 17 +++++++++++++++++ 2 files changed, 21 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 570adcd2f2..f12aa79224 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -930,7 +930,10 @@ class SparkRepo @Inject constructor( .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 transfers = payments.toWithdrawals().filterNot { isContactWithdrawal(it.txid) }.toImmutableList() + // The open journal's withdrawal pays a contact, also before its send activity is written. + val journal = cacheStore.data.first().pendingSparkWithdrawal + val transfers = payments.filterNot { journal?.matches(it) == true }.toWithdrawals() + .filterNot { isContactWithdrawal(it.txid) }.toImmutableList() val failedAt = withdrawalFailedAtSecs val hasSyncedSince = failedAt != null && info.lastSyncError == null && (info.lastSyncedAt ?: 0uL) > failedAt if (info.balanceSats > 0uL || hasSyncedSince) withdrawalFailedAtSecs = null diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a2b1fa6f90..745ff94e6d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -918,6 +918,23 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a pending contact withdrawal is no transfer to savings while its journal is open`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() } + .thenReturn(listOf(contactWithdrawal().copy(status = PaymentStatus.PENDING))) + + val sut = journaledSpark() + + assertEquals( + emptyList(), + sut.state.value.withdrawals, + "The refresh on start runs before the contact's send is written, and the payment pays the contact", + ) + } + @Test fun `drops a journaled withdrawal Spark never sent`() = test { cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } From 6370c373f198e66cc9af03f967b2048f9dccc015 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:57:44 +0100 Subject: [PATCH 73/90] fix: close a contact withdrawal spark refuses for a fee rise at once --- .../java/to/bitkit/repositories/SparkRepo.kt | 13 +++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f12aa79224..065e6afa21 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -789,6 +789,12 @@ class SparkRepo @Inject constructor( clearJournal(journal) throw SparkError.SendRefused("Spark balance can't cover the withdrawal", it) } + // Spark refreshes an expiring quote and checks its fee against the prepared one before it + // withdraws, so a fee rise left nothing too. + if (it.isWithdrawalFeeRise()) { + clearJournal(journal) + throw SparkError.SendRefused("Spark's withdrawal fee rose past its quote", it) + } // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. A // sync that never reached Spark still returns, so only one done after the failure drops it. val failedAt = clock.now().epochSeconds.toULong() @@ -1781,6 +1787,13 @@ sealed interface SparkClaimStep { internal fun SdkException.InvalidInput.isBelowMinimum(): Boolean = v1.startsWith("Amount is below the minimum", ignoreCase = true) +/** + * Spark refuses a withdrawal whose refreshed fee quote costs more than the prepared one, even at its slowest speed, + * with this input error before it withdraws (`affordable_speed` in the 0.28.0 SDK's `send/bitcoin_address.rs`). + */ +internal fun Throwable.isWithdrawalFeeRise(): Boolean = + this is SdkException.InvalidInput && v1.contains("onchain fee rose to", 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) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 745ff94e6d..f271fda3a3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1326,6 +1326,25 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).syncWallet() } + @Test + fun `a withdrawal spark refuses for a fee that rose past its quote closes its journal at once`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any()) }.thenAnswer { + throw SdkException.InvalidInput( + "The onchain fee rose to 900 sats at the slowest speed, above the 500 sats quoted for this payment. " + + "Please re-prepare the payment.", + ) + } + clearInvocations(sparkService) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + // Spark refreshes an expiring quote and checks its fee before it withdraws, so nothing left the wallet. + assertIs(result.exceptionOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + verify(sparkService, never()).syncWallet() + } + @Test fun `a withdrawal to a contact is not marked as a transfer`() = test { val sent = OnchainActivity.create( From d1b899a9798e148df380f01655f8a84190b3f292 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:01:28 +0100 Subject: [PATCH 74/90] fix: skip the lnurl invoice fetch for an on-chain contact payment --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 39 +++++++++++++++++++ 2 files changed, 42 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 32630fcb90..632b0f338d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6590,8 +6590,9 @@ class AppViewModel @Inject constructor( val amount = _sendUiState.value.amount val lnurl = _sendUiState.value.lnurl - // A Spark leg pays the on-chain endpoint, so it fetches no invoice from the unselected LNURL. - val isLnurlPay = lnurl is LnurlParams.LnurlPay && _sendUiState.value.routedPaykitRoute?.serviceLeg == null + // An on-chain payment, from Savings or a Spark leg, fetches no invoice from the unselected LNURL. + val isLnurlPay = lnurl is LnurlParams.LnurlPay && _sendUiState.value.payMethod == SendMethod.LIGHTNING && + _sendUiState.value.routedPaykitRoute?.serviceLeg == null if (isLnurlPay) { val amountMsats = lnurl.data.callbackAmountMsats(amount) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 332d86244d..ab6b99b0dd 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12568,6 +12568,45 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `a savings payment to a mixed contact below its lnurl minimum sends on-chain without the lnurl`() = test { + openMixedContact() + balanceState.value = BalanceState(maxSendLightningSats = 100_000u, maxSendOnchainSats = 100_000u) + whenever(formatMoneyValue(any())).thenReturn("5,000 sats") + whenever(lightningRepo.fetchLnurlInvoice(any(), any(), anyOrNull())) + .thenReturn(Result.failure(AppError("Amount is below the LNURL minimum"))) + stubSuccessfulOnchainSend(REGTEST_ADDRESS, 2_000uL) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS)))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + continueWithAmount(2_000u) + + confirmCurrentPayment() + + verify(lightningRepo, never()).fetchLnurlInvoice(any(), any(), anyOrNull()) + verify(lightningRepo).sendOnChain( + address = eq(REGTEST_ADDRESS), + sats = any(), + speed = anyOrNull(), + utxosToSpend = anyOrNull(), + feeRates = anyOrNull(), + isTransfer = any(), + channelId = anyOrNull(), + isMaxAmount = any(), + tags = any(), + beforeSendAttempt = any(), + onBroadcast = any(), + requestId = anyOrNull(), + orderId = anyOrNull(), + transferContext = anyOrNull(), + payerIdentity = anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + } + @Test fun `a mixed contact lightning can pay routes direct`() = test { val lnurl = openMixedContact() From a5022fea820db9bfedce433d8bbf07460cee0b40 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:04:56 +0100 Subject: [PATCH 75/90] fix: refuse a spark contact leg while an earlier withdrawal settles --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 6 +++++- .../java/to/bitkit/repositories/SparkRepo.kt | 5 ++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 20 +++++++++++------- app/src/main/res/values/strings.xml | 1 + .../repositories/PaykitRouteRepoTest.kt | 16 ++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 9 ++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 21 +++++++++++++++++++ 7 files changed, 69 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 00faaaf57d..9951b9fcab 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -38,7 +38,8 @@ class PaykitRouteRepo @Inject constructor( /** * Fails with [SparkError.WithdrawalOverBalance] when no route pays because Spark's balance covers the amount but - * not the withdrawal fee on top, so the app tells a short balance from a contact it can't pay. + * not the withdrawal fee on top, so the app tells a short balance from a contact it can't pay, and with + * [SparkError.WithdrawalPending] when only a Spark leg could pay while an earlier contact withdrawal settles. */ suspend fun route( amountSats: ULong, @@ -64,6 +65,9 @@ class PaykitRouteRepo @Inject constructor( if (legs.isNotEmpty()) { return@runSuspendCatching paykitRoutePayment(request.copy(serviceLegs = legs), network) } + if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalPending }) { + throw SparkError.WithdrawalPending() + } if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalOverBalance }) { throw SparkError.WithdrawalOverBalance() } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 065e6afa21..745be19d35 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -645,11 +645,14 @@ class SparkRepo @Inject constructor( /** * A Paykit route that withdraws exactly [amountSats] to the contact's on-chain [endpoint] at medium speed, with * Spark's fee on top, or null while Spark cannot send it. Fails with [SparkError.WithdrawalOverBalance] when the - * balance covers the amount but not the fee on top. bitkit-core weighs it against the Pubky Swaps providers. + * balance covers the amount but not the fee on top, and with [SparkError.WithdrawalPending] while an earlier + * contact withdrawal's journal is open, as [withdraw] would refuse it. bitkit-core weighs it against the Pubky + * Swaps providers. */ suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result = withContext(bgDispatcher) { runSuspendCatching { + if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() if (!canWithdraw(amountSats)) return@runSuspendCatching null val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 632b0f338d..c09b995b27 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4826,8 +4826,10 @@ class AppViewModel @Inject constructor( _sendUiState.update { it.copy(isLoading = false) } // Spark could reach the contact, but not with the withdrawal fee on top, so no route pays for want of balance. val isLegOverBalance = result.exceptionOrNull() is SparkError.WithdrawalOverBalance - val picked = if (isLegOverBalance) { - PaykitRoute.None("Spark balance can't cover the withdrawal and its fee") + // Only a Spark leg could pay, and Spark takes one contact withdrawal at a time. + val isLegSettling = result.exceptionOrNull() is SparkError.WithdrawalPending + val picked = if (isLegOverBalance || isLegSettling) { + PaykitRoute.None(result.exceptionOrNull()?.message.orEmpty()) } else { result.getOrElse { Logger.error("Failed to route Paykit payment", it, context = TAG) @@ -4874,13 +4876,17 @@ class AppViewModel @Inject constructor( } ), description = context.getString( - if (isBalanceShort) { - R.string.wallet__send_amount_exceeded__description - } else { - R.string.wallet__send_paykit_no_route__description + when { + isBalanceShort -> R.string.wallet__send_amount_exceeded__description + isLegSettling -> R.string.wallet__send_paykit_withdrawal_settling__description + else -> R.string.wallet__send_paykit_no_route__description } ), - testTag = if (isBalanceShort) "PaykitRouteBalanceToast" else "PaykitRouteNoneToast", + testTag = when { + isBalanceShort -> "PaykitRouteBalanceToast" + isLegSettling -> "PaykitRouteSettlingToast" + else -> "PaykitRouteNoneToast" + }, ) PaykitRouteOutcome.Refused } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7da6da2ad4..15ded59c00 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1641,6 +1641,7 @@ Reserve Balance This contact has no payment method Bitkit can use right now. Can\'t pay this contact + An earlier withdrawal from your spending balance is still settling. Try again once it completes. Cancel expired payment Checking the network. This can take up to 30 seconds. Payment cancelled. Its coins are back in your wallet. diff --git a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt index cef81262cb..f5e46ecb99 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt @@ -100,4 +100,20 @@ class PaykitRouteRepoTest : BaseUnitTest() { assertIs(route.exceptionOrNull()) } + + @Test + fun `a spark leg refused while an earlier withdrawal settles routes as settling`() = test { + whenever(sparkRepo.withdrawalRouteLeg(onchain, 9_000uL)) + .thenReturn(Result.failure(SparkError.WithdrawalPending())) + + val route = sut.route( + amountSats = 9_000uL, + endpoints = listOf(onchain), + lightningSpendableSats = 0uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ) + + assertIs(route.exceptionOrNull()) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f271fda3a3..43ac763b96 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -806,6 +806,15 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull()) } + @Test + fun `quotes no route leg while an earlier contact withdrawal settles`() = test { + val sut = readySpark(balanceSats = 50_000uL) + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qearlier", 5_000uL, null)) } + + assertIs(sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull(), anyOrNull()) + } + @Test fun `quotes a route leg whose debit takes the whole balance`() = test { val sut = readySpark(balanceSats = 20_500uL) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ab6b99b0dd..f9213c1581 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12747,6 +12747,27 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `a spark leg refused while an earlier withdrawal settles says it is still settling`() = test { + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.failure(SparkError.WithdrawalPending())) + setSendState( + SendUiState( + amount = 9_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(onchain), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(toastManager).enqueue(check { assertEquals("PaykitRouteSettlingToast", it.testTag) }) + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + } + @Test fun `a spark leg whose fee the balance can't cover says the balance is short`() = test { // A Spark-only wallet with 10,000 sendable pays an on-chain-only contact 9,000, and the leg fee is about 2,190. From 315cd03bfa3c11ec05e8c0d666a9e3d3a8c23046 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:17:12 +0100 Subject: [PATCH 76/90] fix: confirm an on-chain contact payment with its on-chain details --- .../screens/wallets/send/SendConfirmScreen.kt | 8 +- .../send/SendConfirmLnurlOnchainTest.kt | 73 +++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index bfcba46970..cb0a4f2dd3 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -272,7 +272,7 @@ internal fun SendConfirmContent( ) .navigationBarsPadding() ) { - val isLnurlPay = uiState.lnurl is LnurlParams.LnurlPay + val isLnurlPay = uiState.paysLnurl SendContactTopBar( titleText = when { @@ -365,7 +365,7 @@ private fun ContentRunning( var showDetails by rememberSaveable(initialShowDetails) { mutableStateOf(initialShowDetails) } val swipeProgress = remember { mutableFloatStateOf(0f) } val isPreparing = preparingRequest != null - val isLnurlPay = !isPreparing && uiState.lnurl is LnurlParams.LnurlPay + val isLnurlPay = !isPreparing && uiState.paysLnurl val isHardwareFeeLoading = uiState.hardwareWalletId != null && uiState.onchainFeeUi.isLoading val accentColor = when { @@ -921,6 +921,10 @@ private fun ContactRecipient( } } +/** An on-chain pick or a Spark leg keeps the contact's LNURL in state without paying it. */ +private val SendUiState.paysLnurl: Boolean + get() = lnurl is LnurlParams.LnurlPay && payMethod == SendMethod.LIGHTNING && routedPaykitRoute?.serviceLeg == null + private val SendUiState.confirmationRequestNote: String? get() = paymentRequestNote?.trim()?.takeIf { isPaymentRequest && it.isNotEmpty() } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt new file mode 100644 index 0000000000..16c8499dac --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt @@ -0,0 +1,73 @@ +package to.bitkit.ui.screens.wallets.send + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.test.core.app.ApplicationProvider +import com.synonym.bitkitcore.LnurlPayData +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.R +import to.bitkit.ui.shared.modifiers.sheetHeight +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.LnurlParams +import to.bitkit.viewmodels.SendMethod +import to.bitkit.viewmodels.SendUiState + +@RunWith(RobolectricTestRunner::class) +class SendConfirmLnurlOnchainTest { + @get:Rule + val composeRule = createComposeRule() + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `an onchain payment to a contact with an lnurl confirms with the onchain details`() { + val lnurl = LnurlPayData( + uri = "lnurl1mixedcontact", + callback = "https://example.com/pay", + minSendable = 5_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + composeRule.setContent { + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { + SendConfirmContent( + uiState = SendUiState( + amount = 6_000u, + address = ADDRESS, + isAmountInputValid = true, + payMethod = SendMethod.ONCHAIN, + lnurl = LnurlParams.LnurlPay(lnurl), + ), + isNodeRunning = true, + isLoading = false, + showBiometrics = false, + initialShowDetails = true, + modifier = Modifier.sheetHeight() + ) + } + } + } + val lnurlTitle = ApplicationProvider.getApplicationContext() + .getString(R.string.wallet__lnurl_p_title) + + composeRule.onNodeWithText(lnurlTitle).assertDoesNotExist() + composeRule.onNodeWithTag("SendConfirmToggleDetails").assertExists() + composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) + } + + private companion object { + const val ADDRESS = "bcrt1qkgfgyxyqhvkdqh04sklnzxphmcds6vft6y7h0r" + } +} From b43fae99a9e72c6b52256a157fce707cb9094bd3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:19:46 +0100 Subject: [PATCH 77/90] fix: drop a spark leg's fee when the router picks the lnurl --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c09b995b27..1e03b2d0ac 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4906,6 +4906,8 @@ class AppViewModel @Inject constructor( payMethod = SendMethod.LIGHTNING, decodedInvoice = null, lnurl = route.lnurl ?: it.lnurl, + // No invoice to estimate yet, so an earlier Spark leg's withdrawal fee would stay on Confirm. + lightningFeeSats = null, paykitRoute = route.copy(serviceLeg = null), ) else -> it.copy( diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index f9213c1581..8dc49dfe04 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12607,6 +12607,26 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `a direct lnurl pick after a spark leg drops the leg's withdrawal fee`() = test { + val lnurl = openMixedContact() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + continueWithAmount(2_000u) + assertEquals(300L, sut.sendUiState.value.lightningFeeSats) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri)))) + + continueWithAmount(6_000u) + + assertNull(sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertNull( + sut.sendUiState.value.lightningFeeSats, + "Confirm must not show the Spark withdrawal fee for the LNURL", + ) + } + @Test fun `a mixed contact lightning can pay routes direct`() = test { val lnurl = openMixedContact() From ba94a584e6b677488546a25f3b0ef058b95ddf72 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 17:09:30 +0100 Subject: [PATCH 78/90] fix: show a spark leg's address as its confirm recipient --- .../screens/wallets/send/SendConfirmScreen.kt | 9 ++- .../send/SendConfirmLnurlOnchainTest.kt | 81 ++++++++++++++----- 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index cb0a4f2dd3..648be63fc4 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -740,10 +740,11 @@ private fun LightningDetails( val isLnurlPay = uiState.lnurl is LnurlParams.LnurlPay val expirySeconds = uiState.decodedInvoice?.expirySeconds val description = uiState.decodedInvoice?.description - val destination = when (val lnurl = uiState.lnurl) { - is LnurlParams.LnurlPay -> lnurl.data.uri - else -> uiState.decodedInvoice?.bolt11.orEmpty() - } + val destination = uiState.routedPaykitRoute?.serviceLeg?.endpoint?.value + ?: when (val lnurl = uiState.lnurl) { + is LnurlParams.LnurlPay -> lnurl.data.uri + else -> uiState.decodedInvoice?.bolt11.orEmpty() + } Column( verticalArrangement = Arrangement.spacedBy(16.dp), diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt index 16c8499dac..60868664ea 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt @@ -9,6 +9,9 @@ import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.test.core.app.ApplicationProvider import com.synonym.bitkitcore.LnurlPayData +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.ServiceRouteLeg +import kotlinx.collections.immutable.persistentListOf import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -18,6 +21,7 @@ import to.bitkit.R import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.viewmodels.LnurlParams +import to.bitkit.viewmodels.PaykitRouteUi import to.bitkit.viewmodels.SendMethod import to.bitkit.viewmodels.SendUiState @@ -29,27 +33,56 @@ class SendConfirmLnurlOnchainTest { @Config(sdk = [34], qualifiers = "w411dp-h891dp") @Test fun `an onchain payment to a contact with an lnurl confirms with the onchain details`() { - val lnurl = LnurlPayData( - uri = "lnurl1mixedcontact", - callback = "https://example.com/pay", - minSendable = 5_000_000u, - maxSendable = 100_000_000u, - metadataStr = "[]", - commentAllowed = null, - allowsNostr = false, - nostrPubkey = null, + render( + SendUiState( + amount = 6_000u, + address = ADDRESS, + isAmountInputValid = true, + payMethod = SendMethod.ONCHAIN, + lnurl = LnurlParams.LnurlPay(LNURL), + ), + ) + val lnurlTitle = ApplicationProvider.getApplicationContext() + .getString(R.string.wallet__lnurl_p_title) + + composeRule.onNodeWithText(lnurlTitle).assertDoesNotExist() + composeRule.onNodeWithTag("SendConfirmToggleDetails").assertExists() + composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) + } + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `a spark leg to a contact with an lnurl confirms to the leg's onchain address`() { + val endpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = ADDRESS) + val leg = ServiceRouteLeg( + service = "spark", + endpoint = endpoint, + deliveredSat = 2_000uL, + debitSat = 2_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + render( + SendUiState( + amount = 2_000u, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + lnurl = LnurlParams.LnurlPay(LNURL), + lightningFeeSats = 300, + paykitRoute = PaykitRouteUi(persistentListOf(endpoint), offersSparkLeg = true, serviceLeg = leg), + ), ) + + composeRule.onNodeWithTag("ReviewSwapRoute").assertExists() + composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) + } + + private fun render(uiState: SendUiState) { composeRule.setContent { CompositionLocalProvider(LocalInspectionMode provides true) { AppThemeSurface { SendConfirmContent( - uiState = SendUiState( - amount = 6_000u, - address = ADDRESS, - isAmountInputValid = true, - payMethod = SendMethod.ONCHAIN, - lnurl = LnurlParams.LnurlPay(lnurl), - ), + uiState = uiState, isNodeRunning = true, isLoading = false, showBiometrics = false, @@ -59,15 +92,19 @@ class SendConfirmLnurlOnchainTest { } } } - val lnurlTitle = ApplicationProvider.getApplicationContext() - .getString(R.string.wallet__lnurl_p_title) - - composeRule.onNodeWithText(lnurlTitle).assertDoesNotExist() - composeRule.onNodeWithTag("SendConfirmToggleDetails").assertExists() - composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) } private companion object { const val ADDRESS = "bcrt1qkgfgyxyqhvkdqh04sklnzxphmcds6vft6y7h0r" + val LNURL = LnurlPayData( + uri = "lnurl1mixedcontact", + callback = "https://example.com/pay", + minSendable = 5_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) } } From 1f1a42e0fbc181f2eb70c8da872387b8e69a698c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 17:22:14 +0100 Subject: [PATCH 79/90] fix: route paykit payments with bitkit-core rc14 --- app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt | 3 +++ app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 9951b9fcab..395a6fd446 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -55,6 +55,9 @@ class PaykitRouteRepo @Inject constructor( lightningSpendableSat = lightningSpendableSats, onchainSpendableSat = onchainSpendableSats, serviceLegs = emptyList(), + // Only bitkit-core's Pubky Swaps route reads these, and the app never asks it, so no Swap comes back. + providers = emptyList(), + feeRateSatVb = 0uL, ) val network = Env.network.toCoreNetwork() // The router pays directly before it weighs any leg, so legs are quoted only when no balance pays. diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1e03b2d0ac..674859dc58 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4855,8 +4855,10 @@ class AppViewModel @Inject constructor( _sendUiState.update { it.copy(isAmountInputValid = validateAmount(it.amount)) } PaykitRouteOutcome.Leg } - is PaykitRoute.None -> { - Logger.warn("Found no Paykit route: '${picked.reason}'", context = TAG) + // The app never offers Pubky Swaps providers, so a Swap route can't come back; it pays nothing either. + is PaykitRoute.None, is PaykitRoute.Swap -> { + val reason = (picked as? PaykitRoute.None)?.reason ?: "Swap routes are unsupported" + Logger.warn("Found no Paykit route: '$reason'", context = TAG) _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } // The router's reason is English for the log: the app tells a short balance from an unusable contact. val isAmountShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() From 37276e7da4f0863c34663e8f52f4faa5bc8d3c18 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:00:37 +0100 Subject: [PATCH 80/90] fix: show tags and hide the lnurl comment on a spark leg --- .../screens/wallets/send/SendConfirmScreen.kt | 5 ++-- .../send/SendConfirmLnurlOnchainTest.kt | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 648be63fc4..e17a8d0949 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -453,7 +453,8 @@ private fun ContentRunning( onClickTag = onClickTag, onClickAddTag = onClickAddTag, ) - if ((uiState.lnurl as? LnurlParams.LnurlPay)?.data?.commentAllowed() == true) { + val lnurlPay = uiState.lnurl as? LnurlParams.LnurlPay + if (uiState.paysLnurl && lnurlPay?.data?.commentAllowed() == true) { LnurlCommentSection(uiState, onEvent) } } @@ -737,7 +738,7 @@ private fun LightningDetails( onClickAddTag: () -> Unit, modifier: Modifier = Modifier, ) { - val isLnurlPay = uiState.lnurl is LnurlParams.LnurlPay + val isLnurlPay = uiState.paysLnurl val expirySeconds = uiState.decodedInvoice?.expirySeconds val description = uiState.decodedInvoice?.description val destination = uiState.routedPaykitRoute?.serviceLeg?.endpoint?.value diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt index 60868664ea..3f24c2b268 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt @@ -77,6 +77,34 @@ class SendConfirmLnurlOnchainTest { composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) } + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `a spark leg to a contact with an lnurl shows tags and no lnurl comment`() { + val endpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = ADDRESS) + val leg = ServiceRouteLeg( + service = "spark", + endpoint = endpoint, + deliveredSat = 2_000uL, + debitSat = 2_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + render( + SendUiState( + amount = 2_000u, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + lnurl = LnurlParams.LnurlPay(LNURL.copy(commentAllowed = 100u)), + lightningFeeSats = 300, + paykitRoute = PaykitRouteUi(persistentListOf(endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + composeRule.onNodeWithTag("ReviewSwapRoute").assertExists() + composeRule.onNodeWithTag("CommentInput").assertDoesNotExist() + composeRule.onNodeWithTag("TagsAddSend").assertExists() + } + private fun render(uiState: SendUiState) { composeRule.setContent { CompositionLocalProvider(LocalInspectionMode provides true) { From 3815386d05717e9fcd14b00b8646e6af86e6a932 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:03:05 +0100 Subject: [PATCH 81/90] fix: drop the spark leg fee on a direct bolt11 pick --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 1 + .../viewmodels/AppViewModelSendFlowTest.kt | 38 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 674859dc58..fb6553f797 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4916,6 +4916,7 @@ class AppViewModel @Inject constructor( payMethod = SendMethod.LIGHTNING, decodedInvoice = route.invoice ?: it.decodedInvoice, lnurl = null, + lightningFeeSats = null, paykitRoute = route.copy(serviceLeg = null), ) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 8dc49dfe04..7a711fa200 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12627,6 +12627,44 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `a direct bolt11 pick after a spark leg drops the leg's withdrawal fee`() = test { + val bolt11 = "lnbcrt1legthenbolt11" + stubLightningScan(bolt11, amountSats = 0u) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + usdtEnabled.value = false + sut.openContactPayment( + paymentRequest = bolt11, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Bolt11, bolt11, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ), + ) + advanceUntilIdle() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + continueWithAmount(2_000u) + assertEquals(300L, sut.sendUiState.value.lightningFeeSats) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.Bolt11.rawValue, bolt11)))) + + continueWithAmount(6_000u) + + assertNull(sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals(bolt11, sut.sendUiState.value.decodedInvoice?.bolt11) + assertNull( + sut.sendUiState.value.lightningFeeSats, + "Confirm must not show the Spark withdrawal fee for the BOLT11 invoice", + ) + } + @Test fun `a mixed contact lightning can pay routes direct`() = test { val lnurl = openMixedContact() From f9ad0014956fc098f00c40025088e88ed6f9f4a5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:30:58 +0100 Subject: [PATCH 82/90] fix: confirm a spark withdrawal from the chain Spark lists a withdrawal completed once its provider accepts the payout, before the payout transaction is broadcast or mined (spark-sdk 0.28.0, crates/spark/src/ssp/graphql/models.rs:187-209 and crates/breez-sdk/core/src/models/adaptors.rs:339-347). A contact withdrawal's activity now stays unconfirmed until Electrum lists its payout output in a block. --- .../java/to/bitkit/repositories/SparkRepo.kt | 38 ++++++- .../java/to/bitkit/services/CoreService.kt | 13 +++ .../bitkit/repositories/LightningRepoTest.kt | 2 + .../to/bitkit/repositories/SparkRepoTest.kt | 98 +++++++++++++++++++ 4 files changed, 150 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 745be19d35..7dac526cc1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -45,6 +45,7 @@ import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId import to.bitkit.async.appScope import to.bitkit.data.CacheStore +import to.bitkit.data.SettingsStore import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env @@ -54,6 +55,7 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.models.SparkExitBackupV1 import to.bitkit.models.WalletScope import to.bitkit.models.safe +import to.bitkit.services.CoreService import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.utils.Logger @@ -86,6 +88,8 @@ class SparkRepo @Inject constructor( private val contactResolver: Provider, private val pendingPaymentRepo: PendingPaymentRepo, private val clock: Clock, + private val coreService: Provider, + private val settingsStore: SettingsStore, ) { companion object { private const val TAG = "SparkRepo" @@ -963,9 +967,40 @@ class SparkRepo @Inject constructor( payments .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } .forEach { recordActivity(it) } + // Off the refresh, so a slow Electrum server never holds a send that waits for it. + scope.launch { confirmMinedPayouts(payments) } markTransfers(payments) } + /** + * Spark lists a withdrawal completed once its provider took the payout on, which can be before the payout + * transaction is broadcast or mined, so a contact withdrawal's sent activity is confirmed only once the chain lists + * its payout output in a block. An output the contact already spent drops out of that list, so its activity then + * stays unconfirmed. + */ + private suspend fun confirmMinedPayouts(payments: List) { + payments.filter { it.status == PaymentStatus.COMPLETED && it.paymentType == SparkPaymentType.SEND } + .forEach { payment -> + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@forEach + val sent = (activityRepo.get().getActivity(withdraw.txId).getOrNull() as? Activity.Onchain)?.v1 + ?.takeIf { it.txType == PaymentType.SENT && !it.confirmed } ?: return@forEach + val outputs = runSuspendCatching { + coreService.get().onchain.unspentOutputs( + address = withdraw.destinationAddress, + electrumUrl = settingsStore.data.first().electrumServer, + network = Env.network, + ) + }.getOrElse { + Logger.warn("Failed to look up Spark withdrawal payout '${withdraw.txId}'", it, context = TAG) + return@forEach + } + val isMined = outputs.any { + it.txid == withdraw.txId && it.vout == withdraw.vout && it.confirmations > 0u + } + if (isMined) activityRepo.get().upsertActivity(Activity.Onchain(sent.copy(confirmed = true))) + } + } + private fun markClaimedDeposits(claimed: List) { val claimedTxids = claimed.map { it.txid.lowercase() }.toSet() _depositClaims.update { claims -> @@ -1457,7 +1492,8 @@ class SparkRepo @Inject constructor( fee = payment.fees.toLong().toULong(), address = withdraw.destinationAddress, timestamp = payment.timestamp, - confirmed = payment.status == PaymentStatus.COMPLETED, + // Spark completes a withdrawal before its payout is mined, so only the chain confirms it. + confirmed = existing?.confirmed == true, doesExist = payment.status != PaymentStatus.FAILED, contact = existing?.contact ?: journal?.contact, seenAt = existing?.seenAt, diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index c8b3b80eb1..93b58528a3 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -1,6 +1,7 @@ package to.bitkit.services import com.synonym.bitkitcore.AccountType +import com.synonym.bitkitcore.AccountUtxo import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.ActivityFilter import com.synonym.bitkitcore.ActivityTags @@ -45,6 +46,7 @@ import com.synonym.bitkitcore.getTags import com.synonym.bitkitcore.initDb import com.synonym.bitkitcore.insertActivity import com.synonym.bitkitcore.onchainBroadcastRawTx +import com.synonym.bitkitcore.onchainGetAddressInfo import com.synonym.bitkitcore.openChannel import com.synonym.bitkitcore.prepareLegacyRnNativeSegwitRecoverySweep import com.synonym.bitkitcore.refreshActiveCjitEntries @@ -2392,6 +2394,17 @@ class OnchainService { } } + /** The outputs [address] holds unspent on chain, each with its confirmations, as [electrumUrl] lists them. */ + suspend fun unspentOutputs(address: String, electrumUrl: String, network: Network?): List { + return ServiceQueue.CORE.background { + onchainGetAddressInfo( + address = address, + electrumUrl = electrumUrl, + network = network?.toCoreNetwork(), + ).utxos + } + } + suspend fun broadcastRawTx( serializedTx: String, electrumUrl: String, diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 888909b361..b29d452bcb 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1728,6 +1728,8 @@ class LightningRepoTest : BaseUnitTest() { contactResolver = { mock() }, pendingPaymentRepo = PendingPaymentRepo(), clock = Clock.System, + coreService = { coreService }, + settingsStore = settingsStore, ) sut = LightningRepo( bgDispatcher = testDispatcher, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 43ac763b96..95b570fada 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -24,6 +24,7 @@ import breez_sdk_spark.SendPaymentMethod import breez_sdk_spark.SparkHtlcDetails import breez_sdk_spark.SparkHtlcStatus import breez_sdk_spark.SyncError +import com.synonym.bitkitcore.AccountUtxo import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity @@ -38,6 +39,7 @@ import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope @@ -53,6 +55,7 @@ import org.lightningdevkit.ldknode.Event import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer @@ -67,11 +70,15 @@ 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.data.SettingsData +import to.bitkit.data.SettingsStore 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.CoreService +import to.bitkit.services.OnchainService import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest @@ -107,6 +114,9 @@ class SparkRepoTest : BaseUnitTest() { private val cacheStore = mock { on { data } doReturn cacheData } private val contactResolver = mock() private val pendingPaymentRepo = PendingPaymentRepo() + private val onchainService = mock() + private val coreService = mock { on { onchain } doReturn onchainService } + private val settingsStore = mock { on { data } doReturn flowOf(SettingsData()) } private var now = Instant.fromEpochSeconds(1_800_000_000) private val clock = object : Clock { override fun now() = this@SparkRepoTest.now @@ -120,6 +130,8 @@ class SparkRepoTest : BaseUnitTest() { contactResolver = { contactResolver }, pendingPaymentRepo = pendingPaymentRepo, clock = clock, + coreService = { coreService }, + settingsStore = settingsStore, ) @get:Rule @@ -856,6 +868,92 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a completed contact withdrawal stays unconfirmed until its payout is mined`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertFalse( + assertIs(activity.firstValue).v1.confirmed, + "Spark completes a withdrawal once its provider takes the payout on, before the payout is mined", + ) + } + + @Test + fun `a contact withdrawal is confirmed once the chain lists its payout in a block`() = test { + val sent = sentContactActivity(confirmed = false) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) }.thenReturn(Result.success(sent)) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenReturn(listOf(payoutOutput(txid = "withdrawal", confirmations = 1u))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue(activities.allValues.any { assertIs(it).v1.confirmed }) + } + + @Test + fun `a contact withdrawal whose payout is still in the mempool stays unconfirmed`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenReturn(listOf(payoutOutput(txid = "withdrawal", confirmations = 0u))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue(activities.allValues.none { assertIs(it).v1.confirmed }) + } + + @Test + fun `a confirmed contact withdrawal is not looked up on chain again`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = true))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + verify(onchainService, never()).unspentOutputs(any(), any(), anyOrNull()) + } + + private fun sentContactActivity(confirmed: Boolean) = Activity.Onchain( + OnchainActivity.create( + id = "withdrawal", + txType = ActivityPaymentType.SENT, + txId = "withdrawal", + value = 20_000uL, + fee = 300uL, + address = "bcrt1qcontact", + timestamp = 1uL, + confirmed = confirmed, + contact = "pubkycontact", + ) + ) + + private fun payoutOutput(txid: String, confirmations: UInt) = AccountUtxo( + txid = txid, + vout = 0u, + amount = 20_000uL, + blockHeight = if (confirmations > 0u) 100u else 0u, + address = "bcrt1qcontact", + path = "", + confirmations = confirmations, + coinbase = false, + own = false, + required = null, + ) + @Test fun `an accepted withdrawal stays sent after a restart whose list lacks it`() = test { journaledSpark().also { whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) } From aa09b77586a4a302b334976148fc8e6377d7e39f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:30:58 +0100 Subject: [PATCH 83/90] fix: keep a returned spark withdrawal in flight until it is recorded A sync whose payment list was read during a withdrawal's send, or before the send ended, no longer drops the journal of an aged withdrawal, so the withdrawal Spark returned is always recorded. --- .../java/to/bitkit/repositories/SparkRepo.kt | 33 +++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 46 +++++++++++++++++++ 2 files changed, 74 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 7dac526cc1..7760bbfffd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -164,10 +164,16 @@ class SparkRepo @Inject constructor( @Volatile private var hasSyncedActivities = false - /** A withdrawal's send call is running, so its journal entry must not be settled before Spark lists it. */ + /** + * A withdrawal's send call is running or its returned payment is being recorded, so its journal entry must not be + * settled before Spark lists it. + */ @Volatile private var isWithdrawing = false + /** Counts withdrawal sends that ended, so a list read before one ended never settles its journal. */ + private val withdrawalSendsEnded = AtomicLong(0) + /** A withdrawal to a contact holds the one journal slot, from before it prepares until its send call returns. */ private val isClaimingWithdrawal = AtomicBoolean(false) @@ -754,6 +760,7 @@ class SparkRepo @Inject constructor( // instead of overwriting its journal. if (!isClaimingWithdrawal.compareAndSet(false, true)) throw SparkError.WithdrawalPending() var journal: PendingSparkWithdrawal? = null + var sendReturned = false val sent = try { if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() val prepared = sparkService.prepareSend(address, amountSats) @@ -784,12 +791,13 @@ class SparkRepo @Inject constructor( clearJournal(opened) throw it } - runSuspendCatching { sparkService.send(prepared) } + runSuspendCatching { sparkService.send(prepared) }.also { sendReturned = true } } finally { - isWithdrawing = false + if (!sendReturned) endWithdrawalSend() isClaimingWithdrawal.set(false) } val payment = sent.getOrElse { + endWithdrawalSend() // Spark selects the leaves to spend before anything goes to the operators, so a short balance left // nothing and the journal closes at once, as on the Lightning rail. if (it is SdkException.InsufficientFunds) { @@ -810,7 +818,12 @@ class SparkRepo @Inject constructor( throw it } Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) - recordActivity(payment) + // The withdrawal stays in flight until it is recorded, so a sync with an older list can't drop it. + try { + recordActivity(payment) + } finally { + endWithdrawalSend() + } runSuspendCatching { refresh() }.onFailure { Logger.warn("Failed to refresh Spark after withdrawal '${payment.id}'", it, context = TAG) } @@ -1265,10 +1278,15 @@ class SparkRepo @Inject constructor( // 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() + // A list read while a withdrawal was in flight, or before one ended, may lack it, so it settles no journal. + val sendsEndedBefore = withdrawalSendsEnded.get() + val wasWithdrawing = isWithdrawing val payments = sparkService.listPayments() val isSaved = payments.map { recordActivity(it) }.all { it } releaseFailedSends(payments, recordsBefore, inFlightBefore) - if (!settleJournal || isWithdrawing) return isSaved + if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { + return isSaved + } val journal = cacheStore.data.first().pendingSparkWithdrawal ?: return isSaved // A listed withdrawal whose activity failed to save keeps its journal for the next sync to retry. if (payments.any { journal.matches(it) }) return isSaved @@ -1285,6 +1303,11 @@ class SparkRepo @Inject constructor( * Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. Returns * whether it cleared it: only then is the settlement this attempt's to announce. */ + private fun endWithdrawalSend() { + isWithdrawing = false + withdrawalSendsEnded.incrementAndGet() + } + private suspend fun clearJournal(journal: PendingSparkWithdrawal, sentTxid: String? = null): Boolean { var cleared = false cacheStore.update { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 95b570fada..06244b4d68 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -47,6 +47,7 @@ import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withTimeoutOrNull import org.junit.Before import org.junit.Rule import org.junit.Test @@ -1094,6 +1095,51 @@ class SparkRepoTest : BaseUnitTest() { assertNull(cacheData.value.pendingSparkWithdrawal) } + @Test + fun `a sync whose list was read during an aged send never drops the withdrawal it returns`() = test { + val sut = journaledSpark() + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncedAt = (now + 1.hours).epochSeconds.toULong())) + var isSending = false + var listsDuringSend = 0 + val staleListRead = CompletableDeferred() + val staleListReturns = CompletableDeferred() + var journalWhileRecording: PendingSparkWithdrawal? = null + whenever { sparkService.listPayments() }.doSuspendableAnswer { + // The Synced handler's refresh lists first, then its journal settlement reads the list it settles from. + if (isSending && ++listsDuringSend == 2) { + staleListRead.complete(Unit) + staleListReturns.await() + } + emptyList() + } + whenever { sparkService.send(any()) }.doSuspendableAnswer { + isSending = true + now += 11.minutes + backgroundScope.launch { sparkEvents.emit(SdkEvent.Synced) } + staleListRead.await() + isSending = false + contactWithdrawal() + } + whenever { activityRepo.getActivity(eq("withdrawal"), any()) }.doSuspendableAnswer { + // The stale list lands while the returned withdrawal is being recorded. + staleListReturns.complete(Unit) + withTimeoutOrNull(1.seconds) { cacheData.first { it.pendingSparkWithdrawal == null } } + journalWhileRecording = cacheData.value.pendingSparkWithdrawal + Result.success(null) + } + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + advanceUntilIdle() + + assertTrue(staleListReturns.isCompleted) + assertNotNull(journalWhileRecording, "a stale list must not drop the journal of a withdrawal being recorded") + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) + } + @Test fun `keeps an aged failed withdrawal's journal while the sync after it never reached spark`() = test { val sut = journaledSpark() From e0221f9255687ad85762f9c60ca63477fff54651 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:54:34 +0100 Subject: [PATCH 84/90] fix: match a spark withdrawal by its idempotency key --- .../java/to/bitkit/repositories/SparkRepo.kt | 19 +- .../java/to/bitkit/services/SparkService.kt | 5 +- .../bitkit/repositories/LightningRepoTest.kt | 2 +- .../to/bitkit/repositories/SparkRepoTest.kt | 187 +++++++++++------- 4 files changed, 140 insertions(+), 73 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7760bbfffd..7e62c13f90 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -61,6 +61,7 @@ import to.bitkit.services.SparkService import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import java.io.File +import java.util.UUID import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong @@ -783,6 +784,7 @@ class SparkRepo @Inject constructor( earlierTxids, tags, startedAt = clock.now().epochSeconds, + paymentId = UUID.randomUUID().toString(), ) journal = opened cacheStore.update { it.copy(pendingSparkWithdrawal = opened) } @@ -791,7 +793,7 @@ class SparkRepo @Inject constructor( clearJournal(opened) throw it } - runSuspendCatching { sparkService.send(prepared) }.also { sendReturned = true } + runSuspendCatching { sparkService.send(prepared, opened.paymentId) }.also { sendReturned = true } } finally { if (!sendReturned) endWithdrawalSend() isClaimingWithdrawal.set(false) @@ -1288,8 +1290,12 @@ class SparkRepo @Inject constructor( return isSaved } val journal = cacheStore.data.first().pendingSparkWithdrawal ?: return isSaved - // A listed withdrawal whose activity failed to save keeps its journal for the next sync to retry. - if (payments.any { journal.matches(it) }) return isSaved + // A listed withdrawal whose activity failed to save keeps its journal for the next sync to retry; one Spark + // failed before it had withdrawal details never pays out. + val isListed = payments.any { + journal.matches(it) && (it.details is PaymentDetails.Withdraw || it.status != PaymentStatus.FAILED) + } + if (isListed) return isSaved // Spark may list a withdrawal it just sent only on a later sync, so an unlisted one stays open for a while. if (clock.now().epochSeconds < journal.startedAt + UNLISTED_WITHDRAWAL_GRACE.inWholeSeconds) return isSaved Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) @@ -1593,8 +1599,15 @@ data class PendingSparkWithdrawal( val tags: List = emptyList(), /** Epoch seconds the attempt started, which keeps it open while Spark may still list it. */ val startedAt: Long = 0, + /** The idempotency key the send passed, which Spark keeps as the payment's id. */ + val paymentId: String? = null, ) { + /** + * Whether Spark lists [payment] for this attempt: by [paymentId], also while Spark lists it without withdrawal + * details, or by address and amount. + */ fun matches(payment: Payment): Boolean { + if (paymentId != null && payment.id == paymentId) return true val withdraw = payment.details as? PaymentDetails.Withdraw ?: return false return address == withdraw.destinationAddress && amountSats == payment.amount.toLong().toULong() && withdraw.txId !in earlierTxids diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index cd5a8869fe..811a6b80b6 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -234,13 +234,14 @@ class SparkService @Inject constructor( ), ) - suspend fun send(prepared: PrepareSendPaymentResponse): Payment { + /** Sends [prepared]; Spark makes one payment per [idempotencyKey], a UUID that becomes the payment's id. */ + suspend fun send(prepared: PrepareSendPaymentResponse, idempotencyKey: String? = null): 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 + return requireSdk().sendPayment(SendPaymentRequest(prepared, options, idempotencyKey)).payment } /** The fastest recommended fee rate, in sat/vB, from the SDK's own fee source. */ diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index b29d452bcb..c9c4da0f42 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1719,7 +1719,7 @@ class LightningRepoTest : BaseUnitTest() { ) whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) val sending = CompletableDeferred() - whenever(sparkService.send(any())).doSuspendableAnswer { sending.await() } + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { sending.await() } val spark = SparkRepo( bgDispatcher = testDispatcher, sparkService = sparkService, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 06244b4d68..96c1e5f73c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -233,7 +233,8 @@ class SparkRepoTest : BaseUnitTest() { 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)) + whenever { sparkService.send(any(), anyOrNull()) } + .thenReturn(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING)) val sut = createSut() sut.start(0).getOrThrow() var isRetried = false @@ -267,13 +268,13 @@ class SparkRepoTest : BaseUnitTest() { 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)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) createSut().payInvoice("lnbc1280n1send", 128uL).getOrThrow() inOrder(cacheStore, sparkService) { verifyBlocking(cacheStore) { addSparkSendHash(eq("hash"), anyOrNull()) } - verifyBlocking(sparkService) { send(any()) } + verifyBlocking(sparkService) { send(any(), anyOrNull()) } } } @@ -387,7 +388,7 @@ class SparkRepoTest : BaseUnitTest() { } val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(retry) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(retry) val sut = createSut(store) val starting = async { sut.start(0) } runCurrent() @@ -410,7 +411,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() retry } @@ -446,7 +447,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) } @@ -515,7 +516,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) } @@ -538,7 +539,7 @@ class SparkRepoTest : BaseUnitTest() { 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") } + whenever { sparkService.send(any(), anyOrNull()) }.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() @@ -751,7 +752,7 @@ class SparkRepoTest : BaseUnitTest() { method = PaymentMethod.WITHDRAW, details = PaymentDetails.Withdraw("withdrawal", 0u, ADDRESS), ) - whenever { sparkService.send(any()) }.thenReturn(sent) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sent) val sut = createSut() assertFalse(sut.markWithdrawalAsTransfer("withdrawal")) @@ -855,7 +856,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `records a withdrawal to a contact with its contact and fee`() = test { val sut = journaledSpark() - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) assertEquals("withdrawal", sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow()) @@ -872,7 +873,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a completed contact withdrawal stays unconfirmed until its payout is mined`() = test { val sut = journaledSpark() - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() @@ -957,7 +958,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `an accepted withdrawal stays sent after a restart whose list lacks it`() = test { - journaledSpark().also { whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) } + journaledSpark().also { whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) } .withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() assertNull(cacheData.value.pendingSparkWithdrawal) // After a restart before the request's proof completed, Spark's list lacks the withdrawal. @@ -989,7 +990,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a cached withdrawal never settles a retry after a restart whose list lacks it`() = test { - journaledSpark().also { whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) } + journaledSpark().also { whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) } .withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() whenever { sparkService.listPayments() }.thenReturn(emptyList()) val restarted = createSut().also { it.start(0).getOrThrow() } @@ -1008,7 +1009,7 @@ class SparkRepoTest : BaseUnitTest() { cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } assertIs(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1074,7 +1075,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `keeps an unlisted withdrawal open until its grace period passes`() = test { val sut = journaledSpark() - whenever(sparkService.send(any())).doSuspendableAnswer { throw SdkException.Generic("timeout") } + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw SdkException.Generic("timeout") } assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) @@ -1113,7 +1114,7 @@ class SparkRepoTest : BaseUnitTest() { } emptyList() } - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { isSending = true now += 11.minutes backgroundScope.launch { sparkEvents.emit(SdkEvent.Synced) } @@ -1140,10 +1141,59 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) } + @Test + fun `keeps an aged failed withdrawal's journal while spark lists its payment without withdrawal details`() = test { + val sut = journaledSpark() + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncedAt = (now + 1.hours).epochSeconds.toULong())) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + val paymentId = cacheData.value.pendingSparkWithdrawal?.paymentId + // Spark lists the committed withdrawal before its provider request maps it to withdrawal details. + whenever { sparkService.listPayments() }.thenReturn( + listOf( + contactWithdrawal().copy(id = paymentId.toString(), status = PaymentStatus.PENDING, details = null) + ) + ) + now += 11.minutes + throw SdkException.Generic("timeout") + } + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "a withdrawal Spark lists without its details may still pay out, so its journal stays open", + ) + } + + @Test + fun `drops an aged failed withdrawal's journal once spark fails its payment without withdrawal details`() = test { + val sut = journaledSpark() + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncedAt = (now + 1.hours).epochSeconds.toULong())) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + val paymentId = cacheData.value.pendingSparkWithdrawal?.paymentId + whenever { sparkService.listPayments() }.thenReturn( + listOf( + contactWithdrawal().copy(id = paymentId.toString(), status = PaymentStatus.FAILED, details = null) + ) + ) + now += 11.minutes + throw SdkException.Generic("timeout") + } + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertNull( + cacheData.value.pendingSparkWithdrawal, + "a withdrawal Spark failed before it had withdrawal details never pays out, so its journal closes", + ) + } + @Test fun `keeps an aged failed withdrawal's journal while the sync after it never reached spark`() = test { val sut = journaledSpark() - whenever(sparkService.send(any())).doSuspendableAnswer { + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { now += 11.minutes throw SdkException.Generic("timeout") } @@ -1353,7 +1403,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { false }) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) assertNull(cacheData.value.pendingSparkWithdrawal) } @@ -1374,7 +1424,7 @@ class SparkRepoTest : BaseUnitTest() { ) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) assertNull(cacheData.value.pendingSparkWithdrawal) } @@ -1385,12 +1435,12 @@ class SparkRepoTest : BaseUnitTest() { cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) if (cacheData.value.pendingSparkWithdrawal != null) now += 2.minutes } - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, paymentDeadlineAt = now + 1.minutes) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) assertNull(cacheData.value.pendingSparkWithdrawal) } @@ -1412,7 +1462,7 @@ class SparkRepoTest : BaseUnitTest() { fun `a withdrawal spark returns as failed is not reported as sent`() = test { val sut = journaledSpark() val failed = contactWithdrawal().copy(status = PaymentStatus.FAILED) - whenever(sparkService.send(any())).thenReturn(failed) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(failed)) val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") @@ -1431,7 +1481,7 @@ class SparkRepoTest : BaseUnitTest() { fun `a pending withdrawal stays open until spark completes it`() = test { val sut = journaledSpark() val pending = contactWithdrawal().copy(status = PaymentStatus.PENDING) - whenever(sparkService.send(any())).thenReturn(pending) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(pending) whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(pending)) val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") @@ -1454,7 +1504,7 @@ class SparkRepoTest : BaseUnitTest() { fun `a pending withdrawal spark later fails closes as unsent`() = test { val sut = journaledSpark() val pending = contactWithdrawal().copy(status = PaymentStatus.PENDING) - whenever(sparkService.send(any())).thenReturn(pending) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(pending) whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(pending)) sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") @@ -1468,7 +1518,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a withdrawal spark refuses for its balance closes its journal at once`() = test { val sut = journaledSpark() - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } clearInvocations(sparkService) val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") @@ -1482,7 +1532,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a withdrawal spark refuses for a fee that rose past its quote closes its journal at once`() = test { val sut = journaledSpark() - whenever { sparkService.send(any()) }.thenAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.InvalidInput( "The onchain fee rose to 900 sats at the slowest speed, above the 500 sats quoted for this payment. " + "Please re-prepare the payment.", @@ -1544,7 +1594,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, maxDebitSats = 20_499uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) assertNull(cacheData.value.pendingSparkWithdrawal) } @@ -1552,7 +1602,7 @@ class SparkRepoTest : BaseUnitTest() { fun `keeps the journal when the withdrawal's activity fails to save`() = test { val sut = journaledSpark() whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(AppError("disk full"))) - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() @@ -1564,7 +1614,7 @@ class SparkRepoTest : BaseUnitTest() { val sut = journaledSpark() whenever { activityRepo.addTagsToActivity(any(), any(), any()) } .thenReturn(Result.failure(AppError("disk full"))) - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact", tags = listOf("rent")).getOrThrow() @@ -1577,7 +1627,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(ActivityDeletedError("withdrawal"))) whenever { activityRepo.addTagsToActivity(any(), any(), any()) } .thenReturn(Result.failure(AppError("not found"))) - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact", tags = listOf("rent")).getOrThrow() @@ -1651,7 +1701,7 @@ class SparkRepoTest : BaseUnitTest() { prepareGate.await() prepared } - whenever { sparkService.send(any()) }.thenReturn(contactWithdrawal()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) val first = async { sut.withdraw("bcrt1qcontact", 20_000uL, "first") } runCurrent() @@ -1661,14 +1711,14 @@ class SparkRepoTest : BaseUnitTest() { assertIs(second.await().exceptionOrNull()) assertEquals("withdrawal", first.await().getOrThrow()) - verify(sparkService, times(1)).send(any()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test fun `a foreground during an in-flight withdrawal keeps its journal until spark lists it`() = test { val sut = journaledSpark() val sendGate = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sendGate.await() contactWithdrawal() } @@ -1965,7 +2015,8 @@ class SparkRepoTest : BaseUnitTest() { 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") } + whenever { sparkService.send(any(), anyOrNull()) } + .thenAnswer { throw SdkException.Generic("operators unreachable") } val sut = createSut() sut.refreshState().getOrThrow() @@ -1983,7 +2034,8 @@ class SparkRepoTest : BaseUnitTest() { 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") } + whenever { sparkService.send(any(), anyOrNull()) } + .thenAnswer { throw SdkException.Generic("operators unreachable") } val sut = createSut() sut.refreshState().getOrThrow() assertTrue(sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isFailure) @@ -2036,7 +2088,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 500)) whenever { sparkService.listPayments() }.thenAnswer { throw SdkException.Generic("offline") } assertTrue(createSut().withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isSuccess) @@ -2125,7 +2177,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { throw noRoute } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2142,7 +2194,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, onBeforeSend = { !cancelled }) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2156,7 +2208,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw expired } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw expired } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } @@ -2165,7 +2217,8 @@ class SparkRepoTest : BaseUnitTest() { 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") } + whenever { sparkService.send(any(), anyOrNull()) } + .thenAnswer { throw SdkException.InvalidInput("Invoice has expired") } val sut = createSut() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) @@ -2178,7 +2231,7 @@ class SparkRepoTest : BaseUnitTest() { 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) } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } val sut = createSut() val error = sut.payInvoice("lnbc1", 100uL).exceptionOrNull() @@ -2195,9 +2248,9 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut() assertIs(sut.payInvoice("lnbc1", 100uL, maxTotalFeeMsat = 1_999uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 2)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 2)) assertEquals("hash", sut.payInvoice("lnbc1", 100uL, maxTotalFeeMsat = 2_000uL).getOrThrow()) } @@ -2207,7 +2260,7 @@ class SparkRepoTest : BaseUnitTest() { 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)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut() assertEquals(500uL, sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow()) @@ -2246,7 +2299,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = now - 1.minutes) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2254,7 +2307,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) val sut = createSut() @@ -2295,7 +2348,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { sending.await() } + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() } val sut = createSut() val first = async { sut.payInvoice("lnbc1", 100uL) } @@ -2305,7 +2358,7 @@ class SparkRepoTest : BaseUnitTest() { assertIs(second.exceptionOrNull()) assertEquals("hash", first.await().getOrThrow()) - verify(sparkService, times(1)).send(any()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test @@ -2323,7 +2376,7 @@ class SparkRepoTest : BaseUnitTest() { .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING))) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2340,7 +2393,7 @@ class SparkRepoTest : BaseUnitTest() { 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()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2419,7 +2472,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.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) @@ -2486,7 +2539,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.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. @@ -2503,7 +2556,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() whenever { sparkService.syncWallet() }.thenAnswer { throw SdkException.Generic("operators unreachable") } @@ -2513,7 +2566,7 @@ class SparkRepoTest : BaseUnitTest() { 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()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test @@ -2523,7 +2576,7 @@ class SparkRepoTest : BaseUnitTest() { 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") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) @@ -2531,7 +2584,7 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - verify(sparkService, times(1)).send(any()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test @@ -2546,14 +2599,14 @@ 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.send(any(), anyOrNull()) }.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()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2588,7 +2641,7 @@ class SparkRepoTest : BaseUnitTest() { 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)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds val sut = createSut() @@ -2599,7 +2652,7 @@ class SparkRepoTest : BaseUnitTest() { } assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -2608,7 +2661,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() @@ -2643,7 +2696,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.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))) @@ -2674,7 +2727,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) val before = createSut(store) @@ -2702,7 +2755,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = unexpiredPrepared() whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) val sut = createSut(store) @@ -2758,7 +2811,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) ) @@ -2786,7 +2839,7 @@ class SparkRepoTest : BaseUnitTest() { 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.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() whenever { sparkService.getInfo() }.thenReturn( @@ -2816,7 +2869,7 @@ class SparkRepoTest : BaseUnitTest() { 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") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() From b7c748f7334ae6b4c14ce6bb3ade1d9f9f9bef1f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 01:22:49 +0100 Subject: [PATCH 85/90] test: stub spark sends with their idempotency key Master's restore tests stubbed SparkService.send with one matcher, and this branch gives send an idempotency key, so Mockito refused the stubs once both met. --- .../to/bitkit/repositories/SparkRepoTest.kt | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 891d325a6a..ee2d976372 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -272,7 +272,7 @@ class SparkRepoTest : BaseUnitTest() { val expirySecs = 30 * 24 * 60 * 60L val prepared = prepared(feeSats = 0uL, createdAt = createdAt.toULong(), expirySecs = expirySecs.toULong()) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() @@ -281,7 +281,7 @@ class SparkRepoTest : BaseUnitTest() { sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, createdAt + expirySecs) } assertIs(sut.payInvoice("lnbc1280n1send", 128uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -336,13 +336,13 @@ class SparkRepoTest : BaseUnitTest() { 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()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val restarted = createSut(store) restarted.start(0).getOrThrow() restarted.payInvoice("lnbc1280n1send", 128uL) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -352,14 +352,14 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() val result = sut.payInvoice("lnbc1280n1send", 128uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -371,7 +371,7 @@ class SparkRepoTest : BaseUnitTest() { // Spark reports Synced while its payment-history sync failed, so its list lacks the pre-restore send. val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() assertNull(store.data.first().sparkHistoryUnseededSince) @@ -379,7 +379,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1280n1send", 128uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -390,7 +390,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() assertNull(store.data.first().sparkHistoryUnseededSince) @@ -399,7 +399,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1280n1send", 128uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -410,13 +410,13 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL, createdAt = now.epochSeconds.toULong(), expirySecs = 3_600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow() - verify(sparkService).send(any()) + verify(sparkService).send(any(), anyOrNull()) } @Test @@ -2288,7 +2288,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenAnswer { read } whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { read = staleZero sentPayment(fees = 500) } @@ -2316,7 +2316,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenAnswer { read } whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { read = staleZero sentPayment(fees = 500) } @@ -2971,7 +2971,7 @@ class SparkRepoTest : BaseUnitTest() { 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)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { now = deadline + 1.seconds @@ -2982,7 +2982,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, deadline, null) { true } assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) verifyBlocking(cacheStore) { removeSparkUncertainSend("hash") } verifyBlocking(cacheStore) { removeSparkSendHash("hash") } } From 8cb1a6dbe8cdcdb6b87cc811207e8248683b95c7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 08:42:25 +0100 Subject: [PATCH 86/90] fix: confirm a spark payout the contact already spent --- .../java/to/bitkit/data/SparkPayoutChain.kt | 54 +++++++++++++++++++ .../java/to/bitkit/repositories/SparkRepo.kt | 13 ++--- .../to/bitkit/repositories/SparkRepoTest.kt | 37 +++++++++++++ 3 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 app/src/main/java/to/bitkit/data/SparkPayoutChain.kt diff --git a/app/src/main/java/to/bitkit/data/SparkPayoutChain.kt b/app/src/main/java/to/bitkit/data/SparkPayoutChain.kt new file mode 100644 index 0000000000..eb0a2b55c3 --- /dev/null +++ b/app/src/main/java/to/bitkit/data/SparkPayoutChain.kt @@ -0,0 +1,54 @@ +package to.bitkit.data + +import io.ktor.client.HttpClient +import io.ktor.client.request.get +import io.ktor.client.statement.bodyAsText +import io.ktor.http.HttpStatusCode +import io.ktor.http.isSuccess +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.lightningdevkit.ldknode.Network +import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching +import to.bitkit.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Whether a Spark withdrawal's payout transaction is mined, asked of the Esplora chain Spark reads. Unlike the payout + * address's unspent outputs, the transaction's status still answers once the contact has spent the payout. + */ +@Singleton +class SparkPayoutChain @Inject constructor( + private val client: HttpClient, +) { + companion object { + private const val TAG = "SparkPayoutChain" + private const val SPARK_REGTEST_ESPLORA_URL = "https://regtest-mempool.us-west-2.sparkinfra.net/api" + private val json = Json { ignoreUnknownKeys = true } + + /** The Esplora to ask on [network]: the one Spark reads there, or null where the app knows none. */ + fun esploraUrl(network: Network): String? = when (network) { + Network.BITCOIN -> Env.bitkitEsploraUrl + Network.REGTEST -> SPARK_REGTEST_ESPLORA_URL + else -> null + } + } + + /** Whether [txid] is in a block; null when this network has no Esplora to ask or the lookup failed. */ + suspend fun isMined(txid: String): Boolean? { + val baseUrl = esploraUrl(Env.network) ?: return null + return runSuspendCatching { + val response = client.get("$baseUrl/tx/$txid/status") + // Spark can list a payout before it is broadcast, and the chain then knows no such transaction yet. + if (response.status == HttpStatusCode.NotFound) return@runSuspendCatching false + check(response.status.isSuccess()) { "status ${response.status.value}" } + json.parseToJsonElement(response.bodyAsText()).jsonObject.getValue("confirmed").jsonPrimitive.boolean + }.getOrElse { + Logger.warn("Failed to look up Spark payout transaction '$txid'", it, context = TAG) + null + } + } +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6a639acaf3..b2e341d776 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -46,6 +46,7 @@ import org.lightningdevkit.ldknode.PaymentId import to.bitkit.async.appScope import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkPayoutChain import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env @@ -91,6 +92,7 @@ class SparkRepo @Inject constructor( private val clock: Clock, private val coreService: Provider, private val settingsStore: SettingsStore, + private val payoutChain: SparkPayoutChain, ) { companion object { private const val TAG = "SparkRepo" @@ -1013,9 +1015,9 @@ class SparkRepo @Inject constructor( /** * Spark lists a withdrawal completed once its provider took the payout on, which can be before the payout - * transaction is broadcast or mined, so a contact withdrawal's sent activity is confirmed only once the chain lists - * its payout output in a block. An output the contact already spent drops out of that list, so its activity then - * stays unconfirmed. + * transaction is broadcast or mined, so a contact withdrawal's sent activity is confirmed only once its payout is + * in a block. The payout address's unspent outputs show that first; an output missing there, such as one the + * contact spent before Bitkit saw it mined, is looked up by its transaction instead. */ private suspend fun confirmMinedPayouts(payments: List) { payments.filter { it.status == PaymentStatus.COMPLETED && it.paymentType == SparkPaymentType.SEND } @@ -1033,9 +1035,8 @@ class SparkRepo @Inject constructor( Logger.warn("Failed to look up Spark withdrawal payout '${withdraw.txId}'", it, context = TAG) return@forEach } - val isMined = outputs.any { - it.txid == withdraw.txId && it.vout == withdraw.vout && it.confirmations > 0u - } + val payout = outputs.firstOrNull { it.txid == withdraw.txId && it.vout == withdraw.vout } + val isMined = payout?.let { it.confirmations > 0u } ?: (payoutChain.isMined(withdraw.txId) == true) if (isMined) activityRepo.get().upsertActivity(Activity.Onchain(sent.copy(confirmed = true))) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index ee2d976372..00d5a1ddba 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -73,6 +73,7 @@ import to.bitkit.data.CacheStore import to.bitkit.data.MAX_SPARK_SEND_HASHES import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkPayoutChain import to.bitkit.env.Env import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId @@ -118,6 +119,7 @@ class SparkRepoTest : BaseUnitTest() { private val pendingPaymentRepo = PendingPaymentRepo() private val onchainService = mock() private val coreService = mock { on { onchain } doReturn onchainService } + private val payoutChain = mock() private val settingsStore = mock { on { data } doReturn flowOf(SettingsData()) } private var now = Instant.fromEpochSeconds(1_800_000_000) private val clock = object : Clock { @@ -134,6 +136,7 @@ class SparkRepoTest : BaseUnitTest() { clock = clock, coreService = { coreService }, settingsStore = settingsStore, + payoutChain = payoutChain, ) @get:Rule @@ -1169,6 +1172,39 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(activities.allValues.none { assertIs(it).v1.confirmed }) } + @Test + fun `a contact withdrawal is confirmed from its transaction once the contact spent the payout`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) }.thenReturn(emptyList()) + whenever { payoutChain.isMined("withdrawal") }.thenReturn(true) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue( + activities.allValues.any { assertIs(it).v1.confirmed }, + "A payout spent before Bitkit saw it mined no longer lists as unspent, so its transaction is asked", + ) + } + + @Test + fun `a payout listed unspent in the mempool is not asked about by its transaction`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenReturn(listOf(payoutOutput(txid = "withdrawal", confirmations = 0u))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + verify(payoutChain, never()).isMined(any()) + } + @Test fun `a confirmed contact withdrawal is not looked up on chain again`() = test { whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) @@ -1179,6 +1215,7 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() verify(onchainService, never()).unspentOutputs(any(), any(), anyOrNull()) + verify(payoutChain, never()).isMined(any()) } private fun sentContactActivity(confirmed: Boolean) = Activity.Onchain( From 82ef38a526eb89833a3719a06c7c616d4f2a4345 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 08:42:26 +0100 Subject: [PATCH 87/90] docs: move the spark withdrawal journal kdoc onto clearJournal --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b2e341d776..709dfc1e7a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1415,15 +1415,15 @@ class SparkRepo @Inject constructor( return isSaved } - /** - * Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. Returns - * whether it cleared it: only then is the settlement this attempt's to announce. - */ private fun endWithdrawalSend() { isWithdrawing = false withdrawalSendsEnded.incrementAndGet() } + /** + * Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. Returns + * whether it cleared it: only then is the settlement this attempt's to announce. + */ private suspend fun clearJournal(journal: PendingSparkWithdrawal, sentTxid: String? = null): Boolean { var cleared = false cacheStore.update { From 3ab29cd7fb6b8632d4ea3fccd4969b1ea96bcda1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 08:57:42 +0100 Subject: [PATCH 88/90] test: pass the payout chain to the spark repo in lightning repo tests --- app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 9639aab01e..92527d1807 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1791,6 +1791,7 @@ class LightningRepoTest : BaseUnitTest() { clock = Clock.System, coreService = { coreService }, settingsStore = settingsStore, + payoutChain = mock(), ) sut = LightningRepo( bgDispatcher = testDispatcher, From 2511a609c580179057ca5eb51fa7faebe93b2f6a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 09:29:55 +0100 Subject: [PATCH 89/90] fix: show a spark leg's fee on request confirm --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 36 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index fb6553f797..1c93230e4b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7940,6 +7940,8 @@ class AppViewModel @Inject constructor( val generation = sendStateGeneration val currentState = _sendUiState.value if (currentState.payMethod != SendMethod.LIGHTNING) return + // A Spark leg pays the contact's other endpoint, so its fee is the leg's, never the retained invoice's. + if (currentState.routedPaykitRoute?.serviceLeg != null) return val decodedInvoice = currentState.decodedInvoice ?: return val feeResult = if (decodedInvoice.amountSatoshis > 0uL) { @@ -7951,7 +7953,7 @@ class AppViewModel @Inject constructor( requireCurrentPaymentPreparation(walletGeneration) feeResult.onSuccess { fee -> _sendUiState.update { - if (generation != sendStateGeneration) return@update it + if (generation != sendStateGeneration || it.routedPaykitRoute?.serviceLeg != null) return@update it it.copy( lightningFeeSats = fee.toLong(), lastLightningFee = fee.toLong(), diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 7a711fa200..0fa434ff19 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12711,6 +12711,42 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return lnurl } + @Test + fun `a request paid by a spark leg keeps the leg's fee over the invoice's estimate`() = test { + val bolt11 = "lnbcrt1requestspark" + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + val endpoints = listOf( + Endpoint(MethodId.Bolt11, bolt11, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 2_000uL), + acceptedPaymentEndpointIdentifiers = endpoints.map { it.methodId.rawValue }, + ) + stubLightningScan(bolt11, amountSats = 2_000u) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(lightningRepo.estimateRoutingFees(any())).thenReturn(Result.success(7uL)) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + usdtEnabled.value = false + + sut.openContactPayment(bolt11, testPublicKey, incomingPaymentRequest = request, endpoints = endpoints) + advanceUntilIdle() + + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals( + 300L, + sut.sendUiState.value.lightningFeeSats, + "Confirm shows the withdrawal's fee, not the fee of the invoice the leg doesn't pay", + ) + } + @Test fun `a request above a routed lnurl's maximum does not open a swipeable confirm`() = test { val lnurl = LnurlPayData( From b5fa1530014eee805b1b5bcafe27d990ff640f4c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 10:53:07 +0100 Subject: [PATCH 90/90] fix: confirm a spark payout when electrum fails, keeping its seen time --- .../java/to/bitkit/repositories/SparkRepo.kt | 20 ++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 43 +++++++++++++++++++ 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 709dfc1e7a..46469b49cd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1023,24 +1023,30 @@ class SparkRepo @Inject constructor( payments.filter { it.status == PaymentStatus.COMPLETED && it.paymentType == SparkPaymentType.SEND } .forEach { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@forEach - val sent = (activityRepo.get().getActivity(withdraw.txId).getOrNull() as? Activity.Onchain)?.v1 - ?.takeIf { it.txType == PaymentType.SENT && !it.confirmed } ?: return@forEach + unconfirmedSent(withdraw.txId) ?: return@forEach val outputs = runSuspendCatching { coreService.get().onchain.unspentOutputs( address = withdraw.destinationAddress, electrumUrl = settingsStore.data.first().electrumServer, network = Env.network, ) - }.getOrElse { + }.onFailure { Logger.warn("Failed to look up Spark withdrawal payout '${withdraw.txId}'", it, context = TAG) - return@forEach - } - val payout = outputs.firstOrNull { it.txid == withdraw.txId && it.vout == withdraw.vout } + }.getOrNull() + // A failed Electrum lookup falls through to the transaction's status, as a missing output does. + val payout = outputs?.firstOrNull { it.txid == withdraw.txId && it.vout == withdraw.vout } val isMined = payout?.let { it.confirmations > 0u } ?: (payoutChain.isMined(withdraw.txId) == true) - if (isMined) activityRepo.get().upsertActivity(Activity.Onchain(sent.copy(confirmed = true))) + if (!isMined) return@forEach + // Read again after the lookups, so a seen time written meanwhile isn't written back over. + val latest = unconfirmedSent(withdraw.txId) ?: return@forEach + activityRepo.get().upsertActivity(Activity.Onchain(latest.copy(confirmed = true))) } } + private suspend fun unconfirmedSent(txid: String) = + (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1 + ?.takeIf { it.txType == PaymentType.SENT && !it.confirmed } + private fun markClaimedDeposits(claimed: List) { val claimedTxids = claimed.map { it.txid.lowercase() }.toSet() _depositClaims.update { claims -> diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 00d5a1ddba..4f951f028a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1218,6 +1218,49 @@ class SparkRepoTest : BaseUnitTest() { verify(payoutChain, never()).isMined(any()) } + @Test + fun `a contact withdrawal is confirmed from its transaction when electrum fails`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenAnswer { throw IllegalStateException("electrum down") } + whenever { payoutChain.isMined("withdrawal") }.thenReturn(true) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue( + activities.allValues.any { assertIs(it).v1.confirmed }, + "An Electrum failure should fall back to the Esplora lookup of the payout transaction", + ) + } + + @Test + fun `confirming a mined payout keeps a seen time written during the chain lookup`() = test { + val unseen = sentContactActivity(confirmed = false) + val seen = Activity.Onchain(unseen.v1.copy(seenAt = 42uL)) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + var stored: Activity = unseen + // A Result answer is unboxed, so the stub answers with the activity itself. + whenever { activityRepo.getActivity(eq("withdrawal"), any()) }.thenAnswer { stored } + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) }.thenAnswer { + // The user opens the activity list while the Electrum lookup is in flight. + stored = seen + listOf(payoutOutput(txid = "withdrawal", confirmations = 1u)) + } + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + val confirmed = activities.allValues.map { assertIs(it).v1 }.single { it.confirmed } + assertEquals(42uL, confirmed.seenAt, "The confirm upsert reverted a seen time written during its lookup") + } + private fun sentContactActivity(confirmed: Boolean) = Activity.Onchain( OnchainActivity.create( id = "withdrawal",