From 8bb27fd31822a49c939d0f63dc4c91a817e21399 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 29 Oct 2026 22:51:26 +0100 Subject: [PATCH 01/24] feat: pay contacts through pubky swaps --- app/build.gradle.kts | 4 + app/src/main/java/to/bitkit/env/Env.kt | 11 ++ .../repositories/PubkySwapsRouteRepo.kt | 109 ++++++++++++++ .../screens/wallets/send/SendConfirmScreen.kt | 17 +++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 137 +++++++++++++++++- 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 | 2 + .../viewmodels/AppViewModelSendFlowTest.kt | 3 + journeys/paykit-swap-route.xml | 29 ++++ 23 files changed, 324 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt create mode 100644 journeys/paykit-swap-route.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6198983ef9..b3f1b5128c 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") @@ -362,6 +364,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 83a1ed564f..8555ab0d36 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -54,6 +54,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..35532eb050 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -0,0 +1,109 @@ +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.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, +) { + 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 + 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, + ), + network = Env.network.toCoreNetwork(), + mnemonic = mnemonic, + bip39Passphrase = passphrase, + ) + } + + 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 be4d81f02d..be3776bf1c 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 @@ -58,6 +58,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 @@ -107,6 +108,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 @@ -873,6 +877,19 @@ private fun LightningDetails( } } + uiState.paykitSwapRoute?.let { route -> + val quote = route.quote ?: return@let + val provider = route.providerName?.takeIf { it.isNotBlank() } + ?: quote.providerPubky.ellipsisMiddle(PROVIDER_KEY_LENGTH) + SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { + BodySSB( + text = stringResource(R.string.wallet__send_swap_route_provider, provider), + 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 ebbc027624..1584c31d62 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -27,7 +27,10 @@ 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.SortDirection import com.synonym.bitkitcore.UsdtQuote @@ -214,6 +217,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 @@ -316,6 +320,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, @@ -3931,14 +3936,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) @@ -4071,6 +4082,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 @@ -4460,6 +4487,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 { @@ -4474,6 +4505,46 @@ 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 + } + // 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, + 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 @@ -4749,7 +4820,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 } @@ -4875,6 +4949,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 } || @@ -6108,6 +6189,11 @@ class AppViewModel @Inject constructor( return } + _sendUiState.value.paykitSwapRoute?.quote?.let { + proceedWithSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId) + return + } + when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> proceedWithOnchainPayment( incomingPaymentRequest, @@ -6482,6 +6568,42 @@ 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?, @@ -8860,6 +8982,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 @@ -8888,6 +9011,14 @@ data class SendUiState( !initialSubscriptionPaymentNeedsConfirmation && !requiresAmountReview } +/** A Paykit payment routed through a Pubky Swaps provider: the endpoint, the route once quoted, and its provider. */ +@Stable +data class PaykitSwapRouteUi( + val endpoint: PaykitEndpoint, + val quote: PubkySwapRouteQuote? = null, + val providerName: String? = 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 045e83ac9b..5476d05814 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -977,6 +977,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 2e3d9b1f9f..5206274597 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1010,6 +1010,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 24dcb34d0a..d0a82d88f7 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1003,6 +1003,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 f0336264d1..ecd167d9ce 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1008,6 +1008,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 2a45ff0fe4..a82ddaa7fe 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -858,6 +858,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 8587ae5710..0150d22b5e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -982,6 +982,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 9d926c39bd..d9926bc422 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1003,6 +1003,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 940f3de425..fcb9036536 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -850,6 +850,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 61cd95d307..7bd8397d2a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -859,6 +859,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 2141ffc645..5aaed439be 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1006,6 +1006,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 0f16a7c531..878838f574 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1001,6 +1001,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 d1a5a29132..bdaaa87833 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -861,6 +861,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 0266a4b1e4..923a807517 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1010,6 +1010,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 c9f113920f..0e397be809 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -722,6 +722,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 cd61bf299f..796d825d09 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1026,6 +1026,7 @@ <accent>счёта...</accent> Подтвердить Биткоины отправлены + Маршрут Отправить Кому Да, Отправить diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e0f1418c67..9869929640 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1564,6 +1564,8 @@ Paying\n<accent>invoice...</accent> Confirm Bitcoin Sent + Route + Pubky Swaps · %1$s Swipe To Pay To Yes, Send diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 59d48a26ac..d34cd30575 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -196,6 +196,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 @@ -296,6 +297,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() @@ -943,6 +945,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/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml new file mode 100644 index 0000000000..bb03778896 --- /dev/null +++ b/journeys/paykit-swap-route.xml @@ -0,0 +1,29 @@ + + + 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 the provider's pubky saved as a contact. + 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 Enter Manually (tag "RecipientManual") + Type the fixture-issuer's pubky (from bitkit-docker's fixture-issuer /health) and tap Continue (tag "AddressContinue") + Verify the Add Contact screen is visible and tap Pay (tag "AddContactPay") + 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 46ad2a981b67f456339962b8a22dd7d9c5adb775 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 29 Oct 2026 22:52:04 +0100 Subject: [PATCH 02/24] chore: add changelog fragment --- changelog.d/next/1732.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1732.added.md 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. From 0336ee0374d8d167f27ec34a169400e26df9db5b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 02:19:18 +0100 Subject: [PATCH 03/24] docs: pay the journey's contact from the contact list --- journeys/paykit-swap-route.xml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml index bb03778896..5de3d268fa 100644 --- a/journeys/paykit-swap-route.xml +++ b/journeys/paykit-swap-route.xml @@ -9,14 +9,13 @@ 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 the provider's pubky saved as a contact. + 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 Enter Manually (tag "RecipientManual") - Type the fixture-issuer's pubky (from bitkit-docker's fixture-issuer /health) and tap Continue (tag "AddressContinue") - Verify the Add Contact screen is visible and tap Pay (tag "AddContactPay") + 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") From 9bb81f86eaa6160e027c0f54b8b6565de8002bcb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 04:14:49 +0100 Subject: [PATCH 04/24] chore: use bitkit-core 0.8.0-swaps.1 --- 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 9767d1a465..5569065ecb 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.1" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } From 97749ce626baaeb13a7ed546fbd40d3bdd84b2ca Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 13:33:24 +0100 Subject: [PATCH 05/24] chore: move to bitkit-core 0.8.0-swaps.3 --- .../main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt | 3 +++ app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt | 6 ++++++ gradle/libs.versions.toml | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 35532eb050..b808c2e701 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -5,6 +5,7 @@ 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 @@ -57,6 +58,7 @@ class PubkySwapsRouteRepo @Inject constructor( endpoints: List, lightningSpendableSats: ULong, onchainSpendableSats: ULong, + serviceLegs: List = emptyList(), ): 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 @@ -69,6 +71,7 @@ class PubkySwapsRouteRepo @Inject constructor( onchainSpendableSat = onchainSpendableSats, providers = candidates, feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, + serviceLegs = serviceLegs, ), network = Env.network.toCoreNetwork(), mnemonic = mnemonic, diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1584c31d62..2c3785fd6f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4526,6 +4526,12 @@ class AppViewModel @Inject constructor( toast(AppError(paykitRoute.reason)) return false } + // No service legs are passed in yet, so the router cannot pick one. + is PaykitRoute.Service -> { + Logger.error("Unexpected service route '${paykitRoute.leg.service}'", context = TAG) + toast(AppError(context.getString(R.string.common__error_body))) + return false + } // Balances changed after the contact opened: the regular flow must reopen it. is PaykitRoute.Direct -> { _sendUiState.update { it.copy(paykitSwapRoute = null) } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5569065ecb..af2fd39c6c 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-swaps.1" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-swaps.3" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } From f6f8ad3bebc81c262fb5c9d14aca441165b86054 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 21:10:18 +0100 Subject: [PATCH 06/24] feat: return swap routes to savings after a wallet restore --- .../repositories/PubkySwapsRouteRepo.kt | 25 ++++++++++- .../to/bitkit/viewmodels/WalletViewModel.kt | 29 +++++++++++++ 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 + app/src/main/res/values/strings.xml | 2 + .../java/to/bitkit/ui/WalletViewModelTest.kt | 42 +++++++++++++++++++ gradle/libs.versions.toml | 2 +- 20 files changed, 127 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index b808c2e701..d72db02079 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -8,6 +8,7 @@ import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.pubkySwapsAdvance import com.synonym.bitkitcore.pubkySwapsCommitRoute +import com.synonym.bitkitcore.pubkySwapsRestore import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay @@ -39,6 +40,7 @@ class PubkySwapsRouteRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, private val keychain: Keychain, private val pubkyRepo: PubkyRepo, + private val lightningRepo: LightningRepo, ) { companion object { private const val TAG = "PubkySwapsRouteRepo" @@ -60,8 +62,7 @@ class PubkySwapsRouteRepo @Inject constructor( onchainSpendableSats: ULong, serviceLegs: List = emptyList(), ): 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 candidates = candidates() Logger.debug("Routing Paykit payment via '${candidates.map(PubkyPublicKeyFormat::redacted)}'", context = TAG) pubkySwapsRoutePaykitPayment( request = PaykitRouteRequest( @@ -79,6 +80,26 @@ class PubkySwapsRouteRepo @Inject constructor( ) } + /** + * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed. The listing + * does not carry the contact's address, so a restored swap claims to a fresh Savings address. Returns the swap ids. + */ + suspend fun restoreSwaps(): Result> = withSecrets { mnemonic, passphrase -> + val payoutAddress = lightningRepo.newAddress().getOrThrow() + pubkySwapsRestore( + providers = candidates(), + electrumUrl = Env.electrumServerUrl, + payoutAddress = payoutAddress, + feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, + network = Env.network.toCoreNetwork(), + mnemonic = mnemonic, + bip39Passphrase = passphrase, + ) + } + + /** Providers come from the user's own graph: every contact is asked for its swap offer. */ + private fun candidates(): List = pubkyRepo.contacts.value.map { it.publicKey } + Env.pubkySwapsProviders + suspend fun commit(quoteId: String): Result = withSecrets { mnemonic, passphrase -> pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase) } diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 7dfdfd4ad8..d9420b34b9 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -48,6 +48,7 @@ import to.bitkit.repositories.ConnectivityState import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.NodeStartYieldedToStopError import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.RecoveryModeError import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo @@ -79,6 +80,7 @@ class WalletViewModel @Inject constructor( private val connectivityRepo: ConnectivityRepo, private val boltzService: BoltzService, private val connectionRecovery: WalletConnectionRecovery, + private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, ) : ViewModel() { companion object { private const val TAG = "WalletViewModel" @@ -492,6 +494,7 @@ class WalletViewModel @Inject constructor( } }.onSuccess { _restoreState.update { RestoreState.Completed } + restorePubkySwaps() }.onFailure { Logger.error("Restore from backup failed", it, context = TAG) ToastEventBus.send(it) @@ -561,6 +564,32 @@ class WalletViewModel @Inject constructor( _restoreState.update { RestoreState.Settled } } + /** + * Finishes swap routes a restored wallet left in flight: each is rebuilt from its provider's listing and claimed to + * Savings, since the contact's address did not survive the restore, so the user learns the payment came back. + */ + private fun restorePubkySwaps() { + if (!pubkySwapsRouteRepo.isEnabled) return + viewModelScope.launch(bgDispatcher) { + val restored = pubkySwapsRouteRepo.restoreSwaps().getOrElse { + Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) + return@launch + } + Logger.info("Restored '${restored.size}' Pubky Swaps routes", context = TAG) + restored.forEach { swapId -> + launch { + pubkySwapsRouteRepo.awaitClaim(swapId).onSuccess { + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.wallet__swap_route_restored_title), + description = context.getString(R.string.wallet__swap_route_restored_text), + ) + } + } + } + } + } + fun onRestoreRetry() = requestRecoveryRetry(owner = null, editorId = null) private suspend fun retryRecovery(owner: WalletConnectionRecovery.Owner, backupOnly: Boolean, attempt: Long) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 5476d05814..a7418da19e 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -983,6 +983,8 @@ نعم، أرسل <accent>أرسل\nBitcoin</accent>\nإلى\nرصيد إنفاقك الإنفاق + دفعة لجهة اتصال قاطعتها الاستعادة عادت إلى مدخراتك. + أُعيدت الدفعة إلى المدخرات العلامات إضافة علامة إضافة 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 5206274597..d014e3ba39 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1016,6 +1016,8 @@ Sí, enviar <accent>Enviar\nbitcoin</accent>\na su\nsaldo de gastos Gasto + Un pago a un contacto que la restauración interrumpió volvió a tus ahorros. + Pago devuelto a Ahorros Etiquetas Añadir etiqueta Añadir diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d0a82d88f7..cee57ddeae 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1009,6 +1009,8 @@ Sí, Enviar <accent>Envia\nbitcoin</accent>\nal teu\nsaldo de despesa Despesa + Un pagament a un contacte que la restauració va interrompre ha tornat als teus estalvis. + Pagament retornat a Estalvis Etiquetes Afegeix etiqueta Afegir diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ecd167d9ce..55b390c650 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1014,6 +1014,8 @@ Ano, odeslat <accent>Odeslat\nbitcoin</accent>\ndo vašeho\ndisponibilního zůstatku Útraty + Platba kontaktu přerušená obnovou se vrátila do vašich úspor. + Platba vrácena do Úspor Tagy Vložit tag Vložit diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index a82ddaa7fe..34eb4c8352 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -892,6 +892,8 @@ Notiz Kommentar Optionaler Kommentar zum Empfänger + Eine Zahlung an einen Kontakt, die die Wiederherstellung unterbrochen hat, ist in deine Ersparnisse zurückgeflossen. + Zahlung an Ersparnisse zurückgegeben Tags Tag hinzufügen Hinzufügen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 0150d22b5e..3ee672943f 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -988,6 +988,8 @@ Ναι, Στείλε <accent>Στείλε\nbitcoin</accent>\nστο υπόλοιπο\nδαπανών Δαπάνες + Μια πληρωμή σε επαφή που διέκοψε η επαναφορά επέστρεψε στις αποταμιεύσεις σου. + Η πληρωμή επέστρεψε στις Αποταμιεύσεις Ετικέτες Προσθήκη ετικέτας Προσθήκη diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index d9926bc422..0f16718489 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1009,6 +1009,8 @@ Sí, enviar <accent>Envía\nbitcoin</accent>\na tu\nsaldo de gastos Gasto + Un pago a un contacto que la restauración interrumpió ha vuelto a tus ahorros. + Pago devuelto a Ahorros Etiquetas Añadir etiqueta Añadir diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index fcb9036536..5271fb7b36 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -882,6 +882,8 @@ ₿ {feeSats} para esta transacción ₿ {feeSats} para esta transacción ({fiatSymbol}{fiatFormatted}) Nota + Un pago a un contacto que la restauración interrumpió ha vuelto a tus ahorros. + Pago devuelto a Ahorros Etiquetas Añadir etiqueta Añadir diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 7bd8397d2a..5303d6d9a9 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -889,6 +889,8 @@ Note Commentaire Commentaire facultatif au destinataire + Un paiement à un contact interrompu par la restauration est revenu sur ton épargne. + Paiement renvoyé vers l\'Épargne Tags Ajouter une étiquette Ajouter diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 5aaed439be..924538f2d5 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1012,6 +1012,8 @@ Si, Invia <accent>Invia\nbitcoin</accent>\nal tuo\nconto di spesa Spesa + Un pagamento a un contatto interrotto dal ripristino è tornato nei tuoi risparmi. + Pagamento restituito ai Risparmi Tag Aggiungi Tag Aggiungi diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 878838f574..039ed9cd36 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1007,6 +1007,8 @@ Ja, verzenden <accent>Stuur\nbitcoin</accent>\nnaar je\nbestedingssaldo Bestedingssaldo + Een betaling aan een contact die door het herstel werd onderbroken, is teruggekomen op je spaargeld. + Betaling teruggestort naar Spaargeld Tags Tag toevoegen Toevoegen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index bdaaa87833..0efbd2a276 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -891,6 +891,8 @@ Notatka Komentarz Opcjonalny komentarz dla odbiorcy + Płatność do kontaktu przerwana przez przywracanie wróciła do twoich oszczędności. + Płatność zwrócona do Oszczędności Tagi Dodaj tag Dodaj diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 923a807517..57e149f1fc 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1016,6 +1016,8 @@ Sim, Enviar <accent>Transfira\nbitcoin</accent>\npara seu\nsaldo de gastos Gastos + Um pagamento a um contato que a restauração interrompeu voltou para sua poupança. + Pagamento devolvido à Poupança Tags Adicionar Tag Adicionar diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 0e397be809..9604c8ed31 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -751,6 +751,8 @@ Nota Comentário Comentário opcional para o receptor + Um pagamento a um contacto que o restauro interrompeu voltou às tuas poupanças. + Pagamento devolvido às Poupanças Tags Adicionar Tag Adicionar diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 796d825d09..5f7524c024 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1032,6 +1032,8 @@ Да, Отправить <accent>Отправьте\nбиткоин</accent>\nна ваш\nБаланс Расходов Расходы + Платёж контакту, прерванный восстановлением, вернулся в ваши сбережения. + Платёж возвращён в Сбережения Теги Добавить Тег Добавить diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9869929640..c6ee4f25db 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1571,6 +1571,8 @@ Yes, Send <accent>Send\nbitcoin</accent>\nto your\nspending balance Spending + A contact payment the restore interrupted came back to your savings. + Payment returned to Savings Tags Add Tag Add diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 0285ec4960..5a349a5a87 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -49,6 +49,7 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.NodeStartYieldedToStopError import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo import to.bitkit.repositories.WalletState @@ -86,6 +87,7 @@ class WalletViewModelTest : BaseUnitTest() { private val migrationService = mock() private val connectivityRepo = mock() private val boltzService = mock() + private val pubkySwapsRouteRepo = mock() private val lightningState = MutableStateFlow(LightningState()) private val walletState = MutableStateFlow(WalletState()) @@ -126,6 +128,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, ) } @@ -344,6 +347,40 @@ class WalletViewModelTest : BaseUnitTest() { assertFalse(settingsData.value.pendingRestoreActivitySeen) } + @Test + fun `restores swap routes once a wallet restore completes`() = test { + whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) + whenever(pubkySwapsRouteRepo.restoreSwaps()).thenReturn(Result.success(listOf("swap"))) + whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) + whenever(context.getString(any())).thenReturn("text") + whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn(Result.success(Unit)) + lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) + + sut.restoreWallet("mnemonic", "passphrase") + walletState.value = walletState.value.copy(walletExists = true) + advanceUntilIdle() + + assertEquals(RestoreState.Completed, sut.restoreState.value) + verify(pubkySwapsRouteRepo).restoreSwaps() + verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) + } + + @Test + fun `leaves swap routes alone after a restore while they are off`() = test { + whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(false) + whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn(Result.success(Unit)) + lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) + + sut.restoreWallet("mnemonic", "passphrase") + walletState.value = walletState.value.copy(walletExists = true) + advanceUntilIdle() + + assertEquals(RestoreState.Completed, sut.restoreState.value) + verify(pubkySwapsRouteRepo, never()).restoreSwaps() + } + @Test fun `failed backup restore can retry without restarting node`() = test { val testError = AppError("restore failed") @@ -1164,6 +1201,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, ) assertEquals(RestoreState.Initial, testSut.restoreState.value) @@ -1231,6 +1269,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, ) testSut.start() @@ -1287,6 +1326,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, ) // Trigger restore to put state in non-idle @@ -1327,6 +1367,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, ) testSut.restoreWallet("mnemonic", null) @@ -1418,6 +1459,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, ) advanceUntilIdle() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index af2fd39c6c..434905884b 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-swaps.3" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-swaps.4" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } From 257190c692062859e990ba82cffe8ca7330d151b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 2 Nov 2026 23:04:39 +0100 Subject: [PATCH 07/24] fix: keep the swap restore notice until dismissed --- .../to/bitkit/viewmodels/WalletViewModel.kt | 3 +++ journeys/paykit-swap-restore.xml | 24 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 journeys/paykit-swap-restore.xml diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index d9420b34b9..0cc3c41f38 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -579,10 +579,13 @@ class WalletViewModel @Inject constructor( restored.forEach { swapId -> launch { pubkySwapsRouteRepo.awaitClaim(swapId).onSuccess { + // The claim also opens the received sheet above the toasts: stay until dismissed so the user + // still sees why the money came back once that sheet closes. ToastEventBus.send( type = Toast.ToastType.INFO, title = context.getString(R.string.wallet__swap_route_restored_title), description = context.getString(R.string.wallet__swap_route_restored_text), + autoHide = false, ) } } diff --git a/journeys/paykit-swap-restore.xml b/journeys/paykit-swap-restore.xml new file mode 100644 index 0000000000..7b2e2ea2c1 --- /dev/null +++ b/journeys/paykit-swap-restore.xml @@ -0,0 +1,24 @@ + + + Proves that a swap route the wallet left in flight before its claim is finished after the wallet is wiped and + restored from its recovery phrase: the restore finds the swap at its provider, claims it to Savings (the contact's + address does not survive the restore), and tells the user the payment was returned to Savings. + + Preconditions: as paykit-swap-route.xml, with the provider running against bitkit-docker (`--no-homeserver`) and + the build's PUBKY_SWAPS_PROVIDERS naming it. A throwaway regtest wallet restored from a recovery phrase, with a + spending balance from an LNURL channel, an empty savings balance, a Pubky profile, and the provider and the + fixture-issuer saved as contacts. Start a 20 000 sat payment to the fixture-issuer through the swap route, wait + until the provider logs "HTLC funded; awaiting client claim", and force-stop the app before any block is mined. + Then clear the app's data and enter the same recovery phrase on the restore screen. + + + Tap Restore (tag "RestoreButton") and wait for the Wallet Restored screen, then tap Get Started (tag "GetStartedButton") + Verify the savings balance (tag "ActivitySavings") shows 0 + Mine one block on bitkit-docker's bitcoind, so the provider's lockup confirms + Verify the provider logs "client claimed; hold invoice settled" + Mine one more block, so the claim confirms + Verify the "Received Bitcoin" sheet shows 20 000, then close it + Verify the toast "Payment returned to Savings" is visible + Verify the savings balance (tag "ActivitySavings") shows 20 000, and bitcoind shows the claim transaction paying exactly 0.0002 BTC to the wallet's own address + + From 79dd3457f9b25d6451b3f75071b75efcaad4a064 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:52:49 +0100 Subject: [PATCH 08/24] chore: move to bitkit-core 0.8.0-swaps.9 Restore passes the Lightning payments the node sent, so bitkit-core checks each listed lockup against what was paid, and drives the swaps already on record too. --- .../repositories/PubkySwapsRouteRepo.kt | 30 +++++++++++++++++-- gradle/libs.versions.toml | 2 +- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index d72db02079..a38114a692 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -5,6 +5,7 @@ import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.PaykitRouteRequest import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteState +import com.synonym.bitkitcore.PubkySwapSentPayment import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.pubkySwapsAdvance import com.synonym.bitkitcore.pubkySwapsCommitRoute @@ -13,6 +14,9 @@ import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.withContext +import org.lightningdevkit.ldknode.PaymentDirection +import org.lightningdevkit.ldknode.PaymentKind +import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.env.Env @@ -82,12 +86,15 @@ class PubkySwapsRouteRepo @Inject constructor( /** * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed. The listing - * does not carry the contact's address, so a restored swap claims to a fresh Savings address. Returns the swap ids. + * does not carry the contact's address, so a restored swap claims to a fresh Savings address. bitkit-core checks + * each listed lockup against the Lightning payment this node sent for its hash. Returns the ids to drive: the + * swaps restored now and those already on record. */ suspend fun restoreSwaps(): Result> = withSecrets { mnemonic, passphrase -> val payoutAddress = lightningRepo.newAddress().getOrThrow() - pubkySwapsRestore( + val report = pubkySwapsRestore( providers = candidates(), + sentPayments = sentPayments(), electrumUrl = Env.electrumServerUrl, payoutAddress = payoutAddress, feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, @@ -95,8 +102,27 @@ class PubkySwapsRouteRepo @Inject constructor( mnemonic = mnemonic, bip39Passphrase = passphrase, ) + if (report.incompleteProviders.isNotEmpty()) { + Logger.warn("Swap lists incomplete from '${report.incompleteProviders}'", context = TAG) + } + report.restored + report.known } + /** The Lightning payments this node sent, pending or settled, by hash and the amount paid to the payee. */ + private suspend fun sentPayments(): List = + lightningRepo.getPayments().getOrThrow().mapNotNull { payment -> + val kind = payment.kind as? PaymentKind.Bolt11 ?: return@mapNotNull null + val amountMsat = payment.amountMsat ?: return@mapNotNull null + if (payment.direction != PaymentDirection.OUTBOUND || payment.status == PaymentStatus.FAILED) { + return@mapNotNull null + } + PubkySwapSentPayment( + paymentHashHex = kind.hash, + amountSat = amountMsat / 1000u, + settled = payment.status == PaymentStatus.SUCCEEDED, + ) + } + /** Providers come from the user's own graph: every contact is asked for its swap offer. */ private fun candidates(): List = pubkyRepo.contacts.value.map { it.publicKey } + Env.pubkySwapsProviders diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 50be508050..1fa7c94077 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.4" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-swaps.9" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.86" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.86" } From 9f6ec3b61731f1cd086eef90c25c88a15d860d7d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 20:26:49 +0100 Subject: [PATCH 09/24] test: expect the restore's failed categories --- .../test/java/to/bitkit/ui/WalletViewModelTest.kt | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index b779f617be..cf7903c18a 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -356,14 +356,16 @@ class WalletViewModelTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) whenever(context.getString(any())).thenReturn("text") whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) - whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn(Result.success(Unit)) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn( + Result.success(emptySet()) + ) lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) sut.restoreWallet("mnemonic", "passphrase") walletState.value = walletState.value.copy(walletExists = true) advanceUntilIdle() - assertEquals(RestoreState.Completed, sut.restoreState.value) + assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) verify(pubkySwapsRouteRepo).restoreSwaps() verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) } @@ -372,14 +374,16 @@ class WalletViewModelTest : BaseUnitTest() { fun `leaves swap routes alone after a restore while they are off`() = test { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(false) whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) - whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn(Result.success(Unit)) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn( + Result.success(emptySet()) + ) lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) sut.restoreWallet("mnemonic", "passphrase") walletState.value = walletState.value.copy(walletExists = true) advanceUntilIdle() - assertEquals(RestoreState.Completed, sut.restoreState.value) + assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) verify(pubkySwapsRouteRepo, never()).restoreSwaps() } From de294632a0d9a43d9b049df866e0c4312f2c29a7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:31:16 +0100 Subject: [PATCH 10/24] fix: finish a swap-routed send once, with its tags The hold invoice's own success is skipped and its tags are saved against its payment, a Direct answer moves the payment to Savings, a quote from a replaced send is dropped, and Spending stays selectable for a swap-routed contact. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 53 +++- .../viewmodels/AppViewModelSendFlowTest.kt | 250 ++++++++++++++++++ 2 files changed, 299 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1419347a7c..1c4b25d8fb 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4592,7 +4592,7 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } - _sendUiState.value.paykitSwapRoute?.let { + _sendUiState.value.activePaykitSwapRoute?.let { if (quotePaykitSwapRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) return } @@ -4611,6 +4611,9 @@ class AppViewModel @Inject constructor( } private suspend fun quotePaykitSwapRoute(route: PaykitSwapRouteUi): Boolean { + val generation = sendStateGeneration + val walletGeneration = connectionRecovery.currentGeneration() + val payment = synchronized(contactPaymentContextLock) { activeContactPaymentContext } _sendUiState.update { it.copy(isLoading = true) } val balances = walletRepo.balanceState.value val result = pubkySwapsRouteRepo.route( @@ -4620,6 +4623,12 @@ class AppViewModel @Inject constructor( onchainSpendableSats = balances.maxSendOnchainSats, ) _sendUiState.update { it.copy(isLoading = false) } + if ( + generation != sendStateGeneration || !connectionRecovery.isCurrentGeneration(walletGeneration) || + synchronized(contactPaymentContextLock) { activeContactPaymentContext } != payment + ) { + return false + } val paykitRoute = result.getOrElse { Logger.error("Failed to route Paykit payment through Pubky Swaps", it, context = TAG) toast(it) @@ -4637,9 +4646,12 @@ class AppViewModel @Inject constructor( toast(AppError(context.getString(R.string.common__error_body))) return false } - // Balances changed after the contact opened: the regular flow must reopen it. + // Savings now covers the payment, so it goes on-chain directly. is PaykitRoute.Direct -> { _sendUiState.update { it.copy(paykitSwapRoute = null) } + selectFundingSource(SendFundingSource.Savings, _sendUiState.value) + _sendUiState.update { it.copy(isAmountInputValid = validateAmount(it.amount, SendMethod.ONCHAIN)) } + updateCanSwitchWallet() toast(AppError(context.getString(R.string.common__error_body))) return false } @@ -5705,7 +5717,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.paykitSwapRoute != null + ) { add( SendFundingSource.Spending ) @@ -6352,7 +6367,7 @@ class AppViewModel @Inject constructor( return } - _sendUiState.value.paykitSwapRoute?.quote?.let { + _sendUiState.value.activePaykitSwapRoute?.quote?.let { proceedWithSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId) return } @@ -6746,8 +6761,22 @@ class AppViewModel @Inject constructor( return } Logger.info("Committed Pubky Swaps route '${payment.swapId}' to '${payment.destinationAddress}'", context = TAG) + val holdPaymentHash = runSuspendCatching { + requireNotNull((coreService.decode(payment.invoice) as? Scanner.Lightning)?.invoice) { + "Swap hold invoice is not a Lightning invoice" + }.paymentHash.toHex() + }.getOrElse { + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + // Only the claim finishes the send: the hold invoice's own success event is skipped as already processed. + synchronized(processedPaymentsLock) { processedPayments.add(holdPaymentHash) } + val tagsSaved = saveSwapRouteTags(holdPaymentHash) // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. lightningRepo.payInvoice(payment.invoice).getOrElse { + if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext) @@ -6770,6 +6799,18 @@ class AppViewModel @Inject constructor( ) } + private suspend fun saveSwapRouteTags(paymentHash: String): Boolean { + val tags = _sendUiState.value.selectedTags + if (tags.isEmpty()) return false + return preActivityMetadataRepo.savePreActivityMetadata( + id = paymentHash, + paymentHash = paymentHash, + address = _sendUiState.value.address, + isReceive = false, + tags = tags, + ).isSuccess + } + private suspend fun proceedWithLightningPayment( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, @@ -9178,6 +9219,10 @@ data class SendUiState( val incomingPaymentRequestId: PaykitPaymentRequestId? = null, val paykitSwapRoute: PaykitSwapRouteUi? = null, ) { + /** The swap route while Spending pays: picking another funding source pays that source directly. */ + val activePaykitSwapRoute: PaykitSwapRouteUi? + get() = paykitSwapRoute?.takeIf { payMethod == SendMethod.LIGHTNING && hardwareWalletId == null } + 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 6810454a28..bb84c0ce1e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -21,6 +21,10 @@ 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.PaykitRoute +import com.synonym.bitkitcore.PubkySwapRoutePayment +import com.synonym.bitkitcore.PubkySwapRouteQuote import com.synonym.bitkitcore.Scanner import com.synonym.bitkitcore.UsdtDestination import com.synonym.bitkitcore.UsdtException @@ -16784,6 +16788,243 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return privateContext } + @Test + fun `swap routed contact payment finishes once on the claim and tags the hold payment`() = test { + val activityV1 = mock { + on { value } doReturn SWAP_DEBIT_SATS + on { fee } doReturn 0u + } + val activity = mock { on { v1 } doReturn activityV1 } + whenever { activityRepo.findActivityByPaymentId(any(), any(), any(), any()) } + .thenReturn(Result.success(activity)) + whenever(pendingPaymentRepo.isPending(SWAP_HOLD_HASH)).thenReturn(false) + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).thenReturn(Result.success(SWAP_CLAIM_TXID)) + whenever( + preActivityMetadataRepo.savePreActivityMetadata( + id = eq(SWAP_HOLD_HASH), + paymentHash = eq(SWAP_HOLD_HASH), + txId = anyOrNull(), + address = eq(REGTEST_ADDRESS), + isReceive = eq(false), + tags = eq(listOf("rent")), + feeRate = anyOrNull(), + isTransfer = any(), + channelId = anyOrNull(), + walletId = any(), + ), + ).thenReturn(Result.success(Unit)) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) + sut.addTagToSelected("rent") + confirmCurrentPayment() + assertEquals(SendEffect.PaymentSuccess, awaitItem()) + assertEquals(SWAP_CLAIM_TXID, sut.successSendUiState.value.paymentHashOrTxId) + + emitNodeEvent( + Event.PaymentSuccessful( + paymentId = SWAP_HOLD_HASH, + paymentHash = SWAP_HOLD_HASH, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + advanceUntilIdle() + expectNoEvents() + assertEquals(SWAP_CLAIM_TXID, sut.successSendUiState.value.paymentHashOrTxId) + } + verify(preActivityMetadataRepo).savePreActivityMetadata( + id = eq(SWAP_HOLD_HASH), + paymentHash = eq(SWAP_HOLD_HASH), + txId = anyOrNull(), + address = eq(REGTEST_ADDRESS), + isReceive = eq(false), + tags = eq(listOf("rent")), + feeRate = anyOrNull(), + isTransfer = any(), + channelId = anyOrNull(), + walletId = any(), + ) + } + + @Test + fun `swap route quote failure stays on the amount screen`() = test { + openSwapRoutedContactPayment(quote = Result.failure(AppError("no provider"))) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + assertFalse(sut.sendUiState.value.isLoading) + verify(pubkySwapsRouteRepo, never()).commit(any()) + } + + @Test + fun `swap route hold payment failure never awaits the claim`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.failure(AppError("no route"))) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmCurrentPayment() + expectNoEvents() + } + assertNull(sut.currentSheet.value) + verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any()) + } + + @Test + fun `swap route claim failure shows no success`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).thenReturn(Result.failure(AppError("refunded"))) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmCurrentPayment() + expectNoEvents() + } + assertNull(sut.currentSheet.value) + assertNull(sut.successSendUiState.value.paymentHashOrTxId) + } + + @Test + fun `swap route answered direct switches the payment to savings`() = test { + openSwapRoutedContactPayment( + quote = Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 100_000u) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + assertNull(sut.sendUiState.value.paykitSwapRoute) + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + } + + @Test + fun `swap route quote for a replaced send is discarded`() = test { + val quoted = CompletableDeferred>() + openSwapRoutedContactPayment() + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quoted.await() } + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + sut.resetSendState() + quoted.complete(Result.success(PaykitRoute.Swap(swapRouteQuote()))) + advanceUntilIdle() + expectNoEvents() + } + assertNull(sut.sendUiState.value.paykitSwapRoute) + } + + @Test + fun `swap route quote after a wallet change is discarded without blocking continue`() = test { + val quoted = CompletableDeferred>() + openSwapRoutedContactPayment() + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quoted.await() } + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + walletGeneration++ + quoted.complete(Result.success(PaykitRoute.Swap(swapRouteQuote()))) + advanceUntilIdle() + expectNoEvents() + } + assertFalse(sut.sendUiState.value.isLoading) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + } + + @Test + fun `swap routed contact returns to spending after picking savings`() = test { + openSwapRoutedContactPayment() + + val spending = sut.sendUiState.value.fundingOptions.single { it.source == SendFundingSource.Spending } + assertTrue(spending.enabled) + sut.setSendEvent(SendEvent.PaymentMethodSwitch) + advanceUntilIdle() + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + sut.setSendEvent(SendEvent.PaymentMethodSwitch) + advanceUntilIdle() + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + } + assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) + } + + private suspend fun TestScope.openSwapRoutedContactPayment( + quote: Result = Result.success(PaykitRoute.Swap(swapRouteQuote())), + ) { + whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).thenReturn(quote) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(coreService.decode(SWAP_HOLD_INVOICE)).thenReturn( + Scanner.Lightning(lightningInvoice(SWAP_HOLD_INVOICE, amountSats = SWAP_DEBIT_SATS)), + ) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + sut.openContactPayment( + paymentRequest = REGTEST_ADDRESS, + publicKey = testPublicKey, + endpoints = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), + ) + advanceUntilIdle() + sut.setSendEvent(SendEvent.AmountChange(SWAP_DELIVERED_SATS)) + advanceUntilIdle() + } + + private fun swapRouteQuote() = PubkySwapRouteQuote( + providerPubky = testPublicKey, + quoteId = SWAP_QUOTE_ID, + endpoint = PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS), + deliveredSat = SWAP_DELIVERED_SATS, + lockSat = SWAP_DELIVERED_SATS, + debitSat = SWAP_DEBIT_SATS, + serviceFeeSat = 100u, + providerOnchainFeeSat = 0u, + claimFeeSat = 0u, + totalFeeSat = 100u, + atomicity = "htlc", + validUntilUnix = 0u, + providersQuoted = 1u, + ) + + private fun swapRoutePayment() = PubkySwapRoutePayment( + swapId = SWAP_ID, + invoice = SWAP_HOLD_INVOICE, + debitSat = SWAP_DEBIT_SATS, + deliveredSat = SWAP_DELIVERED_SATS, + destinationAddress = REGTEST_ADDRESS, + htlcAddress = REGTEST_ADDRESS, + timeoutBlockHeight = 0u, + ) + private fun lightningInvoice( bolt11: String, amountSats: ULong, @@ -18252,5 +18493,14 @@ private const val SAMROCK_SETUP_URL = private const val RESTORE_STARTED_AT = 1_700_000_000L private const val HARDWARE_WALLET_ID = "trezor:wallet" private const val REGTEST_ADDRESS = "bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" +private const val SWAP_QUOTE_ID = "swap-quote" +private const val SWAP_ID = "swap" +private const val SWAP_HOLD_INVOICE = "lnbcrt1swaphold" + +/** The hex of [lightningInvoice]'s payment hash. */ +private const val SWAP_HOLD_HASH = "010203" +private const val SWAP_CLAIM_TXID = "claimtxid" +private const val SWAP_DELIVERED_SATS = 20_000uL +private const val SWAP_DEBIT_SATS = 20_100uL private const val OWN_NODE_ID = "02abababababababababababababababababababababababababababababababab" private const val FOREIGN_NODE_ID = "03cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" From 3435c0ef12cade99aa7e420a021056b574460e2d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:58:10 +0100 Subject: [PATCH 11/24] fix: finish a swap-routed send when the claim is broadcast The send succeeds once bitkit-core broadcasts the claim, and the claim is advanced in the background until it confirms. A failed hold payment stops the wait at once, a failed advance is retried, restore shows the Savings notice only for swaps rebuilt now, the contact is set on the hold payment's activity, and the endpoint's method id matches its address. --- .../repositories/PubkySwapsRouteRepo.kt | 79 +++++++++++--- .../java/to/bitkit/viewmodels/AppViewModel.kt | 102 +++++++++++++----- .../to/bitkit/viewmodels/WalletViewModel.kt | 11 +- .../repositories/PubkySwapsRouteRepoTest.kt | 85 +++++++++++++++ .../java/to/bitkit/ui/WalletViewModelTest.kt | 27 ++++- .../viewmodels/AppViewModelSendFlowTest.kt | 67 +++++++++++- 6 files changed, 320 insertions(+), 51 deletions(-) create mode 100644 app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index a38114a692..bd80792412 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -13,14 +13,16 @@ import com.synonym.bitkitcore.pubkySwapsRestore import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus +import to.bitkit.async.appScope 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 @@ -51,8 +53,16 @@ class PubkySwapsRouteRepo @Inject constructor( private const val CLAIM_FEE_RATE_SAT_VB = 2uL private val POLL_INTERVAL = 2.seconds private val CLAIM_TIMEOUT = 10.minutes + + /** How often a broadcast claim is advanced, so bitkit-core rebroadcasts it until it confirms. */ + private val CONFIRMATION_POLL_INTERVAL = 30.seconds + + /** How long a broadcast claim is advanced in the background before polling stops. */ + private val CONFIRMATION_TIMEOUT = 60.minutes } + private val scope = appScope(ioDispatcher, TAG) + val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled /** The contact behind a provider's pubky, so the review shows who routes the payment. */ @@ -87,10 +97,10 @@ class PubkySwapsRouteRepo @Inject constructor( /** * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed. The listing * does not carry the contact's address, so a restored swap claims to a fresh Savings address. bitkit-core checks - * each listed lockup against the Lightning payment this node sent for its hash. Returns the ids to drive: the - * swaps restored now and those already on record. + * each listed lockup against the Lightning payment this node sent for its hash. Swaps already on record keep the + * destination they were committed with. */ - suspend fun restoreSwaps(): Result> = withSecrets { mnemonic, passphrase -> + suspend fun restoreSwaps(): Result = withSecrets { mnemonic, passphrase -> val payoutAddress = lightningRepo.newAddress().getOrThrow() val report = pubkySwapsRestore( providers = candidates(), @@ -105,7 +115,7 @@ class PubkySwapsRouteRepo @Inject constructor( if (report.incompleteProviders.isNotEmpty()) { Logger.warn("Swap lists incomplete from '${report.incompleteProviders}'", context = TAG) } - report.restored + report.known + RestoredPubkySwaps(restored = report.restored, known = report.known) } /** The Lightning payments this node sent, pending or settled, by hash and the amount paid to the payee. */ @@ -124,27 +134,58 @@ class PubkySwapsRouteRepo @Inject constructor( } /** Providers come from the user's own graph: every contact is asked for its swap offer. */ - private fun candidates(): List = pubkyRepo.contacts.value.map { it.publicKey } + Env.pubkySwapsProviders + private fun candidates(): List = + (Env.pubkySwapsProviders + pubkyRepo.contacts.value.map { it.publicKey }).distinct() 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. */ + /** + * Advance the swap until bitkit-core broadcasts the claim to the contact, returning the claim txid. The provider + * settles the hold invoice once it sees the claim, so the payment is done; the claim is still advanced in the + * background so bitkit-core rebroadcasts it until it confirms. + */ suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result { - val deadline = nowMillis() + timeout.inWholeMilliseconds + var lastFailure: Throwable? = null + return withTimeoutOrNull(timeout) { + pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } + }?.onSuccess { + scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } + } ?: Result.failure(lastFailure ?: AppError("Swap '$swapId' not claimed yet")) + } + + private suspend fun awaitConfirmation(swapId: String) { + pollClaim(swapId, CONFIRMATION_POLL_INTERVAL, untilConfirmed = true) {} + .onSuccess { Logger.info("Confirmed Pubky Swaps claim '$it' for '$swapId'", context = TAG) } + .onFailure { Logger.warn("Failed to confirm Pubky Swaps claim for '$swapId'", it, context = TAG) } + } + + private suspend fun pollClaim( + swapId: String, + interval: Duration, + untilConfirmed: Boolean, + onPending: (Throwable) -> Unit, + ): Result { while (true) { - val status = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } - .getOrElse { return Result.failure(it) } - when (val state = status.state) { + // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. + val state = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } + .onFailure { + Logger.warn("Failed to advance Pubky Swaps route '$swapId'", it, context = TAG) + onPending(it) + } + .getOrNull()?.state + when (state) { is PubkySwapRouteState.Claimed -> return Result.success(state.txid) + is PubkySwapRouteState.ClaimBroadcast if !untilConfirmed -> return Result.success(state.txid) is PubkySwapRouteState.Failed -> return Result.failure(AppError(state.reason)) - else -> Logger.debug("Pubky Swaps route '$swapId': $state", context = TAG) + null -> Unit + else -> { + Logger.debug("Pubky Swaps route '$swapId': $state", context = TAG) + onPending(AppError("Swap '$swapId' not claimed yet: '$state'")) + } } - if (nowMillis() > deadline) { - return Result.failure(AppError("Swap '$swapId' not claimed yet: '${status.state}'")) - } - delay(POLL_INTERVAL) + delay(interval) } } @@ -157,3 +198,9 @@ class PubkySwapsRouteRepo @Inject constructor( } } } + +/** The swaps a restore found: those rebuilt now claim to Savings, those already on record keep their destination. */ +data class RestoredPubkySwaps( + val restored: List, + val known: List, +) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1c4b25d8fb..c2d3e4f8b8 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -30,6 +30,7 @@ import com.synonym.bitkitcore.OnChainInvoice import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.PaymentType +import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteQuote import com.synonym.bitkitcore.Scanner import com.synonym.bitkitcore.SortDirection @@ -78,6 +79,7 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.job import kotlinx.coroutines.launch +import kotlinx.coroutines.selects.select import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext @@ -2848,6 +2850,7 @@ class AppViewModel @Inject constructor( private fun closeActiveSendForFailedPayment(paymentHash: String, reason: PaymentFailureReason?): Boolean { val activePaymentHash = _sendUiState.value.decodedInvoice?.paymentHash?.toHex() + ?: _sendUiState.value.activePaykitSwapRoute?.holdPaymentHash if (_currentSheet.value !is Sheet.Send || activePaymentHash != paymentHash) return false setSendEffect( @@ -3989,11 +3992,12 @@ class AppViewModel @Inject constructor( walletGeneration: Long?, ) { requireCurrentPaymentPreparation(walletGeneration) - val decoded = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } - .map { - coreService.decode(it.paymentRequest).also { requireCurrentPaymentPreparation(walletGeneration) } - } - val address = decoded.filterIsInstance().lastOrNull()?.invoice?.address.orEmpty() + val bitcoinEndpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } + val decoded = bitcoinEndpoints.map { + coreService.decode(it.paymentRequest).also { requireCurrentPaymentPreparation(walletGeneration) } + } + val onchainEndpoint = bitcoinEndpoints.zip(decoded).lastOrNull { it.second is Scanner.OnChain } + val address = (onchainEndpoint?.second as? Scanner.OnChain)?.invoice?.address.orEmpty() val invoice = decoded.filterIsInstance().lastOrNull()?.invoice val lnurl = decoded.filterIsInstance().lastOrNull()?.let { LnurlParams.LnurlPay(it.data) } val usdtEndpoint = payment.endpoints.firstOrNull { it.methodId == MethodId.UsdtArbitrum } @@ -4009,7 +4013,12 @@ 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 swapRoute = paykitSwapRoute( + payment = payment, + methodId = onchainEndpoint?.first?.methodId, + address = address, + canPayDirectly = canUseLightning || canUseOnchain || useUsdt, + ) val payMethod = if (swapRoute != null) { SendMethod.LIGHTNING } else { @@ -4161,13 +4170,14 @@ class AppViewModel @Inject constructor( */ private fun paykitSwapRoute( payment: ContactPaymentContext, + methodId: MethodId?, 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 + if (methodId?.isOnchain != true) return null return PaykitSwapRouteUi(endpoint = PaykitEndpoint(methodId = methodId.rawValue, value = address)) } @@ -6773,30 +6783,65 @@ class AppViewModel @Inject constructor( } // Only the claim finishes the send: the hold invoice's own success event is skipped as already processed. synchronized(processedPaymentsLock) { processedPayments.add(holdPaymentHash) } + // A failed hold payment closes the send through the node's failure event, like a regular Lightning send. + _sendUiState.update { it.copy(paykitSwapRoute = it.paykitSwapRoute?.copy(holdPaymentHash = holdPaymentHash)) } val tagsSaved = saveSwapRouteTags(holdPaymentHash) - // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. - lightningRepo.payInvoice(payment.invoice).getOrElse { - if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) - return + val holdFailure = viewModelScope.async(start = CoroutineStart.UNDISPATCHED) { + lightningRepo.nodeEvents.watchUntil { + when (it) { + is Event.PaymentFailed if it.paymentHash == holdPaymentHash -> WatchResult.Complete(it.reason) + else -> WatchResult.Continue() + } + } } - val claimTxid = pubkySwapsRouteRepo.awaitClaim(payment.swapId).getOrElse { - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) - return + try { + // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. + lightningRepo.payInvoice(payment.invoice).getOrElse { + if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + val claimTxid = awaitSwapClaim(payment, holdFailure).getOrElse { + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + if (it is LightningPaymentFailedError) { + if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) + releasePrivatePaymentListIfNeeded(contactPaymentContext) + return + } + handlePaymentPreparationFailure(it, contactPaymentContext) + return + } + finishManualAllowancePayment(allowanceAttemptId, succeeded = true) + Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$claimTxid'", context = TAG) + // The claim pays the contact's address: the wallet's own record of the payment is the hold invoice's debit. + syncContactForActivity(holdPaymentHash) + onSendSuccess( + NewTransactionSheetDetails( + type = NewTransactionSheetType.LIGHTNING, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = holdPaymentHash, + sats = payment.deliveredSat.toLong(), + ), + allowDuplicateHash = true, + ) + } finally { + holdFailure.cancel() } - 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 awaitSwapClaim( + payment: PubkySwapRoutePayment, + holdFailure: Deferred, + ): Result = coroutineScope { + val claim = async { pubkySwapsRouteRepo.awaitClaim(payment.swapId) } + select { + claim.onAwait { it } + holdFailure.onAwait { + Result.failure(LightningPaymentFailedError(reason = it, paymentRequest = payment.invoice)) + } + }.also { claim.cancel() } } private suspend fun saveSwapRouteTags(paymentHash: String): Boolean { @@ -9257,6 +9302,7 @@ data class PaykitSwapRouteUi( val endpoint: PaykitEndpoint, val quote: PubkySwapRouteQuote? = null, val providerName: String? = null, + val holdPaymentHash: String? = null, ) @Immutable diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 2a17f18198..19a0323593 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -577,12 +577,17 @@ class WalletViewModel @Inject constructor( private fun restorePubkySwaps() { if (!pubkySwapsRouteRepo.isEnabled) return viewModelScope.launch(bgDispatcher) { - val restored = pubkySwapsRouteRepo.restoreSwaps().getOrElse { + val swaps = pubkySwapsRouteRepo.restoreSwaps().getOrElse { Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) return@launch } - Logger.info("Restored '${restored.size}' Pubky Swaps routes", context = TAG) - restored.forEach { swapId -> + Logger.info( + "Restored '${swaps.restored.size}' Pubky Swaps routes, '${swaps.known.size}' known", + context = TAG, + ) + // A known swap keeps the destination it was committed with, such as the contact, so it is driven silently. + swaps.known.forEach { launch { pubkySwapsRouteRepo.awaitClaim(it) } } + swaps.restored.forEach { swapId -> launch { pubkySwapsRouteRepo.awaitClaim(swapId).onSuccess { // The claim also opens the received sheet above the toasts: stay until dismissed so the user diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt new file mode 100644 index 0000000000..afdb692722 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -0,0 +1,85 @@ +package to.bitkit.repositories + +import com.synonym.bitkitcore.PubkySwapRouteState +import com.synonym.bitkitcore.PubkySwapRouteStatus +import com.synonym.bitkitcore.pubkySwapsAdvance +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito.mockStatic +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.data.keychain.Keychain +import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.AppError +import kotlin.test.assertEquals +import kotlin.time.Duration.Companion.minutes + +class PubkySwapsRouteRepoTest : BaseUnitTest() { + companion object { + private const val SWAP_ID = "swap" + private const val CLAIM_TXID = "claim" + private const val CONFIRMED_CLAIM_TXID = "confirmed" + + /** The Kotlin facade holding bitkit-core's top-level functions, which Kotlin sources cannot name. */ + private val CORE: Class<*> = Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt") + } + + private val keychain = mock() + private lateinit var sut: PubkySwapsRouteRepo + + @Before + fun setUp() { + whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn("mnemonic") + sut = PubkySwapsRouteRepo( + ioDispatcher = testDispatcher, + keychain = keychain, + pubkyRepo = mock(), + lightningRepo = mock(), + ) + } + + @Test + fun `awaitClaim finishes once the claim is broadcast`() = test { + val txid = advancing( + PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u), + PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID), + PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID), + ) { sut.awaitClaim(SWAP_ID, timeout = 1.minutes) } + + assertEquals(Result.success(CLAIM_TXID), txid) + } + + @Test + fun `awaitClaim keeps polling after a failed advance`() = test { + val txid = advancing( + AppError("electrum unreachable"), + PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID), + PubkySwapRouteState.Claimed(CLAIM_TXID), + ) { sut.awaitClaim(SWAP_ID, timeout = 1.minutes) } + + assertEquals(Result.success(CLAIM_TXID), txid) + } + + private suspend fun advancing(vararg answers: Any, block: suspend () -> T): T = + mockStatic(CORE).use { core -> + var stub = core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + answers.forEach { answer -> + stub = when (answer) { + is Throwable -> stub.thenAnswer { throw answer } + else -> stub.thenReturn(status(answer as PubkySwapRouteState)) + } + } + block() + } + + private fun status(state: PubkySwapRouteState) = PubkySwapRouteStatus( + swapId = SWAP_ID, + state = state, + providerPubky = "provider", + deliveredSat = 20_000u, + destinationAddress = "address", + ) +} diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index cf7903c18a..a0929e099f 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -33,6 +33,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever +import to.bitkit.R import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery @@ -50,6 +51,7 @@ import to.bitkit.repositories.LightningState import to.bitkit.repositories.NodeStartYieldedToStopError import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.PubkySwapsRouteRepo +import to.bitkit.repositories.RestoredPubkySwaps import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo import to.bitkit.repositories.WalletState @@ -352,7 +354,8 @@ class WalletViewModelTest : BaseUnitTest() { @Test fun `restores swap routes once a wallet restore completes`() = test { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) - whenever(pubkySwapsRouteRepo.restoreSwaps()).thenReturn(Result.success(listOf("swap"))) + whenever(pubkySwapsRouteRepo.restoreSwaps()) + .thenReturn(Result.success(RestoredPubkySwaps(listOf("swap"), emptyList()))) whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) whenever(context.getString(any())).thenReturn("text") whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) @@ -368,6 +371,28 @@ class WalletViewModelTest : BaseUnitTest() { assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) verify(pubkySwapsRouteRepo).restoreSwaps() verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) + verify(context).getString(R.string.wallet__swap_route_restored_title) + } + + @Test + fun `drives known swap routes after a restore without the Savings notice`() = test { + whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) + whenever(pubkySwapsRouteRepo.restoreSwaps()) + .thenReturn(Result.success(RestoredPubkySwaps(emptyList(), listOf("swap")))) + whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) + whenever(context.getString(any())).thenReturn("text") + whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn( + Result.success(emptySet()) + ) + lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) + + sut.restoreWallet("mnemonic", "passphrase") + walletState.value = walletState.value.copy(walletExists = true) + advanceUntilIdle() + + verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) + verify(context, never()).getString(R.string.wallet__swap_route_restored_title) } @Test diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index bb84c0ce1e..b457ea40d2 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -16826,7 +16826,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.addTagToSelected("rent") confirmCurrentPayment() assertEquals(SendEffect.PaymentSuccess, awaitItem()) - assertEquals(SWAP_CLAIM_TXID, sut.successSendUiState.value.paymentHashOrTxId) + assertEquals(SWAP_HOLD_HASH, sut.successSendUiState.value.paymentHashOrTxId) + assertEquals(NewTransactionSheetType.LIGHTNING, sut.successSendUiState.value.type) emitNodeEvent( Event.PaymentSuccessful( @@ -16838,8 +16839,14 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) advanceUntilIdle() expectNoEvents() - assertEquals(SWAP_CLAIM_TXID, sut.successSendUiState.value.paymentHashOrTxId) + assertEquals(SWAP_HOLD_HASH, sut.successSendUiState.value.paymentHashOrTxId) } + verify(activityRepo).setContact( + contactPublicKey = eq(testPublicKey), + forPaymentId = eq(SWAP_HOLD_HASH), + syncLdkPayments = any(), + walletId = any(), + ) verify(preActivityMetadataRepo).savePreActivityMetadata( id = eq(SWAP_HOLD_HASH), paymentHash = eq(SWAP_HOLD_HASH), @@ -16854,6 +16861,25 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `swap route pairs the address with the method of the endpoint it came from`() = test { + val taprootAddress = "bcrt1ptaproot" + whenever(coreService.decode(taprootAddress)).thenReturn( + Scanner.OnChain(OnChainInvoice(taprootAddress, 0u, null, null, null)), + ) + openSwapRoutedContactPayment( + endpoints = listOf( + Endpoint(MethodId.P2tr, taprootAddress, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ), + ) + + assertEquals( + PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS), + sut.sendUiState.value.paykitSwapRoute?.endpoint, + ) + } + @Test fun `swap route quote failure stays on the amount screen`() = test { openSwapRoutedContactPayment(quote = Result.failure(AppError("no provider"))) @@ -16886,6 +16912,40 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any()) } + @Test + fun `swap route hold payment failure event stops awaiting the claim`() = test { + var claimCancelled = false + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { + try { + awaitCancellation() + } finally { + claimCancelled = true + } + } + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmCurrentPayment() + emitNodeEvent( + Event.PaymentFailed( + paymentId = SWAP_HOLD_HASH, + paymentHash = SWAP_HOLD_HASH, + reason = PaymentFailureReason.ROUTE_NOT_FOUND, + ), + ) + advanceUntilIdle() + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + assertTrue(claimCancelled) + assertNull(sut.successSendUiState.value.paymentHashOrTxId) + } + @Test fun `swap route claim failure shows no success`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) @@ -16979,6 +17039,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private suspend fun TestScope.openSwapRoutedContactPayment( quote: Result = Result.success(PaykitRoute.Swap(swapRouteQuote())), + endpoints: List = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), ) { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).thenReturn(quote) @@ -16992,7 +17053,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.openContactPayment( paymentRequest = REGTEST_ADDRESS, publicKey = testPublicKey, - endpoints = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), + endpoints = endpoints, ) advanceUntilIdle() sut.setSendEvent(SendEvent.AmountChange(SWAP_DELIVERED_SATS)) From 5548350ab8b522615561ef68b4006930583e2184 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 23:11:28 +0100 Subject: [PATCH 12/24] fix: keep a swap quote matched to the amount and fee shown A new amount clears the quote, a send whose quote is missing or for another amount returns to Amount before anything is paid, and picking Spending again shows the quoted fee. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 20 ++++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 41 +++++++++++++++++++ 2 files changed, 60 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 c2d3e4f8b8..377f0df3e6 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4204,10 +4204,18 @@ class AppViewModel @Inject constructor( private suspend fun onAmountChange(amount: ULong) { if (_sendUiState.value.paykitUsesUsdt || !_sendUiState.value.isAmountEditable) return _sendUiState.update { + // A quote is for the amount it was made for, so a new amount needs a new quote. + val staleQuote = it.paykitSwapRoute?.quote?.let { quote -> quote.deliveredSat != amount } == true it.copy( amount = amount, isAmountInputValid = validateAmount(amount), confirmedWarnings = persistentListOf(), + paykitSwapRoute = if (staleQuote) { + it.paykitSwapRoute.copy(quote = null, providerName = null) + } else { + it.paykitSwapRoute + }, + lightningFeeSats = if (staleQuote) 0 else it.lightningFeeSats, ) } updateCanSwitchWallet() @@ -4450,7 +4458,8 @@ class AppViewModel @Inject constructor( hardwareWalletId = null, hardwareWalletName = null, hardwareAvailableSats = 0uL, - lightningFeeSats = 0, + // A quoted swap route pays the quote's fee on Spending. + lightningFeeSats = it.paykitSwapRoute?.quote?.totalFeeSat?.toLong() ?: 0, selectedUtxos = null, confirmedWarnings = persistentListOf(), isAmountInputValid = validateAmount(it.amount, SendMethod.LIGHTNING), @@ -6279,6 +6288,15 @@ class AppViewModel @Inject constructor( delay(SCREEN_TRANSITION_DELAY) // wait for screen transitions when applicable if (!validateIncomingPaymentRequest(contactPaymentContext)) return + _sendUiState.value.activePaykitSwapRoute?.let { route -> + if (route.quote?.deliveredSat == _sendUiState.value.amount) return@let + // The route must be quoted for the confirmed amount before it is committed. + _sendUiState.update { + it.copy(paykitSwapRoute = route.copy(quote = null, providerName = null), lightningFeeSats = 0) + } + setSendEffect(SendEffect.NavigateToAmount) + return + } val incomingPaymentRequest = contactPaymentContext?.incomingPaymentRequest val proofPreparation = preparePaymentProof(incomingPaymentRequest) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index b457ea40d2..fc03594eae 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -17037,6 +17037,47 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) } + @Test + fun `swap route amount edited while quoting needs a new quote before paying`() = test { + val quoted = CompletableDeferred>() + openSwapRoutedContactPayment() + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quoted.await() } + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + sut.setSendEvent(SendEvent.AmountChange(2_000uL)) + quoted.complete(Result.success(PaykitRoute.Swap(swapRouteQuote()))) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + assertEquals(2_000uL, sut.sendUiState.value.amount) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + confirmCurrentPayment() + assertEquals(SendEffect.NavigateToAmount, awaitItem()) + } + verify(pubkySwapsRouteRepo, never()).commit(any()) + } + + @Test + fun `swap route fee shows again when confirm returns to spending`() = test { + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + sut.setSendEvent(SendEvent.PaymentMethodSwitch) + advanceUntilIdle() + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + sut.setSendEvent(SendEvent.PaymentMethodSwitch) + advanceUntilIdle() + cancelAndIgnoreRemainingEvents() + } + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + assertEquals(swapRouteQuote(), sut.sendUiState.value.activePaykitSwapRoute?.quote) + assertEquals(swapRouteQuote().totalFeeSat.toLong(), sut.sendUiState.value.lightningFeeSats) + } + private suspend fun TestScope.openSwapRoutedContactPayment( quote: Result = Result.success(PaykitRoute.Swap(swapRouteQuote())), endpoints: List = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), From 712cc055ef079ac3ccf8dd83dea9c9cebc2b8093 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 23:59:59 +0100 Subject: [PATCH 13/24] fix: keep a late swap result on its own payment The paying contact is bound to the hold payment before paying, and a claim or failure that lands after the sheet was dismissed shows a toast instead of touching the send that is open. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 31 +++++-- .../viewmodels/AppViewModelSendFlowTest.kt | 81 +++++++++++++++++++ 2 files changed, 104 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 377f0df3e6..eb66066787 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6782,10 +6782,12 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, allowanceAttemptId: String?, ) { + val sendGeneration = sendStateGeneration + val isSendCurrent = { sendGeneration == sendStateGeneration } val payment = pubkySwapsRouteRepo.commit(quote.quoteId).getOrElse { releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) + handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) return } Logger.info("Committed Pubky Swaps route '${payment.swapId}' to '${payment.destinationAddress}'", context = TAG) @@ -6796,7 +6798,7 @@ class AppViewModel @Inject constructor( }.getOrElse { releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) + handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) return } // Only the claim finishes the send: the hold invoice's own success event is skipped as already processed. @@ -6813,12 +6815,15 @@ class AppViewModel @Inject constructor( } } try { + contactPaymentContext?.let { + synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } + } // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).getOrElse { if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext) + handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) return } val claimTxid = awaitSwapClaim(payment, holdFailure).getOrElse { @@ -6828,13 +6833,18 @@ class AppViewModel @Inject constructor( releasePrivatePaymentListIfNeeded(contactPaymentContext) return } - handlePaymentPreparationFailure(it, contactPaymentContext) + handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) return } finishManualAllowancePayment(allowanceAttemptId, succeeded = true) Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$claimTxid'", context = TAG) // The claim pays the contact's address: the wallet's own record of the payment is the hold invoice's debit. - syncContactForActivity(holdPaymentHash) + if (contactPaymentContext != null) syncContactForActivity(holdPaymentHash) + if (!isSendCurrent()) { + notifyPendingPaymentSucceeded() + return + } + synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } onSendSuccess( NewTransactionSheetDetails( type = NewTransactionSheetType.LIGHTNING, @@ -6846,6 +6856,7 @@ class AppViewModel @Inject constructor( ) } finally { holdFailure.cancel() + clearPendingContactPaymentContext(holdPaymentHash) } } @@ -8837,8 +8848,12 @@ class AppViewModel @Inject constructor( } } - private fun handlePaymentPreparationFailure(error: Throwable, contactPaymentContext: ContactPaymentContext?) { - if (contactPaymentContext?.isInitialSubscriptionPayment == true) { + private fun handlePaymentPreparationFailure( + error: Throwable, + contactPaymentContext: ContactPaymentContext?, + isSendCurrent: Boolean = true, + ) { + if (isSendCurrent && contactPaymentContext?.isInitialSubscriptionPayment == true) { setSendEffect( SendEffect.NavigateToError( error.toSendFailureDetails(context, _sendUiState.value.currentLightningPaymentRequest()) @@ -8846,7 +8861,7 @@ class AppViewModel @Inject constructor( ) } else { toast(error) - hideSheet() + if (isSendCurrent) hideSheet() } if (contactPaymentContext?.incomingPaymentRequest != null) { viewModelScope.launch { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index fc03594eae..5a7ab135fc 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -261,8 +261,10 @@ import kotlin.test.assertFalse import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertSame import kotlin.test.assertTrue import kotlin.time.Clock +import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime import kotlin.time.Instant @@ -16965,6 +16967,84 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.successSendUiState.value.paymentHashOrTxId) } + @Test + fun `swap route claim after dismissal leaves the next contact send untouched`() = test { + val claim = CompletableDeferred>() + val contactPaymentContextB = startSwapRoutedPaymentThenOpenNextContactSend(claim) + + sut.sendEffect.test { + claim.complete(Result.success(SWAP_CLAIM_TXID)) + advanceBeforeHoldWatchDeadline() + expectNoEvents() + } + assertSame(contactPaymentContextB, activeContactPaymentContext()) + assertNull(sut.successSendUiState.value.paymentHashOrTxId) + verify(toastManager).enqueue(check { assertEquals("PendingPaymentSucceededToast", it.testTag) }) + verify(activityRepo).setContact( + contactPublicKey = eq(testPublicKey), + forPaymentId = eq(SWAP_HOLD_HASH), + syncLdkPayments = any(), + walletId = any(), + ) + verify(activityRepo, never()).setContact( + contactPublicKey = eq(SWAP_NEXT_CONTACT_PUBLIC_KEY), + forPaymentId = any(), + syncLdkPayments = any(), + walletId = any(), + ) + } + + @Test + fun `swap route claim failure after dismissal keeps the next send open`() = test { + val claim = CompletableDeferred>() + val contactPaymentContextB = startSwapRoutedPaymentThenOpenNextContactSend(claim) + val sheetB = sut.currentSheet.value + + claim.complete(Result.failure(AppError("refunded"))) + advanceBeforeHoldWatchDeadline() + + assertTrue(sheetB is Sheet.Send) + assertSame(sheetB, sut.currentSheet.value) + assertSame(contactPaymentContextB, activeContactPaymentContext()) + } + + private suspend fun TestScope.startSwapRoutedPaymentThenOpenNextContactSend( + claim: CompletableDeferred>, + ): ContactPaymentContext? { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + openSwapRoutedContactPayment() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + sut.setSendEvent(SendEvent.SwipeToPay) + advanceBeforeHoldWatchDeadline() + sut.setSendEvent(SendEvent.PayConfirmed) + advanceBeforeHoldWatchDeadline() + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) + sut.hideSheet() + advanceBeforeHoldWatchDeadline() + sut.openContactPayment( + paymentRequest = REGTEST_ADDRESS, + publicKey = SWAP_NEXT_CONTACT_PUBLIC_KEY, + endpoints = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), + ) + advanceBeforeHoldWatchDeadline() + return activeContactPaymentContext().also { + assertEquals(SWAP_NEXT_CONTACT_PUBLIC_KEY, it?.publicKey) + } + } + + private fun TestScope.advanceBeforeHoldWatchDeadline() { + advanceTimeBy(1.days) + runCurrent() + } + @Test fun `swap route answered direct switches the payment to savings`() = test { openSwapRoutedContactPayment( @@ -18604,5 +18684,6 @@ private const val SWAP_HOLD_HASH = "010203" private const val SWAP_CLAIM_TXID = "claimtxid" private const val SWAP_DELIVERED_SATS = 20_000uL private const val SWAP_DEBIT_SATS = 20_100uL +private const val SWAP_NEXT_CONTACT_PUBLIC_KEY = "pubky8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo" private const val OWN_NODE_ID = "02abababababababababababababababababababababababababababababababab" private const val FOREIGN_NODE_ID = "03cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" From 4b8c8df034bc355c4be68d160c68f30f32237218 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 00:16:03 +0100 Subject: [PATCH 14/24] fix: retry a failed swap payment with a fresh quote Any failure after a swap-routed payment starts clears its quote, and the error screen retries from the amount, where Continue asks for a new one. The hold-failure test now exercises the failure event instead of the watch's timeout. --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 6 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 27 ++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 76 +++++++++++++++---- 3 files changed, 91 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 7906998ac3..cb31798d0a 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -333,6 +333,7 @@ fun SendSheet( is SendEffect.NavigateToError -> navController.navigateTo( SendRoute.errorFromFailure( failure = it.failure, + retryRoute = it.retryRoute, ) ) } @@ -1002,6 +1003,7 @@ sealed interface SendRoute { @Serializable enum class SendRetryRoute(val sendRoute: SendRoute) { + Amount(SendRoute.Amount), Confirm(SendRoute.Confirm), QuickPay(SendRoute.QuickPay), } @@ -1009,7 +1011,7 @@ enum class SendRetryRoute(val sendRoute: SendRoute) { private fun SendRoute.Error.failureTitle(payMethod: SendMethod): Int { return when (retryRoute) { SendRetryRoute.QuickPay -> R.string.wallet__send_instant_failed - SendRetryRoute.Confirm -> when (payMethod) { + SendRetryRoute.Amount, SendRetryRoute.Confirm -> when (payMethod) { SendMethod.LIGHTNING -> R.string.wallet__send_instant_failed SendMethod.ONCHAIN -> R.string.wallet__send_error_tx_failed } @@ -1028,7 +1030,7 @@ private fun SendRoute.Error.shouldResetRoutingCaches(routingCacheResetAttempted: private fun SendRoute.Error.supportPaymentMethod(sendPayMethod: SendMethod): SendMethod { return when (retryRoute) { SendRetryRoute.QuickPay -> SendMethod.LIGHTNING - SendRetryRoute.Confirm -> sendPayMethod + SendRetryRoute.Amount, SendRetryRoute.Confirm -> sendPayMethod } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index eb66066787..7ef9971d47 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -252,6 +252,7 @@ import to.bitkit.ui.pushNotification import to.bitkit.ui.screens.wallets.receive.ReceiveRoute import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.ui.shared.toast.ToastQueueManager +import to.bitkit.ui.sheets.SendRetryRoute import to.bitkit.ui.sheets.SendRoute import to.bitkit.ui.sheets.hardware.HardwareRoute import to.bitkit.ui.theme.TRANSITION_SCREEN_MS @@ -2855,10 +2856,16 @@ class AppViewModel @Inject constructor( setSendEffect( SendEffect.NavigateToError( - reason.toSendFailureDetails( + failure = reason.toSendFailureDetails( context = context, paymentRequest = _sendUiState.value.currentLightningPaymentRequest(), - ) + ), + // The swap provider consumed the committed quote, so a retry re-quotes from the amount. + retryRoute = if (_sendUiState.value.activePaykitSwapRoute != null) { + SendRetryRoute.Amount + } else { + SendRetryRoute.Confirm + }, ) ) return true @@ -6785,6 +6792,7 @@ class AppViewModel @Inject constructor( val sendGeneration = sendStateGeneration val isSendCurrent = { sendGeneration == sendStateGeneration } val payment = pubkySwapsRouteRepo.commit(quote.quoteId).getOrElse { + clearSwapRouteQuote(isSendCurrent()) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) @@ -6796,6 +6804,7 @@ class AppViewModel @Inject constructor( "Swap hold invoice is not a Lightning invoice" }.paymentHash.toHex() }.getOrElse { + clearSwapRouteQuote(isSendCurrent()) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) @@ -6820,6 +6829,7 @@ class AppViewModel @Inject constructor( } // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).getOrElse { + clearSwapRouteQuote(isSendCurrent()) if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) @@ -6827,6 +6837,7 @@ class AppViewModel @Inject constructor( return } val claimTxid = awaitSwapClaim(payment, holdFailure).getOrElse { + clearSwapRouteQuote(isSendCurrent()) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) if (it is LightningPaymentFailedError) { if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) @@ -6860,6 +6871,13 @@ class AppViewModel @Inject constructor( } } + private fun clearSwapRouteQuote(isSendCurrent: Boolean) { + if (!isSendCurrent) return + _sendUiState.update { + it.copy(paykitSwapRoute = it.paykitSwapRoute?.copy(quote = null, providerName = null), lightningFeeSats = 0) + } + } + private suspend fun awaitSwapClaim( payment: PubkySwapRoutePayment, holdFailure: Deferred, @@ -9444,7 +9462,10 @@ sealed class SendEffect { data object NavigateToContacts : SendEffect() data object NavigateToComingSoon : SendEffect() data object PaymentSuccess : SendEffect() - data class NavigateToError(val failure: SendFailureDetails) : SendEffect() + data class NavigateToError( + val failure: SendFailureDetails, + val retryRoute: SendRetryRoute = SendRetryRoute.Confirm, + ) : SendEffect() data class NavigateToPending( val paymentHash: String, val amount: Long, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 5a7ab135fc..e872970c55 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -241,6 +241,7 @@ import to.bitkit.ui.components.Sheet import to.bitkit.ui.components.SubscriptionRoute import to.bitkit.ui.components.TimedSheetType import to.bitkit.ui.shared.toast.ToastQueueManager +import to.bitkit.ui.sheets.SendRetryRoute import to.bitkit.ui.sheets.SendRoute import to.bitkit.ui.sheets.hardware.HardwareRoute import to.bitkit.ui.theme.TRANSITION_SCREEN_MS @@ -258,6 +259,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 @@ -16933,21 +16935,57 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.AmountContinue) advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) - confirmCurrentPayment() - emitNodeEvent( - Event.PaymentFailed( - paymentId = SWAP_HOLD_HASH, - paymentHash = SWAP_HOLD_HASH, - reason = PaymentFailureReason.ROUTE_NOT_FOUND, - ), - ) - advanceUntilIdle() + confirmSwapRoutedPayment() + assertFalse(claimCancelled) + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() assertTrue(awaitItem() is SendEffect.NavigateToError) } assertTrue(claimCancelled) assertNull(sut.successSendUiState.value.paymentHashOrTxId) } + @Test + fun `swap route hold payment failure retries from the amount without recommitting the quote`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() + assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + + sut.setSendEvent(SendEvent.ClearPayConfirmation) + confirmSwapRoutedPayment() + assertEquals(SendEffect.NavigateToAmount, awaitItem()) + } + verify(pubkySwapsRouteRepo, times(1)).commit(SWAP_QUOTE_ID) + } + + @Test + fun `swap route refused commit clears the quote`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.failure(AppError("quote_expired"))) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + cancelAndIgnoreRemainingEvents() + } + assertNotNull(sut.sendUiState.value.paykitSwapRoute) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + } + @Test fun `swap route claim failure shows no success`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) @@ -17020,10 +17058,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.AmountContinue) advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) - sut.setSendEvent(SendEvent.SwipeToPay) - advanceBeforeHoldWatchDeadline() - sut.setSendEvent(SendEvent.PayConfirmed) - advanceBeforeHoldWatchDeadline() + confirmSwapRoutedPayment() cancelAndIgnoreRemainingEvents() } verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) @@ -17045,6 +17080,21 @@ class AppViewModelSendFlowTest : BaseUnitTest() { runCurrent() } + private fun TestScope.confirmSwapRoutedPayment() { + sut.setSendEvent(SendEvent.SwipeToPay) + advanceBeforeHoldWatchDeadline() + sut.setSendEvent(SendEvent.PayConfirmed) + advanceBeforeHoldWatchDeadline() + } + + private suspend fun emitSwapHoldPaymentFailed() = emitNodeEvent( + Event.PaymentFailed( + paymentId = SWAP_HOLD_HASH, + paymentHash = SWAP_HOLD_HASH, + reason = PaymentFailureReason.ROUTE_NOT_FOUND, + ), + ) + @Test fun `swap route answered direct switches the payment to savings`() = test { openSwapRoutedContactPayment( From 47aff38d3d8ed496c422bb7a485cd64a78f1aa5b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 02:25:26 +0100 Subject: [PATCH 15/24] fix: keep swap sends on their own payment A dismissed swap send releases the confirm guard, and its commit, hold hash and tags no longer reach the next send. A result for a payment edited from Amount in the same sheet is no longer applied to it. A claim wait that runs out shows the send as pending on the hold payment and keeps advancing the swap, instead of offering a retry that could pay the contact twice. Drops the changelog entry: the routes are behind a regtest debug flag. --- .../repositories/PubkySwapsRouteRepo.kt | 16 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 79 +++++++--- .../repositories/PubkySwapsRouteRepoTest.kt | 21 +++ .../viewmodels/AppViewModelSendFlowTest.kt | 145 +++++++++++++++++- changelog.d/next/1732.added.md | 1 - 5 files changed, 234 insertions(+), 28 deletions(-) delete mode 100644 changelog.d/next/1732.added.md diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index bd80792412..0af2e6eace 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -150,9 +150,15 @@ class PubkySwapsRouteRepo @Inject constructor( var lastFailure: Throwable? = null return withTimeoutOrNull(timeout) { pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } - }?.onSuccess { - scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } - } ?: Result.failure(lastFailure ?: AppError("Swap '$swapId' not claimed yet")) + }?.onSuccess { advanceInBackground(swapId) } ?: run { + // The provider may still settle the hold payment, so the swap keeps advancing towards its claim. + advanceInBackground(swapId) + Result.failure(PubkySwapClaimTimeoutException(swapId, lastFailure)) + } + } + + private fun advanceInBackground(swapId: String) { + scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } } private suspend fun awaitConfirmation(swapId: String) { @@ -204,3 +210,7 @@ data class RestoredPubkySwaps( val restored: List, val known: List, ) + +/** A claim wait that ran out with the swap still open: its hold payment may yet settle. */ +class PubkySwapClaimTimeoutException(swapId: String, cause: Throwable?) : + AppError("Swap '$swapId' not claimed yet", cause) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 7ef9971d47..f943242a6a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -221,6 +221,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.PubkySwapClaimTimeoutException import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.PublicPaykitPaymentResult import to.bitkit.repositories.PublicPaykitRepo @@ -565,6 +566,9 @@ class AppViewModel @Inject constructor( private var isPaymentRequestIdentityActivating = false private var isSubmittingPaymentRequest = false private var isSoftwarePaymentSubmissionActive = false + + // The confirmed send that holds the submission guard; dismissing that send releases the guard for the next one. + private var confirmedPaymentSubmission: Any? = null private val activePaymentSubmissions = mutableSetOf() private var paykitPaymentRequestPollingJob: Job? = null private var paykitSessionRestoreRetryJob: Job? = null @@ -6790,12 +6794,20 @@ class AppViewModel @Inject constructor( allowanceAttemptId: String?, ) { val sendGeneration = sendStateGeneration - val isSendCurrent = { sendGeneration == sendStateGeneration } + // A payment edited from Amount in the same sheet holds a fresh quote or none, so the result is no longer its. + val isSendCurrent = { + sendGeneration == sendStateGeneration && + _sendUiState.value.paykitSwapRoute?.quote?.quoteId == quote.quoteId + } + // Read before the commit: a commit returning after dismissal must not take the next send's tags or address. + val tags = _sendUiState.value.selectedTags + val address = _sendUiState.value.address val payment = pubkySwapsRouteRepo.commit(quote.quoteId).getOrElse { - clearSwapRouteQuote(isSendCurrent()) + val isCurrent = isSendCurrent() + clearSwapRouteQuote(isCurrent) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) + handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) return } Logger.info("Committed Pubky Swaps route '${payment.swapId}' to '${payment.destinationAddress}'", context = TAG) @@ -6804,17 +6816,22 @@ class AppViewModel @Inject constructor( "Swap hold invoice is not a Lightning invoice" }.paymentHash.toHex() }.getOrElse { - clearSwapRouteQuote(isSendCurrent()) + val isCurrent = isSendCurrent() + clearSwapRouteQuote(isCurrent) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) + handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) return } // Only the claim finishes the send: the hold invoice's own success event is skipped as already processed. synchronized(processedPaymentsLock) { processedPayments.add(holdPaymentHash) } // A failed hold payment closes the send through the node's failure event, like a regular Lightning send. - _sendUiState.update { it.copy(paykitSwapRoute = it.paykitSwapRoute?.copy(holdPaymentHash = holdPaymentHash)) } - val tagsSaved = saveSwapRouteTags(holdPaymentHash) + if (isSendCurrent()) { + _sendUiState.update { + it.copy(paykitSwapRoute = it.paykitSwapRoute?.copy(holdPaymentHash = holdPaymentHash)) + } + } + val tagsSaved = saveSwapRouteTags(holdPaymentHash, tags, address) val holdFailure = viewModelScope.async(start = CoroutineStart.UNDISPATCHED) { lightningRepo.nodeEvents.watchUntil { when (it) { @@ -6823,28 +6840,43 @@ class AppViewModel @Inject constructor( } } } + var keepContactPaymentContext = false try { contactPaymentContext?.let { synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } } // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).getOrElse { - clearSwapRouteQuote(isSendCurrent()) + val isCurrent = isSendCurrent() + clearSwapRouteQuote(isCurrent) if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) + handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) return } val claimTxid = awaitSwapClaim(payment, holdFailure).getOrElse { - clearSwapRouteQuote(isSendCurrent()) + if (it is PubkySwapClaimTimeoutException) { + // The provider may still settle the hold payment, so a retry could pay the contact twice: the + // send waits as pending on the hold payment while the swap keeps advancing in the background. + Logger.warn("Pubky Swaps route '${payment.swapId}' outcome unknown", it, context = TAG) + keepContactPaymentContext = true + pendingPaymentRepo.track(holdPaymentHash) + if (isSendCurrent()) { + synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } + setSendEffect(SendEffect.NavigateToPending(holdPaymentHash, payment.deliveredSat.toLong())) + } + return + } + val isCurrent = isSendCurrent() + clearSwapRouteQuote(isCurrent) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) if (it is LightningPaymentFailedError) { if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) return } - handlePaymentPreparationFailure(it, contactPaymentContext, isSendCurrent()) + handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) return } finishManualAllowancePayment(allowanceAttemptId, succeeded = true) @@ -6867,7 +6899,7 @@ class AppViewModel @Inject constructor( ) } finally { holdFailure.cancel() - clearPendingContactPaymentContext(holdPaymentHash) + if (!keepContactPaymentContext) clearPendingContactPaymentContext(holdPaymentHash) } } @@ -6891,13 +6923,12 @@ class AppViewModel @Inject constructor( }.also { claim.cancel() } } - private suspend fun saveSwapRouteTags(paymentHash: String): Boolean { - val tags = _sendUiState.value.selectedTags + private suspend fun saveSwapRouteTags(paymentHash: String, tags: List, address: String): Boolean { if (tags.isEmpty()) return false return preActivityMetadataRepo.savePreActivityMetadata( id = paymentHash, paymentHash = paymentHash, - address = _sendUiState.value.address, + address = address, isReceive = false, tags = tags, ).isSuccess @@ -7984,6 +8015,8 @@ class AppViewModel @Inject constructor( } if (_currentSheet.value is Sheet.Send) { sendStateGeneration++ + // A payment still running for the dismissed send, like a swap awaiting its claim, must not block the next. + if (confirmedPaymentSubmission != null) releaseConfirmedPaymentSubmission() cancelHardwarePaymentRequestIfNeeded() resetQuickPay() quickPayRepo.detachAll() @@ -8188,11 +8221,11 @@ class AppViewModel @Inject constructor( private fun onConfirmPay() { Logger.debug("Payment checks confirmed, proceeding…", context = TAG) - if (isSubmittingPaymentRequest || isSoftwarePaymentSubmissionActive || - !_sendUiState.value.isHardwareFeeReady - ) { + if (isSubmittingPaymentRequest || isSoftwarePaymentSubmissionActive) { + _sendUiState.update { it.copy(shouldConfirmPay = false) } return } + if (!_sendUiState.value.isHardwareFeeReady) return val contactPaymentContext = synchronized(contactPaymentContextLock) { activeContactPaymentContext } if (_sendUiState.value.isPaymentRequest && contactPaymentContext?.incomingPaymentRequest == null) { @@ -8207,6 +8240,7 @@ class AppViewModel @Inject constructor( return } isSoftwarePaymentSubmissionActive = true + val submission = Any().also { confirmedPaymentSubmission = it } viewModelScope.launch(start = CoroutineStart.UNDISPATCHED) { val finishSubmission = beginPaymentSubmission() try { @@ -8214,12 +8248,17 @@ class AppViewModel @Inject constructor( proceedWithPayment(contactPaymentContext) } finally { finishSubmission() - isSubmittingPaymentRequest = false - isSoftwarePaymentSubmissionActive = false + if (confirmedPaymentSubmission === submission) releaseConfirmedPaymentSubmission() } } } + private fun releaseConfirmedPaymentSubmission() { + confirmedPaymentSubmission = null + isSubmittingPaymentRequest = false + isSoftwarePaymentSubmissionActive = false + } + override fun onCleared() { isSubmittingPaymentRequest = false } diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index afdb692722..adc7ed4e5f 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -3,19 +3,24 @@ package to.bitkit.repositories import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.PubkySwapRouteStatus import com.synonym.bitkitcore.pubkySwapsAdvance +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Before import org.junit.Test import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.mock +import org.mockito.kotlin.times import org.mockito.kotlin.whenever import to.bitkit.data.keychain.Keychain import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import kotlin.test.assertEquals +import kotlin.test.assertIs import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds class PubkySwapsRouteRepoTest : BaseUnitTest() { companion object { @@ -63,6 +68,22 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { assertEquals(Result.success(CLAIM_TXID), txid) } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `awaitClaim running out leaves the swap open and keeps advancing it`() = test { + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) + .thenReturn(status(PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID))) + + val result = sut.awaitClaim(SWAP_ID, timeout = 1.seconds) + advanceUntilIdle() + + assertIs(result.exceptionOrNull()) + core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, times(2)) + } + } + private suspend fun advancing(vararg answers: Any, block: suspend () -> T): T = mockStatic(CORE).use { core -> var stub = core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index e872970c55..d14f7d7481 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -208,6 +208,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.PubkySwapClaimTimeoutException import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.PublicPaykitPaymentResult import to.bitkit.repositories.PublicPaykitRepo @@ -11759,8 +11760,6 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.hideSheet() runCurrent() assertTrue(paymentSubmissionActive.value) - sut.setSendEvent(SendEvent.PayConfirmed) - runCurrent() release.complete(Unit) runCurrent() assertFalse(paymentSubmissionActive.value) @@ -17005,6 +17004,61 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.successSendUiState.value.paymentHashOrTxId) } + @Test + fun `swap route claim leaves a payment edited in the same sheet untouched`() = test { + val claim = CompletableDeferred>() + val editedQuote = swapRouteQuote().copy(quoteId = "edited-quote", deliveredSat = SWAP_DELIVERED_SATS + 1_000u) + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + openSwapRoutedContactPayment() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Swap(editedQuote))) + sut.setSendEvent(SendEvent.AmountChange(editedQuote.deliveredSat)) + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals("edited-quote", sut.sendUiState.value.paykitSwapRoute?.quote?.quoteId) + cancelAndIgnoreRemainingEvents() + } + + sut.sendEffect.test { + claim.complete(Result.success(SWAP_CLAIM_TXID)) + advanceBeforeHoldWatchDeadline() + expectNoEvents() + } + assertEquals("edited-quote", sut.sendUiState.value.paykitSwapRoute?.quote?.quoteId) + assertNull(sut.successSendUiState.value.paymentHashOrTxId) + verify(toastManager).enqueue(check { assertEquals("PendingPaymentSucceededToast", it.testTag) }) + } + + @Test + fun `swap route claim wait running out shows the send as pending`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())) + .thenReturn(Result.failure(PubkySwapClaimTimeoutException(SWAP_ID, AppError("awaiting lockup")))) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmCurrentPayment() + assertEquals(SendEffect.NavigateToPending(SWAP_HOLD_HASH, SWAP_DELIVERED_SATS.toLong()), awaitItem()) + expectNoEvents() + } + verify(pendingPaymentRepo).track(SWAP_HOLD_HASH) + verify(preActivityMetadataRepo, never()).deletePreActivityMetadata(SWAP_HOLD_HASH) + assertNull(sut.successSendUiState.value.paymentHashOrTxId) + } + @Test fun `swap route claim after dismissal leaves the next contact send untouched`() = test { val claim = CompletableDeferred>() @@ -17046,6 +17100,87 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertSame(contactPaymentContextB, activeContactPaymentContext()) } + @Test + fun `swap route commit after dismissal leaves its hold payment off the next send`() = test { + val commit = CompletableDeferred>() + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).doSuspendableAnswer { commit.await() } + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + cancelAndIgnoreRemainingEvents() + } + sut.hideSheet() + advanceBeforeHoldWatchDeadline() + openSwapRoutedContactPayment() + val sheetB = sut.currentSheet.value + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + commit.complete(Result.success(swapRoutePayment())) + advanceBeforeHoldWatchDeadline() + assertNotNull(sut.sendUiState.value.paykitSwapRoute) + assertNull(sut.sendUiState.value.paykitSwapRoute?.holdPaymentHash) + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() + expectNoEvents() + } + assertTrue(sheetB is Sheet.Send) + assertSame(sheetB, sut.currentSheet.value) + } + + @Test + fun `swap route claim wait after dismissal lets the next send pay`() = test { + val claim = CompletableDeferred>() + val commitB = CompletableDeferred>() + var commits = 0 + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).doSuspendableAnswer { + if (++commits == 1) Result.success(swapRoutePayment()) else commitB.await() + } + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + openSwapRoutedContactPayment() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) + sut.hideSheet() + advanceBeforeHoldWatchDeadline() + openSwapRoutedContactPayment(settle = { advanceBeforeHoldWatchDeadline() }) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + // The first payment still awaits its claim. + assertTrue(paymentSubmissionActive.value) + confirmSwapRoutedPayment() + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) + assertFalse(sut.sendUiState.value.shouldConfirmPay) + + // The first payment ending must not lift the guard of the second while it still pays. + claim.complete(Result.success(SWAP_CLAIM_TXID)) + advanceBeforeHoldWatchDeadline() + sut.setSendEvent(SendEvent.PayConfirmed) + advanceBeforeHoldWatchDeadline() + verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) + assertFalse(sut.sendUiState.value.shouldConfirmPay) + } + private suspend fun TestScope.startSwapRoutedPaymentThenOpenNextContactSend( claim: CompletableDeferred>, ): ContactPaymentContext? { @@ -17211,6 +17346,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private suspend fun TestScope.openSwapRoutedContactPayment( quote: Result = Result.success(PaykitRoute.Swap(swapRouteQuote())), endpoints: List = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), + // `advanceUntilIdle` fires the hold watch's timer, which ends a swap payment still awaiting its claim. + settle: TestScope.() -> Unit = { advanceUntilIdle() }, ) { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).thenReturn(quote) @@ -17226,9 +17363,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { publicKey = testPublicKey, endpoints = endpoints, ) - advanceUntilIdle() + settle() sut.setSendEvent(SendEvent.AmountChange(SWAP_DELIVERED_SATS)) - advanceUntilIdle() + settle() } private fun swapRouteQuote() = PubkySwapRouteQuote( 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. From bc8f3e8c6b7f6020a0e75f352f643661c64634fe Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 02:55:21 +0100 Subject: [PATCH 16/24] fix: wait for a swap claim outside the send submission Once the hold invoice is paid, the claim wait runs on its own, so a send re-quoted in the same sheet can pay and backups and Paykit background work go on. A re-quote drops the committed hold hash, a pending swap reaches Bitcoin Sent when its hold payment settles, and its Retry re-quotes from Amount. --- .../java/to/bitkit/ui/sheets/SendSheet.kt | 1 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 74 +++++++++++++++---- .../viewmodels/AppViewModelSendFlowTest.kt | 54 +++++++++++++- 3 files changed, 110 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index cb31798d0a..43f9e1023e 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -328,6 +328,7 @@ fun SendSheet( observeResolution = it.observeResolution, isOnchain = it.isOnchain, refusalReason = it.refusalReason, + retryRoute = it.retryRoute, ) ) is SendEffect.NavigateToError -> navController.navigateTo( diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index f943242a6a..2bbf80a8e1 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -4222,7 +4222,7 @@ class AppViewModel @Inject constructor( isAmountInputValid = validateAmount(amount), confirmedWarnings = persistentListOf(), paykitSwapRoute = if (staleQuote) { - it.paykitSwapRoute.copy(quote = null, providerName = null) + it.paykitSwapRoute.copy(quote = null, providerName = null, holdPaymentHash = null) } else { it.paykitSwapRoute }, @@ -4688,9 +4688,11 @@ class AppViewModel @Inject constructor( } _sendUiState.update { it.copy( + // A new quote replaces the committed one, so its hold payment is no longer this send's. paykitSwapRoute = route.copy( quote = quote, providerName = pubkySwapsRouteRepo.providerContact(quote.providerPubky)?.name, + holdPaymentHash = null, ), lightningFeeSats = quote.totalFeeSat.toLong(), ) @@ -6840,31 +6842,62 @@ class AppViewModel @Inject constructor( } } } + contactPaymentContext?.let { + synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } + } + // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. + lightningRepo.payInvoice(payment.invoice).getOrElse { + holdFailure.cancel() + clearPendingContactPaymentContext(holdPaymentHash) + val isCurrent = isSendCurrent() + clearSwapRouteQuote(isCurrent) + if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) + return + } + // The claim wait can take minutes, so it runs outside this send's submission: other sends, backups and + // Paykit's background work go on meanwhile. + viewModelScope.launch { + finishSwapRoutedPayment( + SwapRoutedPayment(payment, holdPaymentHash, tagsSaved, contactPaymentContext, allowanceAttemptId), + holdFailure, + isSendCurrent, + ) + } + } + + private suspend fun finishSwapRoutedPayment( + swap: SwapRoutedPayment, + holdFailure: Deferred, + isSendCurrent: () -> Boolean, + ) { + val payment = swap.payment + val holdPaymentHash = swap.holdPaymentHash + val contactPaymentContext = swap.contactPaymentContext + val allowanceAttemptId = swap.allowanceAttemptId var keepContactPaymentContext = false try { - contactPaymentContext?.let { - synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } - } - // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. - lightningRepo.payInvoice(payment.invoice).getOrElse { - val isCurrent = isSendCurrent() - clearSwapRouteQuote(isCurrent) - if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) - return - } val claimTxid = awaitSwapClaim(payment, holdFailure).getOrElse { if (it is PubkySwapClaimTimeoutException) { // The provider may still settle the hold payment, so a retry could pay the contact twice: the // send waits as pending on the hold payment while the swap keeps advancing in the background. Logger.warn("Pubky Swaps route '${payment.swapId}' outcome unknown", it, context = TAG) keepContactPaymentContext = true + // The hold payment's own success event now finishes the send, through its pending resolution. + synchronized(processedPaymentsLock) { processedPayments.remove(holdPaymentHash) } pendingPaymentRepo.track(holdPaymentHash) if (isSendCurrent()) { synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } - setSendEffect(SendEffect.NavigateToPending(holdPaymentHash, payment.deliveredSat.toLong())) + setSendEffect( + SendEffect.NavigateToPending( + paymentHash = holdPaymentHash, + amount = payment.deliveredSat.toLong(), + // The provider consumed the committed quote, so a retry re-quotes from the amount. + retryRoute = SendRetryRoute.Amount, + ), + ) } return } @@ -6872,7 +6905,7 @@ class AppViewModel @Inject constructor( clearSwapRouteQuote(isCurrent) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) if (it is LightningPaymentFailedError) { - if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) + if (swap.tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) releasePrivatePaymentListIfNeeded(contactPaymentContext) return } @@ -9511,6 +9544,7 @@ sealed class SendEffect { val observeResolution: Boolean = true, val isOnchain: Boolean = false, val refusalReason: String? = null, + val retryRoute: SendRetryRoute = SendRetryRoute.Confirm, ) : SendEffect() } @@ -9558,6 +9592,14 @@ sealed interface SendEvent { data object Contacts : SendEvent } +private data class SwapRoutedPayment( + val payment: PubkySwapRoutePayment, + val holdPaymentHash: String, + val tagsSaved: Boolean, + val contactPaymentContext: ContactPaymentContext?, + val allowanceAttemptId: String?, +) + private class LightningPaymentFailedError( val reason: PaymentFailureReason?, val paymentRequest: String?, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d14f7d7481..11869c346f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -17051,12 +17051,61 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmCurrentPayment() - assertEquals(SendEffect.NavigateToPending(SWAP_HOLD_HASH, SWAP_DELIVERED_SATS.toLong()), awaitItem()) + assertEquals( + SendEffect.NavigateToPending( + SWAP_HOLD_HASH, + SWAP_DELIVERED_SATS.toLong(), + retryRoute = SendRetryRoute.Amount, + ), + awaitItem(), + ) expectNoEvents() } verify(pendingPaymentRepo).track(SWAP_HOLD_HASH) verify(preActivityMetadataRepo, never()).deletePreActivityMetadata(SWAP_HOLD_HASH) assertNull(sut.successSendUiState.value.paymentHashOrTxId) + + // The hold payment settling later finishes the pending send. + sut.onSendSuccess( + NewTransactionSheetDetails( + type = NewTransactionSheetType.LIGHTNING, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = SWAP_HOLD_HASH, + sats = SWAP_DELIVERED_SATS.toLong(), + ), + ) + assertEquals(SWAP_HOLD_HASH, sut.successSendUiState.value.paymentHashOrTxId) + } + + @Test + fun `swap route claim wait leaves a re-quoted send free to pay`() = test { + val claim = CompletableDeferred>() + val editedQuote = swapRouteQuote().copy(quoteId = "edited-quote", deliveredSat = SWAP_DELIVERED_SATS + 1_000u) + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(pubkySwapsRouteRepo.commit("edited-quote")).doSuspendableAnswer { awaitCancellation() } + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + openSwapRoutedContactPayment() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + // Backups and Paykit's background work do not wait for the claim. + assertFalse(paymentSubmissionActive.value) + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Swap(editedQuote))) + sut.setSendEvent(SendEvent.AmountChange(editedQuote.deliveredSat)) + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + // The first swap's hold payment is no longer this send's. + assertNull(sut.sendUiState.value.paykitSwapRoute?.holdPaymentHash) + confirmSwapRoutedPayment() + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo).commit("edited-quote") + assertFalse(sut.sendUiState.value.shouldConfirmPay) } @Test @@ -17164,8 +17213,6 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.AmountContinue) advanceBeforeHoldWatchDeadline() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) - // The first payment still awaits its claim. - assertTrue(paymentSubmissionActive.value) confirmSwapRoutedPayment() cancelAndIgnoreRemainingEvents() } @@ -17175,6 +17222,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { // The first payment ending must not lift the guard of the second while it still pays. claim.complete(Result.success(SWAP_CLAIM_TXID)) advanceBeforeHoldWatchDeadline() + verify(toastManager).enqueue(check { assertEquals("PendingPaymentSucceededToast", it.testTag) }) sut.setSendEvent(SendEvent.PayConfirmed) advanceBeforeHoldWatchDeadline() verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) From de7b78f61ed4be7441c3599a3ff839aac247c28a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 03:21:43 +0100 Subject: [PATCH 17/24] fix: wait on a swap's hold payment on the pending screen Once the hold invoice is paid, the send moves to Pending, which has no way back to Amount, so a fresh quote cannot pay the contact a second time. The hold payment settling or failing finishes the send; the claim wait only drives the swap, and a swap bitkit-core failed fails the pending send. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 102 ++++++++---------- .../viewmodels/AppViewModelSendFlowTest.kt | 55 ++++++---- 2 files changed, 77 insertions(+), 80 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 2bbf80a8e1..6d0912ecca 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6825,8 +6825,6 @@ class AppViewModel @Inject constructor( handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) return } - // Only the claim finishes the send: the hold invoice's own success event is skipped as already processed. - synchronized(processedPaymentsLock) { processedPayments.add(holdPaymentHash) } // A failed hold payment closes the send through the node's failure event, like a regular Lightning send. if (isSendCurrent()) { _sendUiState.update { @@ -6857,6 +6855,20 @@ class AppViewModel @Inject constructor( handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) return } + // The provider settles the hold payment once it sees the claim, so the send waits on it as a pending Lightning + // payment. Pending has no way back to Amount, where a fresh quote could pay the contact a second time. + pendingPaymentRepo.track(holdPaymentHash) + if (isSendCurrent()) { + synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } + setSendEffect( + SendEffect.NavigateToPending( + paymentHash = holdPaymentHash, + amount = payment.deliveredSat.toLong(), + // The provider consumed the committed quote, so a retry re-quotes from the amount. + retryRoute = SendRetryRoute.Amount, + ), + ) + } // The claim wait can take minutes, so it runs outside this send's submission: other sends, backups and // Paykit's background work go on meanwhile. viewModelScope.launch { @@ -6875,71 +6887,41 @@ class AppViewModel @Inject constructor( ) { val payment = swap.payment val holdPaymentHash = swap.holdPaymentHash - val contactPaymentContext = swap.contactPaymentContext - val allowanceAttemptId = swap.allowanceAttemptId - var keepContactPaymentContext = false - try { - val claimTxid = awaitSwapClaim(payment, holdFailure).getOrElse { - if (it is PubkySwapClaimTimeoutException) { - // The provider may still settle the hold payment, so a retry could pay the contact twice: the - // send waits as pending on the hold payment while the swap keeps advancing in the background. - Logger.warn("Pubky Swaps route '${payment.swapId}' outcome unknown", it, context = TAG) - keepContactPaymentContext = true - // The hold payment's own success event now finishes the send, through its pending resolution. - synchronized(processedPaymentsLock) { processedPayments.remove(holdPaymentHash) } - pendingPaymentRepo.track(holdPaymentHash) - if (isSendCurrent()) { - synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } - setSendEffect( - SendEffect.NavigateToPending( - paymentHash = holdPaymentHash, - amount = payment.deliveredSat.toLong(), - // The provider consumed the committed quote, so a retry re-quotes from the amount. - retryRoute = SendRetryRoute.Amount, - ), - ) - } - return - } - val isCurrent = isSendCurrent() - clearSwapRouteQuote(isCurrent) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - if (it is LightningPaymentFailedError) { - if (swap.tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) - releasePrivatePaymentListIfNeeded(contactPaymentContext) - return - } - handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) - return - } - finishManualAllowancePayment(allowanceAttemptId, succeeded = true) - Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$claimTxid'", context = TAG) - // The claim pays the contact's address: the wallet's own record of the payment is the hold invoice's debit. - if (contactPaymentContext != null) syncContactForActivity(holdPaymentHash) - if (!isSendCurrent()) { - notifyPendingPaymentSucceeded() - return - } - synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } - onSendSuccess( - NewTransactionSheetDetails( - type = NewTransactionSheetType.LIGHTNING, - direction = NewTransactionSheetDirection.SENT, - paymentHashOrTxId = holdPaymentHash, - sats = payment.deliveredSat.toLong(), - ), - allowDuplicateHash = true, - ) + // The send itself finishes on the hold payment's own events; this drives the swap to its claim. + val claim = try { + awaitSwapClaim(payment, holdFailure) } finally { holdFailure.cancel() - if (!keepContactPaymentContext) clearPendingContactPaymentContext(holdPaymentHash) + } + claim.onSuccess { + finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = true) + Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$it'", context = TAG) + }.onFailure { + if (it is PubkySwapClaimTimeoutException) { + // The provider may still settle the hold payment, so the send stays pending on it. + Logger.warn("Pubky Swaps route '${payment.swapId}' outcome unknown", it, context = TAG) + return + } + clearSwapRouteQuote(isSendCurrent()) + finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = false) + clearPendingContactPaymentContext(holdPaymentHash) + releasePrivatePaymentListIfNeeded(swap.contactPaymentContext) + if (swap.tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) + if (it is LightningPaymentFailedError) return + // A failed swap never reveals the preimage, so its hold payment cannot settle and a retry is safe. + Logger.error("Failed Pubky Swaps route '${payment.swapId}'", it, context = TAG) + pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(holdPaymentHash)) + if (shouldNotifyPendingResolution(holdPaymentHash)) notifyPendingPaymentFailed() } } private fun clearSwapRouteQuote(isSendCurrent: Boolean) { if (!isSendCurrent) return _sendUiState.update { - it.copy(paykitSwapRoute = it.paykitSwapRoute?.copy(quote = null, providerName = null), lightningFeeSats = 0) + it.copy( + paykitSwapRoute = it.paykitSwapRoute?.copy(quote = null, providerName = null, holdPaymentHash = null), + lightningFeeSats = 0, + ) } } @@ -8048,7 +8030,7 @@ class AppViewModel @Inject constructor( } if (_currentSheet.value is Sheet.Send) { sendStateGeneration++ - // A payment still running for the dismissed send, like a swap awaiting its claim, must not block the next. + // A payment still running for the dismissed send, like a slow swap commit, must not block the next. if (confirmedPaymentSubmission != null) releaseConfirmedPaymentSubmission() cancelHardwarePaymentRequestIfNeeded() resetQuickPay() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 11869c346f..dd8394cd07 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -16792,7 +16792,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `swap routed contact payment finishes once on the claim and tags the hold payment`() = test { + fun `swap routed contact payment waits on its hold payment and tags it`() = test { val activityV1 = mock { on { value } doReturn SWAP_DEBIT_SATS on { fee } doReturn 0u @@ -16800,7 +16800,6 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val activity = mock { on { v1 } doReturn activityV1 } whenever { activityRepo.findActivityByPaymentId(any(), any(), any(), any()) } .thenReturn(Result.success(activity)) - whenever(pendingPaymentRepo.isPending(SWAP_HOLD_HASH)).thenReturn(false) whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) @@ -16828,9 +16827,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) sut.addTagToSelected("rent") confirmCurrentPayment() - assertEquals(SendEffect.PaymentSuccess, awaitItem()) - assertEquals(SWAP_HOLD_HASH, sut.successSendUiState.value.paymentHashOrTxId) - assertEquals(NewTransactionSheetType.LIGHTNING, sut.successSendUiState.value.type) + assertEquals(swapHoldPending(), awaitItem()) emitNodeEvent( Event.PaymentSuccessful( @@ -16842,8 +16839,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) advanceUntilIdle() expectNoEvents() - assertEquals(SWAP_HOLD_HASH, sut.successSendUiState.value.paymentHashOrTxId) } + // The Pending screen shows Bitcoin Sent on the hold payment's resolution. + verify(pendingPaymentRepo).resolve(check { assertIs(it) }) verify(activityRepo).setContact( contactPublicKey = eq(testPublicKey), forPaymentId = eq(SWAP_HOLD_HASH), @@ -16935,12 +16933,14 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) assertFalse(claimCancelled) emitSwapHoldPaymentFailed() advanceBeforeHoldWatchDeadline() - assertTrue(awaitItem() is SendEffect.NavigateToError) + expectNoEvents() } assertTrue(claimCancelled) + verify(pendingPaymentRepo).resolve(check { assertIs(it) }) assertNull(sut.successSendUiState.value.paymentHashOrTxId) } @@ -16957,9 +16957,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmSwapRoutedPayment() + // The Pending screen hands its retry route to the error screen. + assertEquals(swapHoldPending(), awaitItem()) emitSwapHoldPaymentFailed() advanceBeforeHoldWatchDeadline() - assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) sut.setSendEvent(SendEvent.ClearPayConfirmation) @@ -16986,7 +16987,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `swap route claim failure shows no success`() = test { + fun `swap route claim failure fails the pending send`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) @@ -16998,9 +16999,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmCurrentPayment() + assertEquals(swapHoldPending(), awaitItem()) expectNoEvents() } - assertNull(sut.currentSheet.value) + verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Failure(SWAP_HOLD_HASH)) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) assertNull(sut.successSendUiState.value.paymentHashOrTxId) } @@ -17034,11 +17037,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } assertEquals("edited-quote", sut.sendUiState.value.paykitSwapRoute?.quote?.quoteId) assertNull(sut.successSendUiState.value.paymentHashOrTxId) - verify(toastManager).enqueue(check { assertEquals("PendingPaymentSucceededToast", it.testTag) }) } @Test - fun `swap route claim wait running out shows the send as pending`() = test { + fun `swap route claim wait running out keeps the send pending`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) @@ -17051,14 +17053,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmCurrentPayment() - assertEquals( - SendEffect.NavigateToPending( - SWAP_HOLD_HASH, - SWAP_DELIVERED_SATS.toLong(), - retryRoute = SendRetryRoute.Amount, - ), - awaitItem(), - ) + assertEquals(swapHoldPending(), awaitItem()) expectNoEvents() } verify(pendingPaymentRepo).track(SWAP_HOLD_HASH) @@ -17115,6 +17110,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.sendEffect.test { claim.complete(Result.success(SWAP_CLAIM_TXID)) + emitSwapHoldPaymentSuccessful() advanceBeforeHoldWatchDeadline() expectNoEvents() } @@ -17221,6 +17217,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { // The first payment ending must not lift the guard of the second while it still pays. claim.complete(Result.success(SWAP_CLAIM_TXID)) + emitSwapHoldPaymentSuccessful() advanceBeforeHoldWatchDeadline() verify(toastManager).enqueue(check { assertEquals("PendingPaymentSucceededToast", it.testTag) }) sut.setSendEvent(SendEvent.PayConfirmed) @@ -17270,6 +17267,21 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceBeforeHoldWatchDeadline() } + private fun swapHoldPending() = SendEffect.NavigateToPending( + paymentHash = SWAP_HOLD_HASH, + amount = SWAP_DELIVERED_SATS.toLong(), + retryRoute = SendRetryRoute.Amount, + ) + + private suspend fun emitSwapHoldPaymentSuccessful() = emitNodeEvent( + Event.PaymentSuccessful( + paymentId = SWAP_HOLD_HASH, + paymentHash = SWAP_HOLD_HASH, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + private suspend fun emitSwapHoldPaymentFailed() = emitNodeEvent( Event.PaymentFailed( paymentId = SWAP_HOLD_HASH, @@ -17399,6 +17411,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).thenReturn(quote) + // The swap send waits on its hold payment as a pending payment. + doAnswer { doReturn(true).whenever(pendingPaymentRepo).isPending(SWAP_HOLD_HASH) } + .whenever(pendingPaymentRepo).track(SWAP_HOLD_HASH) whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), ) From 8d40a8bfb5d5bfdb5b10603a2c405b6bea785aa9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 03:52:35 +0100 Subject: [PATCH 18/24] fix: keep a swap hold failed before its send returns on error --- .../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 6d0912ecca..919df72fb3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6857,8 +6857,10 @@ class AppViewModel @Inject constructor( } // The provider settles the hold payment once it sees the claim, so the send waits on it as a pending Lightning // payment. Pending has no way back to Amount, where a fresh quote could pay the contact a second time. - pendingPaymentRepo.track(holdPaymentHash) - if (isSendCurrent()) { + // A hold payment that failed before payInvoice returned already opened the error screen through its event. + val holdFailedEarly = holdFailure.isCompleted + if (!holdFailedEarly) pendingPaymentRepo.track(holdPaymentHash) + if (!holdFailedEarly && isSendCurrent()) { synchronized(contactPaymentContextLock) { activeContactPaymentContext = null } setSendEffect( SendEffect.NavigateToPending( diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index dd8394cd07..eb10b03b80 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -16944,6 +16944,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.successSendUiState.value.paymentHashOrTxId) } + @Test + fun `swap route hold payment failing before it returns stays on its failure`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())).doSuspendableAnswer { + emitSwapHoldPaymentFailed() + Result.success(SWAP_HOLD_HASH) + } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + val effects = cancelAndConsumeRemainingEvents() + assertFalse(swapHoldPending() in effects.map { (it as? app.cash.turbine.Event.Item)?.value }, "$effects") + } + verify(pendingPaymentRepo, never()).track(SWAP_HOLD_HASH) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + } + @Test fun `swap route hold payment failure retries from the amount without recommitting the quote`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) From c59a089db56e1ff3517c18b774a2c34ca1b744c2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 04:20:55 +0100 Subject: [PATCH 19/24] fix: open the error for a swap hold failure handled late --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 13 +++++++--- .../viewmodels/AppViewModelSendFlowTest.kt | 25 +++++++++++++++++++ 2 files changed, 35 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 919df72fb3..3e972b5a25 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6904,7 +6904,9 @@ class AppViewModel @Inject constructor( Logger.warn("Pubky Swaps route '${payment.swapId}' outcome unknown", it, context = TAG) return } - clearSwapRouteQuote(isSendCurrent()) + // A failed hold payment keeps its hash on the send: its own failure handler may still be on its way to + // the error screen and finds the send by that hash. + clearSwapRouteQuote(isSendCurrent(), keepHoldPaymentHash = it is LightningPaymentFailedError) finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = false) clearPendingContactPaymentContext(holdPaymentHash) releasePrivatePaymentListIfNeeded(swap.contactPaymentContext) @@ -6917,11 +6919,16 @@ class AppViewModel @Inject constructor( } } - private fun clearSwapRouteQuote(isSendCurrent: Boolean) { + private fun clearSwapRouteQuote(isSendCurrent: Boolean, keepHoldPaymentHash: Boolean = false) { if (!isSendCurrent) return _sendUiState.update { + val route = it.paykitSwapRoute it.copy( - paykitSwapRoute = it.paykitSwapRoute?.copy(quote = null, providerName = null, holdPaymentHash = null), + paykitSwapRoute = route?.copy( + quote = null, + providerName = null, + holdPaymentHash = route.holdPaymentHash.takeIf { keepHoldPaymentHash }, + ), lightningFeeSats = 0, ) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index eb10b03b80..070142aec4 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -16966,6 +16966,31 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) } + @Test + fun `swap route hold payment failing before it returns opens the error once its handler catches up`() = test { + val activityRefreshed = CompletableDeferred() + whenever { activityRepo.handlePaymentEvent(SWAP_HOLD_HASH) }.doSuspendableAnswer { activityRefreshed.await() } + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())).doSuspendableAnswer { + emitSwapHoldPaymentFailed() + Result.success(SWAP_HOLD_HASH) + } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + activityRefreshed.complete(Unit) + advanceBeforeHoldWatchDeadline() + assertIs(awaitItem()) + expectNoEvents() + } + verify(pendingPaymentRepo, never()).track(SWAP_HOLD_HASH) + } + @Test fun `swap route hold payment failure retries from the amount without recommitting the quote`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) From 490bdb4f74fbc397f8db0f62ca964963b83bc604 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:55:06 +0100 Subject: [PATCH 20/24] fix: retry a refused swap from amount and keep its claim running --- .../repositories/PubkySwapsRouteRepo.kt | 9 ++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 45 ++++++++++++------- .../repositories/PubkySwapsRouteRepoTest.kt | 21 +++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 9 ++-- 4 files changed, 63 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 0af2e6eace..669beba904 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -12,6 +12,7 @@ import com.synonym.bitkitcore.pubkySwapsCommitRoute import com.synonym.bitkitcore.pubkySwapsRestore import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -146,16 +147,18 @@ class PubkySwapsRouteRepo @Inject constructor( * settles the hold invoice once it sees the claim, so the payment is done; the claim is still advanced in the * background so bitkit-core rebroadcasts it until it confirms. */ - suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result { + // Runs on the app scope: the swap keeps advancing towards its claim when the caller, such as a cleared screen, + // stops waiting. + suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result = scope.async { var lastFailure: Throwable? = null - return withTimeoutOrNull(timeout) { + withTimeoutOrNull(timeout) { pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } }?.onSuccess { advanceInBackground(swapId) } ?: run { // The provider may still settle the hold payment, so the swap keeps advancing towards its claim. advanceInBackground(swapId) Result.failure(PubkySwapClaimTimeoutException(swapId, lastFailure)) } - } + }.await() private fun advanceInBackground(swapId: String) { scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 3e972b5a25..3cc9bc2c4c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6805,11 +6805,7 @@ class AppViewModel @Inject constructor( val tags = _sendUiState.value.selectedTags val address = _sendUiState.value.address val payment = pubkySwapsRouteRepo.commit(quote.quoteId).getOrElse { - val isCurrent = isSendCurrent() - clearSwapRouteQuote(isCurrent) - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) + failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) return } Logger.info("Committed Pubky Swaps route '${payment.swapId}' to '${payment.destinationAddress}'", context = TAG) @@ -6818,11 +6814,7 @@ class AppViewModel @Inject constructor( "Swap hold invoice is not a Lightning invoice" }.paymentHash.toHex() }.getOrElse { - val isCurrent = isSendCurrent() - clearSwapRouteQuote(isCurrent) - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) + failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) return } // A failed hold payment closes the send through the node's failure event, like a regular Lightning send. @@ -6847,12 +6839,8 @@ class AppViewModel @Inject constructor( lightningRepo.payInvoice(payment.invoice).getOrElse { holdFailure.cancel() clearPendingContactPaymentContext(holdPaymentHash) - val isCurrent = isSendCurrent() - clearSwapRouteQuote(isCurrent) if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) - releasePrivatePaymentListIfNeeded(contactPaymentContext) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) - handlePaymentPreparationFailure(it, contactPaymentContext, isCurrent) + failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) return } // The provider settles the hold payment once it sees the claim, so the send waits on it as a pending Lightning @@ -6919,6 +6907,33 @@ class AppViewModel @Inject constructor( } } + /** A swap that failed before its hold payment went out moved no funds, so the send retries from the amount. */ + private suspend fun failSwapRoutedPayment( + error: Throwable, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + isCurrent: Boolean, + ) { + clearSwapRouteQuote(isCurrent) + releasePrivatePaymentListIfNeeded(contactPaymentContext) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + if (!isCurrent) { + handlePaymentPreparationFailure(error, contactPaymentContext, isSendCurrent = false) + return + } + setSendEffect( + SendEffect.NavigateToError( + failure = error.toSendFailureDetails(context, paymentRequest = null), + retryRoute = SendRetryRoute.Amount, + ), + ) + if (contactPaymentContext?.incomingPaymentRequest != null) { + viewModelScope.launch { + refreshIncomingPaykitPaymentRequests(PaykitPaymentRequestRefreshMode.STORED, forceFresh = true) + } + } + } + private fun clearSwapRouteQuote(isSendCurrent: Boolean, keepHoldPaymentHash: Boolean = false) { if (!isSendCurrent) return _sendUiState.update { diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index adc7ed4e5f..3e4e2f5a4e 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -4,13 +4,16 @@ import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.PubkySwapRouteStatus import com.synonym.bitkitcore.pubkySwapsAdvance import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Test import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.atLeast import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.whenever @@ -84,6 +87,24 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `awaitClaim keeps advancing the swap after its caller is cancelled`() = test { + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) + .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) + .thenReturn(status(PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID))) + + val caller = launch { sut.awaitClaim(SWAP_ID) } + runCurrent() + caller.cancel() + advanceUntilIdle() + + core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, atLeast(3)) + } + } + private suspend fun advancing(vararg answers: Any, block: suspend () -> T): T = mockStatic(CORE).use { core -> var stub = core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 070142aec4..74a1b462e9 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -16907,9 +16907,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmCurrentPayment() + assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) expectNoEvents() } - assertNull(sut.currentSheet.value) verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any()) } @@ -17018,7 +17018,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `swap route refused commit clears the quote`() = test { + fun `swap route refused commit clears the quote and retries from the amount`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.failure(AppError("quote_expired"))) openSwapRoutedContactPayment() @@ -17027,8 +17027,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmSwapRoutedPayment() - cancelAndIgnoreRemainingEvents() + assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) + expectNoEvents() } + assertNotNull(sut.currentSheet.value) + assertNotNull(activeContactPaymentContext()) assertNotNull(sut.sendUiState.value.paykitSwapRoute) assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) } From 19f575cb2ebc62552a2b912c03c3d29cb9ee736e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:09:47 +0100 Subject: [PATCH 21/24] fix: release a refused swap's private payment list --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 +- .../viewmodels/AppViewModelSendFlowTest.kt | 47 +++++++++++++++++++ 2 files changed, 51 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 3cc9bc2c4c..19df174b16 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6915,7 +6915,10 @@ class AppViewModel @Inject constructor( isCurrent: Boolean, ) { clearSwapRouteQuote(isCurrent) - releasePrivatePaymentListIfNeeded(contactPaymentContext) + // Nothing was paid to the list's address, so a retry may pay from the same list. + contactPaymentContext?.privatePaymentContext?.let { + privatePaykitRepo.releasePrivatePaymentList(contactPaymentContext.publicKey, it) + } finishManualAllowancePayment(allowanceAttemptId, succeeded = false) if (!isCurrent) { handlePaymentPreparationFailure(error, contactPaymentContext, isSendCurrent = false) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 74a1b462e9..c3d639c52e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -203,6 +203,7 @@ import to.bitkit.repositories.PendingPaymentRepo import to.bitkit.repositories.PendingPaymentResolution import to.bitkit.repositories.PreActivityMetadataRepo import to.bitkit.repositories.PrivatePaykitAddressReservationRepo +import to.bitkit.repositories.PrivatePaykitError import to.bitkit.repositories.PrivatePaykitPaymentContext import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyIdentityReadiness @@ -17017,6 +17018,50 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pubkySwapsRouteRepo, times(1)).commit(SWAP_QUOTE_ID) } + @Test + fun `swap route retry after a refused commit pays from the same private payment list`() = test { + val privateContext = PrivatePaykitPaymentContext(mapOf(MethodId.P2wpkh.rawValue to REGTEST_ADDRESS), 7uL) + var consumed = false + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)).doSuspendableAnswer { + if (consumed) { + Result.failure(PrivatePaykitError.PaymentListAlreadyConsumed) + } else { + consumed = true + Result.success(Unit) + } + } + whenever(privatePaykitRepo.releasePrivatePaymentList(testPublicKey, privateContext)).doSuspendableAnswer { + consumed = false + Result.success(Unit) + } + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)) + .thenReturn(Result.failure(AppError("quote_expired")), Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment(privatePaymentContext = privateContext) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertIs(awaitItem()) + + // Retry from Amount quotes afresh for the same contact. + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + sut.setSendEvent(SendEvent.ClearPayConfirmation) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + cancelAndIgnoreRemainingEvents() + } + verify(privatePaykitRepo, times(2)).consumePrivatePaymentList(testPublicKey, privateContext) + verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) + verify(lightningRepo).payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull()) + } + @Test fun `swap route refused commit clears the quote and retries from the amount`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.failure(AppError("quote_expired"))) @@ -17458,6 +17503,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { endpoints: List = listOf(Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = "")), // `advanceUntilIdle` fires the hold watch's timer, which ends a swap payment still awaiting its claim. settle: TestScope.() -> Unit = { advanceUntilIdle() }, + privatePaymentContext: PrivatePaykitPaymentContext? = null, ) { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())).thenReturn(quote) @@ -17474,6 +17520,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.openContactPayment( paymentRequest = REGTEST_ADDRESS, publicKey = testPublicKey, + privatePaymentContext = privatePaymentContext, endpoints = endpoints, ) settle() From cd13b1322ea1fdf9a6db1b95976d7b194953cfef Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:50:39 +0100 Subject: [PATCH 22/24] chore: move to bitkit-core 0.8.0-swaps.11 --- 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 1fa7c94077..8dae0b80ca 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.9" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-swaps.11" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.86" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.86" } From 9a7eebeb315a08cc39716d853091fc1a8f55901d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:07:11 +0100 Subject: [PATCH 23/24] chore: build on the bitkit-core 0.8.0-rc14 release rc14 adds an optional auth argument to the regtest calls with no Kotlin default; pass null to keep today's unauthenticated calls. --- app/src/main/java/to/bitkit/services/CoreService.kt | 5 ++++- gradle/libs.versions.toml | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index a459abd9bb..f894e8da1e 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -2248,13 +2248,14 @@ class BlocktankService( // MARK: - Regtest methods suspend fun regtestMine(count: UInt = 1u) { - com.synonym.bitkitcore.regtestMine(count = count) + com.synonym.bitkitcore.regtestMine(count = count, auth = null) } suspend fun regtestDeposit(address: String, amountSat: ULong = 10_000_000uL): String { return com.synonym.bitkitcore.regtestDeposit( address = address, amountSat = amountSat, + auth = null, ) } @@ -2262,6 +2263,7 @@ class BlocktankService( return com.synonym.bitkitcore.regtestPay( invoice = invoice, amountSat = amountSat, + auth = null, ) } @@ -2274,6 +2276,7 @@ class BlocktankService( fundingTxId = fundingTxId, vout = vout, forceCloseAfterS = forceCloseAfterS.toULong(), + auth = null, ) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1c632ab1d9..efba03931a 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.11" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc14" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc6" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.86" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.86" } From c22b8f6ed0e20801727b0575cd2ed7fee16ca849 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:15:50 +0100 Subject: [PATCH 24/24] fix: keep a swap hold with an unknown spark outcome pending --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../viewmodels/AppViewModelSendFlowTest.kt | 22 +++++++++++++++++++ 2 files changed, 25 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 9eb1b94de3..51049b43cc 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6911,7 +6911,9 @@ class AppViewModel @Inject constructor( synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } } // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. - lightningRepo.payInvoice(payment.invoice).getOrElse { + lightningRepo.payInvoice(payment.invoice).onFailure { + // Spark may have sent it, so an unknown outcome waits on the claim like a sent hold payment. + if (it is PaymentPendingException) return@onFailure holdFailure.cancel() clearPendingContactPaymentContext(holdPaymentHash) if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d504ca463d..b27a21103c 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -17324,6 +17324,28 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any()) } + @Test + fun `swap route hold payment with an unknown outcome stays pending`() = test { + val privateContext = PrivatePaykitPaymentContext(mapOf(MethodId.P2wpkh.rawValue to REGTEST_ADDRESS), 7uL) + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.failure(PaymentPendingException(SWAP_HOLD_HASH))) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment(privatePaymentContext = privateContext) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + cancelAndIgnoreRemainingEvents() + } + verify(pendingPaymentRepo).track(SWAP_HOLD_HASH) + verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) + verify(privatePaykitRepo, never()).releasePrivatePaymentList(testPublicKey, privateContext) + } + @Test fun `swap route hold payment failure event stops awaiting the claim`() = test { var claimCancelled = false