diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 7da76a0ef8..80e5545ee8 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -136,6 +136,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") @@ -419,6 +421,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", "BLOCKTANK_REGTEST_AUTH")) { 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 40f321a491..e572e80fd5 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -66,6 +66,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..669beba904 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -0,0 +1,219 @@ +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.PubkySwapSentPayment +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.async +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.runSuspendCatching +import to.bitkit.models.PubkyProfile +import to.bitkit.models.PubkyPublicKeyFormat +import to.bitkit.models.toCoreNetwork +import to.bitkit.utils.AppError +import to.bitkit.utils.Logger +import to.bitkit.utils.ServiceError +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the + * contact published. bitkit-core picks the provider and checks its quote, contract and hold invoice; the wallet pays + * the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. + */ +@Singleton +class PubkySwapsRouteRepo @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val keychain: Keychain, + private val pubkyRepo: PubkyRepo, + private val lightningRepo: LightningRepo, +) { + 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 + + /** 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. */ + 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, + serviceLegs: List = emptyList(), + ): Result = withSecrets { mnemonic, passphrase -> + val candidates = candidates() + Logger.debug("Routing Paykit payment via '${candidates.map(PubkyPublicKeyFormat::redacted)}'", context = TAG) + pubkySwapsRoutePaykitPayment( + request = PaykitRouteRequest( + amountSat = amountSats, + contactEndpoints = endpoints, + lightningSpendableSat = lightningSpendableSats, + onchainSpendableSat = onchainSpendableSats, + providers = candidates, + feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, + serviceLegs = serviceLegs, + ), + network = Env.network.toCoreNetwork(), + mnemonic = mnemonic, + bip39Passphrase = passphrase, + ) + } + + /** + * 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. Swaps already on record keep the + * destination they were committed with. + */ + suspend fun restoreSwaps(): Result = withSecrets { mnemonic, passphrase -> + val payoutAddress = lightningRepo.newAddress().getOrThrow() + val report = pubkySwapsRestore( + providers = candidates(), + sentPayments = sentPayments(), + electrumUrl = Env.electrumServerUrl, + payoutAddress = payoutAddress, + feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, + network = Env.network.toCoreNetwork(), + mnemonic = mnemonic, + bip39Passphrase = passphrase, + ) + if (report.incompleteProviders.isNotEmpty()) { + Logger.warn("Swap lists incomplete from '${report.incompleteProviders}'", context = TAG) + } + 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. */ + 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 = + (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 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. + */ + // 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 + 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) } } + } + + 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) { + // 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)) + null -> Unit + else -> { + Logger.debug("Pubky Swaps route '$swapId': $state", context = TAG) + onPending(AppError("Swap '$swapId' not claimed yet: '$state'")) + } + } + delay(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) + } + } +} + +/** 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, +) + +/** 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/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index e17a8d0949..92c03debe9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -59,6 +59,7 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.ext.commentAllowed +import to.bitkit.ext.ellipsisMiddle import to.bitkit.ext.formatInvoiceExpiryRelative import to.bitkit.models.FeeRate import to.bitkit.models.PaykitAsset @@ -108,6 +109,9 @@ import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds private val EXPIRY_REFRESH_INTERVAL = 60.seconds + +/** Characters of a swap provider's pubky shown on the confirm screen. */ +private const val PROVIDER_KEY_LENGTH = 12 const val SEND_CONFIRM_RESET_RESULT_KEY = "SEND_CONFIRM_RESET_RESULT_KEY" @Composable @@ -870,7 +874,19 @@ private fun LightningDetails( } } - if (uiState.routedPaykitRoute?.serviceLeg != null) { + val swapRoute = uiState.paykitSwapRoute + val swapQuote = swapRoute?.quote + if (swapQuote != null) { + val provider = swapRoute.providerName?.takeIf { it.isNotBlank() } + ?: swapQuote.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") + ) + } + } else if (uiState.routedPaykitRoute?.serviceLeg != null) { SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { BodySSB( text = stringResource(R.string.wallet__send_swap_route_spark), @@ -923,9 +939,10 @@ private fun ContactRecipient( } } -/** An on-chain pick or a Spark leg keeps the contact's LNURL in state without paying it. */ +/** An on-chain pick, a Spark leg or a swap route keeps the contact's LNURL in state without paying it. */ private val SendUiState.paysLnurl: Boolean - get() = lnurl is LnurlParams.LnurlPay && payMethod == SendMethod.LIGHTNING && routedPaykitRoute?.serviceLeg == null + get() = lnurl is LnurlParams.LnurlPay && payMethod == SendMethod.LIGHTNING && + routedPaykitRoute?.serviceLeg == null && activePaykitSwapRoute == null private val SendUiState.confirmationRequestNote: String? get() = paymentRequestNote?.trim()?.takeIf { isPaymentRequest && it.isNotEmpty() } 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 fd2c3a9df8..3dddda875e 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -364,11 +364,13 @@ fun SendSheet( observeResolution = it.observeResolution, isOnchain = it.isOnchain, refusalReason = it.refusalReason, + retryRoute = it.retryRoute, ) ) is SendEffect.NavigateToError -> navController.navigateTo( SendRoute.errorFromFailure( failure = it.failure, + retryRoute = it.retryRoute, ) ) } @@ -1042,6 +1044,7 @@ sealed interface SendRoute { @Serializable enum class SendRetryRoute(val sendRoute: SendRoute) { + Amount(SendRoute.Amount), Confirm(SendRoute.Confirm), QuickPay(SendRoute.QuickPay), } @@ -1049,7 +1052,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 } @@ -1068,7 +1071,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 03cc20685f..46929f74a4 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -30,6 +30,8 @@ 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.ServiceRouteLeg import com.synonym.bitkitcore.SortDirection @@ -78,6 +80,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 @@ -223,6 +226,8 @@ 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 import to.bitkit.repositories.QuickPayPaymentFailedError @@ -257,6 +262,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 @@ -333,6 +339,7 @@ class AppViewModel @Inject constructor( private val paykitPaymentRequestDiagnostics: PaykitPaymentRequestDiagnostics, private val refreshContactPaykitLink: RefreshContactPaykitLinkUseCase, private val usdtRepo: UsdtRepo, + private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, private val paykitRouteRepo: PaykitRouteRepo, val paykitUsdtPayments: PaykitUsdtPaymentRepo, private val samRockRepo: SamRockRepo, @@ -582,6 +589,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 @@ -2984,14 +2994,21 @@ 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( 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 @@ -4121,11 +4138,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 } @@ -4152,7 +4170,19 @@ class AppViewModel @Inject constructor( invoice = invoice, lnurl = lnurl, ).takeIf { it.endpoints.isNotEmpty() } - val payMethod = if (offersSparkLeg && !canUseOnchain) { + // Without a Spark leg, a Pubky Swaps provider can pay it from Spending: the router weighs swaps after service + // legs. + val swapRoute = if (offersSparkLeg) { + null + } else { + paykitSwapRoute( + payment = payment, + methodId = onchainEndpoint?.first?.methodId, + address = address, + canPayDirectly = canUseLightning || canUseOnchain || useUsdt, + ) + } + val payMethod = if (swapRoute != null || offersSparkLeg && !canUseOnchain) { SendMethod.LIGHTNING } else { paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) @@ -4165,6 +4195,7 @@ class AppViewModel @Inject constructor( paykitAmount = "", payMethod = payMethod, paykitRoute = route, + paykitSwapRoute = swapRoute, ) } if (usdtRepo.shouldRefresh(isUsdtEnabled.value)) usdtRepo.refresh(history = false) @@ -4317,6 +4348,23 @@ 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, + 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 + if (methodId?.isOnchain != true) return null + return PaykitSwapRouteUi(endpoint = PaykitEndpoint(methodId = methodId.rawValue, value = address)) + } + /** * Offered whatever Lightning can pay when the payment opens: an amount entered later can pass Lightning's limit, * and the router still prefers a direct payment that works. @@ -4350,10 +4398,18 @@ class AppViewModel @Inject constructor( if (_sendUiState.value.paykitUsesUsdt || !_sendUiState.value.isAmountEditable) return paykitRouteDecided = false _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, holdPaymentHash = null) + } else { + it.paykitSwapRoute + }, + lightningFeeSats = if (staleQuote) 0 else it.lightningFeeSats, ) } updateCanSwitchWallet() @@ -4509,7 +4565,9 @@ class AppViewModel @Inject constructor( } updateCanSwitchWallet() // A source switch on Confirm asks the router again, for a request (no amount step) or a route already decided. - if (activeIncomingPaymentRequest() != null || paykitRouteDecided) { + // A swap route pays its own quote, so the router never adds a Spark leg beside it. + val reroutes = activeIncomingPaymentRequest() != null || paykitRouteDecided + if (_sendUiState.value.paykitSwapRoute == null && reroutes) { _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { // A refused route leaves no leg or invoice to pay, and a picked LNURL past its limits can't be paid; // switching the source again recomputes validity. @@ -4611,7 +4669,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), @@ -4750,16 +4809,10 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } - // A Spark leg pays the on-chain endpoint, so the unselected LNURL's limits never apply to it. - _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { - when (routePaykitPayment(it)) { - PaykitRouteOutcome.Leg -> { - setSendEffect(SendEffect.NavigateToConfirm) - return - } - PaykitRouteOutcome.Refused, PaykitRouteOutcome.Stale -> return - PaykitRouteOutcome.Direct -> Unit - } + if (!routePaykitPaymentOnContinue()) return + _sendUiState.value.activePaykitSwapRoute?.let { + if (quotePaykitSwapRoute(it)) setSendEffect(SendEffect.NavigateToConfirm) + return } // The route can restore an LNURL a BOLT11 pick cleared, so its limits are read after routing. An on-chain // pick keeps the contact's LNURL in state, and its limits never apply to that payment. @@ -4783,6 +4836,108 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) } + /** + * Asks the router first: a swap route alone is quoted on its own, but next to a Spark leg the swap covers only + * what Spark can't pay, so a smaller amount entered later goes back to Spark. False when Continue stops here. + */ + private suspend fun routePaykitPaymentOnContinue(): Boolean { + val state = _sendUiState.value + // A Spark leg pays the on-chain endpoint, so the unselected LNURL's limits never apply to it. + val route = state.paykitRoute + ?.takeIf { state.routesPaykitPayment && (state.activePaykitSwapRoute == null || it.offersSparkLeg) } + ?: return true + val swapFallback = if (route.offersSparkLeg && state.payMethod == SendMethod.LIGHTNING) { + paykitSwapRouteFallback(route, state.address) + } else { + null + } + return when (routePaykitPayment(route, hasSwapFallback = swapFallback != null)) { + PaykitRouteOutcome.Leg -> { + _sendUiState.update { it.copy(paykitSwapRoute = null) } + setSendEffect(SendEffect.NavigateToConfirm) + false + } + PaykitRouteOutcome.Refused, PaykitRouteOutcome.Stale -> false + PaykitRouteOutcome.Direct -> { + _sendUiState.update { it.copy(paykitSwapRoute = null) } + true + } + PaykitRouteOutcome.SwapFallback -> { + _sendUiState.update { it.copy(paykitSwapRoute = swapFallback) } + true + } + } + } + + /** The Pubky Swaps route that pays an on-chain contact from Spending when Spark can't, or null when no swap can. */ + private fun paykitSwapRouteFallback(route: PaykitRouteUi, address: String): PaykitSwapRouteUi? { + val payment = synchronized(contactPaymentContextLock) { activeContactPaymentContext } ?: return null + val methodId = route.endpoints.lastOrNull { it.isOnchain() }?.methodId + ?.let { MethodId.fromRawValue(it) } + val canPayFromSavings = walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() + return paykitSwapRoute(payment, methodId, address, canPayDirectly = canPayFromSavings) + } + + 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( + amountSats = _sendUiState.value.amount, + endpoints = listOf(route.endpoint), + lightningSpendableSats = maxSendableLightningSats(), + 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) + return false + } + val quote = when (paykitRoute) { + is PaykitRoute.Swap -> paykitRoute.quote + is PaykitRoute.None -> { + 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 + } + // 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 + } + } + _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(), + ) + } + return true + } + /** Shows [lnurl]'s too-low or too-high toast when [amount] is outside its limits; true when it accepts it. */ private suspend fun validateLnurlAmount(lnurl: LnurlParams.LnurlPay, amount: ULong): Boolean { val minSendable = lnurl.data.minSendableSat() @@ -4813,7 +4968,7 @@ class AppViewModel @Inject constructor( * LNURL whose limits refuse the amount, and a Spark leg to on-chain ones; Savings only the on-chain endpoints. * Direct pays the endpoint it names. */ - private suspend fun routePaykitPayment(route: PaykitRouteUi): PaykitRouteOutcome { + private suspend fun routePaykitPayment(route: PaykitRouteUi, hasSwapFallback: Boolean = false): PaykitRouteOutcome { val state = _sendUiState.value val generation = sendStateGeneration val contact = synchronized(contactPaymentContextLock) { activeContactPaymentContext } @@ -4884,6 +5039,9 @@ class AppViewModel @Inject constructor( val reason = (picked as? PaykitRoute.None)?.reason ?: "Swap routes are unsupported" Logger.warn("Found no Paykit route: '$reason'", context = TAG) _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } + // A Spark balance too small for the amount and fee, or no route at all, leaves the payment to a swap + // provider when one can carry it: its quote follows, so nothing shows here. + if (hasSwapFallback && !isLegSettling) return PaykitRouteOutcome.SwapFallback // The router's reason is English for the log: the app tells a short balance from an unusable contact. val isAmountShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() // The router never saw an LNURL whose limits refuse the amount, so its limit says why. @@ -5238,7 +5396,11 @@ class AppViewModel @Inject constructor( val fromMainScanner = isMainScanner if ( contactPaymentContext != null && - (requiresPaykitAssetSelection(contactPaymentContext) || requiresPaykitServiceRoute(contactPaymentContext)) + ( + requiresPaykitAssetSelection(contactPaymentContext) || + requiresPaykitServiceRoute(contactPaymentContext) || + requiresPaykitSwapRoute(contactPaymentContext) + ) ) { openPaykitContactPayment(contactPaymentContext, fromMainScanner, suppressQuickPay, walletGeneration) return@withContext @@ -5353,6 +5515,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 + } + /** Any on-chain endpoint lets Spark pay an amount the contact's Lightning endpoints or Savings can't. */ private fun requiresPaykitServiceRoute(payment: ContactPaymentContext): Boolean { if (!paykitRouteRepo.canRouteThroughSpark) return false @@ -6010,7 +6179,7 @@ class AppViewModel @Inject constructor( if (state.usdtRecipient != null) add(SendFundingSource.Usdt) if ( state.isUnified || state.decodedInvoice != null || state.lnurl is LnurlParams.LnurlPay || - state.paykitRoute?.offersSparkLeg == true + state.paykitSwapRoute != null || state.paykitRoute?.offersSparkLeg == true ) { add( SendFundingSource.Spending @@ -6488,9 +6657,10 @@ class AppViewModel @Inject constructor( if (_sendUiState.value.showSanityWarningDialog != null) return val settings = settingsStore.data.first() - // A Spark leg spends its debit, the amount plus Spark's fees, from Spark's balance. + // A Spark leg spends its debit, the amount plus Spark's fees, from Spark's balance; a swap quote its debit + // from Spending. val leg = _sendUiState.value.routedPaykitRoute?.serviceLeg - val spentSats = leg?.debitSat ?: amountSats + val spentSats = _sendUiState.value.activePaykitSwapRoute?.quote?.debitSat ?: leg?.debitSat ?: amountSats val balanceToCheck = when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> { _sendUiState.value.hardwareAvailableSats @@ -6570,6 +6740,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) @@ -6627,7 +6806,7 @@ class AppViewModel @Inject constructor( val lnurl = _sendUiState.value.lnurl // An on-chain payment, from Savings or a Spark leg, fetches no invoice from the unselected LNURL. val isLnurlPay = lnurl is LnurlParams.LnurlPay && _sendUiState.value.payMethod == SendMethod.LIGHTNING && - _sendUiState.value.routedPaykitRoute?.serviceLeg == null + _sendUiState.value.routedPaykitRoute?.serviceLeg == null && _sendUiState.value.activePaykitSwapRoute == null if (isLnurlPay) { val amountMsats = lnurl.data.callbackAmountMsats(amount) @@ -6670,6 +6849,11 @@ class AppViewModel @Inject constructor( return } + _sendUiState.value.activePaykitSwapRoute?.quote?.let { + proceedWithSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId) + return + } + _sendUiState.value.routedPaykitRoute?.serviceLeg?.let { proceedWithServiceRoutedPayment( leg = it, @@ -7089,6 +7273,194 @@ class AppViewModel @Inject constructor( ) } + private suspend fun proceedWithSwapRoutedPayment( + quote: PubkySwapRouteQuote, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + val 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 { + failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) + 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 { + failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) + return + } + // A failed hold payment closes the send through the node's failure event, like a regular Lightning send. + 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) { + is Event.PaymentFailed if it.paymentHash == holdPaymentHash -> WatchResult.Complete(it.reason) + else -> WatchResult.Continue() + } + } + } + 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).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) + 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 + // payment. Pending has no way back to Amount, where a fresh quote could pay the contact a second time. + // 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( + 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 { + 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 + // 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() + } + 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 + } + // 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) + 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() + } + } + + /** 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) + // 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) + 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 { + val route = it.paykitSwapRoute + it.copy( + paykitSwapRoute = route?.copy( + quote = null, + providerName = null, + holdPaymentHash = route.holdPaymentHash.takeIf { keepHoldPaymentHash }, + ), + lightningFeeSats = 0, + ) + } + } + + 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, tags: List, address: String): Boolean { + if (tags.isEmpty()) return false + return preActivityMetadataRepo.savePreActivityMetadata( + id = paymentHash, + paymentHash = paymentHash, + address = address, + isReceive = false, + tags = tags, + ).isSuccess + } + private suspend fun proceedWithServiceRoutedPayment( leg: ServiceRouteLeg, incomingPaymentRequest: PaykitPaymentRequest?, @@ -8318,6 +8690,8 @@ class AppViewModel @Inject constructor( } if (_currentSheet.value is Sheet.Send) { sendStateGeneration++ + // A payment still running for the dismissed send, like a slow swap commit, must not block the next. + if (confirmedPaymentSubmission != null) releaseConfirmedPaymentSubmission() cancelHardwarePaymentRequestIfNeeded() resetQuickPay() quickPayRepo.detachAll() @@ -8528,11 +8902,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) { @@ -8547,6 +8921,7 @@ class AppViewModel @Inject constructor( return } isSoftwarePaymentSubmissionActive = true + val submission = Any().also { confirmedPaymentSubmission = it } viewModelScope.launch(start = CoroutineStart.UNDISPATCHED) { val finishSubmission = beginPaymentSubmission() try { @@ -8554,12 +8929,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 } @@ -9216,8 +9596,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()) @@ -9225,7 +9609,7 @@ class AppViewModel @Inject constructor( ) } else { toast(error) - hideSheet() + if (isSendCurrent) hideSheet() } if (contactPaymentContext?.incomingPaymentRequest != null) { viewModelScope.launch { @@ -9663,8 +10047,13 @@ data class SendUiState( val fixedOnchainAmount: ULong? = null, val initialSubscriptionPaymentNeedsConfirmation: Boolean = false, val incomingPaymentRequestId: PaykitPaymentRequestId? = null, + val paykitSwapRoute: PaykitSwapRouteUi? = null, val paykitRoute: PaykitRouteUi? = 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 } + /** The Paykit route this payment takes: a Spark leg runs only while Spending is the source. */ val routedPaykitRoute: PaykitRouteUi? get() = paykitRoute?.takeIf { payMethod == SendMethod.LIGHTNING } @@ -9701,6 +10090,15 @@ 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, + val holdPaymentHash: String? = null, +) + /** * A contact payment bitkit-core's router picks the way for: the contact's bitcoin endpoints, whether a Spark leg may * reach its on-chain ones, the leg once the router picked one, and the decoded invoice and LNURL a Direct pick pays. @@ -9714,7 +10112,7 @@ data class PaykitRouteUi( val lnurl: LnurlParams.LnurlPay? = null, ) -private enum class PaykitRouteOutcome { Direct, Leg, Refused, Stale } +private enum class PaykitRouteOutcome { Direct, Leg, Refused, Stale, SwapFallback } private fun PaykitEndpoint.isOnchain(): Boolean = MethodId.fromRawValue(methodId)?.isOnchain == true @@ -9827,13 +10225,17 @@ 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, val observeResolution: Boolean = true, val isOnchain: Boolean = false, val refusalReason: String? = null, + val retryRoute: SendRetryRoute = SendRetryRoute.Confirm, ) : SendEffect() } @@ -9881,6 +10283,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/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 7de4230089..8e22e31fef 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -49,6 +49,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.SparkRepo import to.bitkit.repositories.SyncSource @@ -81,6 +82,7 @@ class WalletViewModel @Inject constructor( private val connectivityRepo: ConnectivityRepo, private val boltzService: BoltzService, private val connectionRecovery: WalletConnectionRecovery, + private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, sparkRepo: SparkRepo, ) : ViewModel() { companion object { @@ -496,6 +498,7 @@ class WalletViewModel @Inject constructor( } }.onSuccess { failedCategories -> _restoreState.update { RestoreState.Completed(failedCategories) } + restorePubkySwaps() }.onFailure { Logger.error("Restore from backup failed", it, context = TAG) ToastEventBus.send(it) @@ -570,6 +573,40 @@ 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 swaps = pubkySwapsRouteRepo.restoreSwaps().getOrElse { + Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) + return@launch + } + 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 + // 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, + ) + } + } + } + } + } + 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 e4cd0e3bca..ea3e507769 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1133,6 +1133,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 692bc2f515..ac264b1e59 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1166,6 +1166,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 012af26c5e..4b04e35918 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1159,6 +1159,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 32e9c3b9be..95029f5fbb 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1164,6 +1164,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 3c67d6f9ec..8866f7a182 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1040,6 +1040,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 e63ed7a2bd..d1f2273483 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1138,6 +1138,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 f4b03b2a0e..c1ed2c78bb 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1159,6 +1159,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 cb250a075a..382535bae8 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1030,6 +1030,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 f4a8687132..a1fb49eb53 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1037,6 +1037,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 a44dda72c2..d47c232af1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1162,6 +1162,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 b210d10775..dd89ec2370 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1157,6 +1157,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 480fd04042..68b06fd873 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1039,6 +1039,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 7d48e5a6f6..05a4115161 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1166,6 +1166,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 aef7c3de1f..b544d086f6 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -899,6 +899,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 6885fd0628..b212fdf892 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1182,6 +1182,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 c195a779ce..d2747c9793 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1774,12 +1774,15 @@ Confirm Bitcoin Sent Route + Pubky Swaps · %1$s Spark Swipe To Pay To 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/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt new file mode 100644 index 0000000000..3e4e2f5a4e --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -0,0 +1,127 @@ +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.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 +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 { + 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) + } + + @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)) + } + } + + @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()) } } + 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 158bb3669c..3b853cfe9f 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 @@ -49,6 +50,8 @@ 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.RestoredPubkySwaps import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo import to.bitkit.repositories.WalletState @@ -87,6 +90,7 @@ class WalletViewModelTest : BaseUnitTest() { private val migrationService = mock() private val connectivityRepo = mock() private val boltzService = mock() + private val pubkySwapsRouteRepo = mock() private val sparkRepo = idleSparkRepo() private val lightningState = MutableStateFlow(LightningState()) @@ -128,6 +132,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, ) } @@ -349,6 +354,67 @@ 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(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) + 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(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 + 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(emptySet()) + ) + lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) + + sut.restoreWallet("mnemonic", "passphrase") + walletState.value = walletState.value.copy(walletExists = true) + advanceUntilIdle() + + assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) + verify(pubkySwapsRouteRepo, never()).restoreSwaps() + } + @Test fun `failed backup restore can retry without restarting node`() = test { val testError = AppError("restore failed") @@ -1179,6 +1245,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, ) @@ -1247,6 +1314,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, ) @@ -1304,6 +1372,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, ) @@ -1345,6 +1414,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, ) @@ -1437,6 +1507,7 @@ class WalletViewModelTest : BaseUnitTest() { connectivityRepo = connectivityRepo, boltzService = boltzService, connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, ) advanceUntilIdle() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6f3ca362b5..784c7a4a10 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -23,6 +23,8 @@ 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.ServiceRouteLeg import com.synonym.bitkitcore.UsdtDestination @@ -206,11 +208,14 @@ 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 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 import to.bitkit.repositories.QuickPayCompletionKind @@ -248,6 +253,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 @@ -269,8 +275,10 @@ import kotlin.test.assertIs 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 @@ -321,6 +329,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitPaymentProofRepo = mock() private val paykitPaymentRequestDiagnostics = mock() private val usdtRepo = mock() + private val pubkySwapsRouteRepo = mock() private val paykitRouteRepo = mock() private val usdtState = MutableStateFlow(UsdtWalletState(balance = 1_000_000u)) private val paykitUsdtPayments = mock() @@ -1010,6 +1019,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paykitPaymentRequestDiagnostics = paykitPaymentRequestDiagnostics, refreshContactPaykitLink = refreshContactPaykitLink, usdtRepo = usdtRepo, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, paykitRouteRepo = paykitRouteRepo, paykitUsdtPayments = paykitUsdtPayments, samRockRepo = samRockRepo, @@ -12104,8 +12114,6 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.hideSheet() runCurrent() assertTrue(paymentSubmissionActive.value) - sut.setSendEvent(SendEvent.PayConfirmed) - runCurrent() release.complete(Unit) runCurrent() assertFalse(paymentSubmissionActive.value) @@ -18728,6 +18736,810 @@ class AppViewModelSendFlowTest : BaseUnitTest() { return privateContext } + @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 + } + val activity = mock { on { v1 } doReturn activityV1 } + whenever { activityRepo.findActivityByPaymentId(any(), any(), any(), any()) } + .thenReturn(Result.success(activity)) + 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(swapHoldPending(), awaitItem()) + + emitNodeEvent( + Event.PaymentSuccessful( + paymentId = SWAP_HOLD_HASH, + paymentHash = SWAP_HOLD_HASH, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + advanceUntilIdle() + expectNoEvents() + } + // 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), + syncLdkPayments = any(), + walletId = any(), + ) + 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 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 `spark balance short of a contact payment falls back to a swap quote`() = test { + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.failure(SparkError.WithdrawalOverBalance())) + openSwapRoutedContactPayment() + assertNull(sut.sendUiState.value.paykitSwapRoute) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + } + + verify(paykitRouteRepo).route(eq(SWAP_DELIVERED_SATS), any(), any(), eq(0uL), eq(true)) + assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + verify(toastManager, never()).enqueue(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() + assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) + expectNoEvents() + } + 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 + 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()) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + assertFalse(claimCancelled) + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() + expectNoEvents() + } + assertTrue(claimCancelled) + verify(pendingPaymentRepo).resolve(check { assertIs(it) }) + 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 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())) + 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() + // The Pending screen hands its retry route to the error screen. + assertEquals(swapHoldPending(), awaitItem()) + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() + 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 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"))) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) + expectNoEvents() + } + assertNotNull(sut.currentSheet.value) + assertNotNull(activeContactPaymentContext()) + assertNotNull(sut.sendUiState.value.paykitSwapRoute) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + } + + @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)) + 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() + assertEquals(swapHoldPending(), awaitItem()) + expectNoEvents() + } + verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Failure(SWAP_HOLD_HASH)) + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + 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) + } + + @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)) + 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(swapHoldPending(), 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 + 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)) + emitSwapHoldPaymentSuccessful() + 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()) + } + + @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()) + 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)) + emitSwapHoldPaymentSuccessful() + advanceBeforeHoldWatchDeadline() + verify(toastManager).enqueue(check { assertEquals("PendingPaymentSucceededToast", it.testTag) }) + 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? { + 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() + 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() + } + + private fun TestScope.confirmSwapRoutedPayment() { + sut.setSendEvent(SendEvent.SwipeToPay) + advanceBeforeHoldWatchDeadline() + sut.setSendEvent(SendEvent.PayConfirmed) + 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, + paymentHash = SWAP_HOLD_HASH, + reason = PaymentFailureReason.ROUTE_NOT_FOUND, + ), + ) + + @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) + } + + @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 = "")), + // `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) + // 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)), + ) + 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, + privatePaymentContext = privatePaymentContext, + endpoints = endpoints, + ) + settle() + sut.setSendEvent(SendEvent.AmountChange(SWAP_DELIVERED_SATS)) + settle() + } + + 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, @@ -20362,5 +21174,15 @@ 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 SWAP_NEXT_CONTACT_PUBLIC_KEY = "pubky8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo" private const val OWN_NODE_ID = "02abababababababababababababababababababababababababababababababab" private const val FOREIGN_NODE_ID = "03cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" 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 + + diff --git a/journeys/paykit-swap-route.xml b/journeys/paykit-swap-route.xml new file mode 100644 index 0000000000..5de3d268fa --- /dev/null +++ b/journeys/paykit-swap-route.xml @@ -0,0 +1,28 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet that holds only a spending + balance, routes through a Pubky Swaps provider found among the user's own contacts, without the user picking a + swap, and that the contact receives the exact amount on chain. + + Preconditions: a dev debug build with E2E=true, E2E_BACKEND=local, E2E_HOMESERVER_PUBKY set to the local + marketplace homeserver and PUBKY_SWAPS_ROUTES=true; bitkit-docker's + default stack with the marketplace, payment-requests and lnurl-pay profiles; the provider running against + bitkit-docker's LND and funded; adb reverse for 6286, 6287, 6288, 15411, 15412, 60001, 23735, 23000 and 23010. + The wallet has a spending balance from an LNURL channel with bitkit-docker's LND and an empty savings balance, + a Pubky profile on the local homeserver, and both the provider's and the fixture-issuer's pubkys saved as contacts. + The contact is bitkit-docker's fixture-issuer, which publishes only a btc-regtest-p2wpkh endpoint. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Verify the contact list shows both the fixture-issuer and the provider, and tap the fixture-issuer (tag "SendContact_" followed by its pubky) + Verify the amount screen (tag "send_amount_screen") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Pubky Swaps" followed by the provider's shortened pubky + Swipe to pay (tag "GRAB") + Once the provider logs "HTLC funded; awaiting client claim", mine one block on bitkit-docker's bitcoind + Verify the Bitcoin Sent screen (tag "SendSuccess") is visible + Verify the provider logs "client claimed; hold invoice settled", and bitcoind shows the claim transaction paying exactly 0.0002 BTC to the fixture-issuer's address + +