Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
8bb27fd
feat: pay contacts through pubky swaps
ovitrif Oct 29, 2026
46ad2a9
chore: add changelog fragment
ovitrif Oct 29, 2026
0336ee0
docs: pay the journey's contact from the contact list
ovitrif Oct 30, 2026
9bb81f8
chore: use bitkit-core 0.8.0-swaps.1
ovitrif Oct 30, 2026
97749ce
chore: move to bitkit-core 0.8.0-swaps.3
ovitrif Nov 2, 2026
f6f8ad3
feat: return swap routes to savings after a wallet restore
ovitrif Nov 2, 2026
257190c
fix: keep the swap restore notice until dismissed
ovitrif Nov 2, 2026
718fcbd
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif Nov 9, 2026
79dd345
chore: move to bitkit-core 0.8.0-swaps.9
ovitrif Nov 9, 2026
9f6ec3b
test: expect the restore's failed categories
ovitrif Nov 9, 2026
de29463
fix: finish a swap-routed send once, with its tags
ovitrif Nov 9, 2026
3435c0e
fix: finish a swap-routed send when the claim is broadcast
ovitrif Nov 9, 2026
5548350
fix: keep a swap quote matched to the amount and fee shown
ovitrif Nov 9, 2026
712cc05
fix: keep a late swap result on its own payment
ovitrif Nov 9, 2026
4b8c8df
fix: retry a failed swap payment with a fresh quote
ovitrif Nov 9, 2026
47aff38
fix: keep swap sends on their own payment
ovitrif Nov 10, 2026
bc8f3e8
fix: wait for a swap claim outside the send submission
ovitrif Nov 10, 2026
de7b78f
fix: wait on a swap's hold payment on the pending screen
ovitrif Nov 10, 2026
8d40a8b
fix: keep a swap hold failed before its send returns on error
ovitrif Nov 10, 2026
c59a089
fix: open the error for a swap hold failure handled late
ovitrif Nov 10, 2026
490bdb4
fix: retry a refused swap from amount and keep its claim running
ovitrif Nov 10, 2026
19f575c
fix: release a refused swap's private payment list
ovitrif Nov 10, 2026
cd13b13
chore: move to bitkit-core 0.8.0-swaps.11
ovitrif Nov 10, 2026
7c56d7a
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif Nov 11, 2026
9a7eebe
chore: build on the bitkit-core 0.8.0-rc14 release
ovitrif Nov 11, 2026
46948b6
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif Nov 11, 2026
c22b8f6
fix: keep a swap hold with an unknown spark outcome pending
ovitrif Nov 11, 2026
c866eb5
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif Nov 11, 2026
098c355
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif Nov 11, 2026
a786e34
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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())
Expand Down
11 changes: 11 additions & 0 deletions app/src/main/java/to/bitkit/env/Env.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>
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
Expand Down
219 changes: 219 additions & 0 deletions app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt
Original file line number Diff line number Diff line change
@@ -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<PaykitEndpoint>,
lightningSpendableSats: ULong,
onchainSpendableSats: ULong,
serviceLegs: List<ServiceRouteLeg> = emptyList(),
): Result<PaykitRoute> = 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<RestoredPubkySwaps> = 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<PubkySwapSentPayment> =
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<String> =
(Env.pubkySwapsProviders + pubkyRepo.contacts.value.map { it.publicKey }).distinct()

suspend fun commit(quoteId: String): Result<PubkySwapRoutePayment> = 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<String> = scope.async {
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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<String> {
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)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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 <T> withSecrets(block: suspend (String, String?) -> T): Result<T> = 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<String>,
val known: List<String>,
)

/** 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)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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() }
Expand Down
7 changes: 5 additions & 2 deletions app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
)
}
Expand Down Expand Up @@ -1042,14 +1044,15 @@ sealed interface SendRoute {

@Serializable
enum class SendRetryRoute(val sendRoute: SendRoute) {
Amount(SendRoute.Amount),
Confirm(SendRoute.Confirm),
QuickPay(SendRoute.QuickPay),
}

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
}
Expand All @@ -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
}
}

Expand Down
Loading
Loading