Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 15 additions & 0 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3133,6 +3133,21 @@ class LightningRepo @Inject constructor(
/** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */
fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats)

/**
* Waits, up to [NODE_RUN_WAIT_TIMEOUT], while the node is stopping or a start is queued, so a caller that then
* checks channels sees the restarted node rather than the stop. Returns at once when no start is coming.
*/
suspend fun awaitPendingNodeStart() {
val changes = combine(_lightningState, pendingStartCount) { _, _ -> }
withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) {
changes.first {
val lifecycle = _lightningState.value.nodeLifecycleState
val isComing = lifecycle is NodeLifecycleState.Stopping || pendingStartCount.value > 0
lifecycle.canRun() || !isComing
}
}
}

/** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */
fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,10 @@ fun SendAmountScreen(
}
}

LaunchedEffect(uiState.decodedInvoice, uiState.payMethod) {
LaunchedEffect(uiState.decodedInvoice, uiState.payMethod, balances.maxSendLightningSats) {
if (uiState.payMethod == SendMethod.LIGHTNING && uiState.decodedInvoice != null) {
currentOnEvent(SendEvent.EstimateMaxRoutingFee)
val quote = SendEvent.EstimateMaxRoutingFee(uiState.decodedInvoice.bolt11, balances.maxSendLightningSats)
currentOnEvent(quote)
}
}

Expand All @@ -194,6 +195,7 @@ fun SendAmountScreen(
amountInputViewModel = amountInputViewModel,
syncNodeVariant = syncNodeVariant,
currencies = currencies,
balances = balances,
onBack = {
onEvent(SendEvent.AmountReset)
onBack()
Expand Down Expand Up @@ -463,7 +465,7 @@ private fun SendAmountNodeRunning(

PrimaryButton(
text = stringResource(R.string.common__continue),
enabled = uiState.isAmountInputValid && !uiState.isFundingSourceLoading,
enabled = uiState.isAmountInputValid && !uiState.isFundingSourceLoading && !uiState.awaitsSparkMaxFee,
isLoading = uiState.isLoading,
onClick = onContinue,
textStyle = if (uiState.paykitUsesUsdt) AppTextStyles.BodySSB.copy(letterSpacing = 0.sp) else null,
Expand Down
88 changes: 81 additions & 7 deletions app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
Expand Down Expand Up @@ -57,6 +58,7 @@ import to.bitkit.repositories.ConnectivityState
import to.bitkit.repositories.PaykitPaymentRequest
import to.bitkit.repositories.PaykitSubscriptionId
import to.bitkit.repositories.SparkState
import to.bitkit.ui.LocalBalances
import to.bitkit.ui.components.ConnectionIssuesView
import to.bitkit.ui.components.SyncNodeVariant
import to.bitkit.ui.components.SyncNodeView
Expand Down Expand Up @@ -116,6 +118,31 @@ private val CHANNELS_REFRESH_INTERVAL = 1.seconds
internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean =
payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats)

/**
* The amount Spark would pay for the scanned invoice: its own amount, or for an amountless one the amount entered, so
* the review of an amountless invoice Spark can pay goes ahead without the node too.
*/
internal fun sendInvoiceSats(invoiceSats: ULong?, enteredSats: ULong): ULong? =
invoiceSats?.takeIf { it > 0uL } ?: enteredSats.takeIf { invoiceSats != null && it > 0uL }

/**
* Whether the amount of an amountless Lightning invoice can be entered without the node: Spark can send, so an amount
* within its balance pays without channels. An LNURL payment still waits for the node.
*/
internal fun sparkCanTakeAmount(
payMethod: SendMethod,
invoiceSats: ULong?,
isLnurl: Boolean,
sparkState: SparkState,
): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats == 0uL && !isLnurl &&
sparkState.isUsable && sparkState.sendableSats > 0uL

internal fun lightningAmountLimit(cachedMax: ULong, sparkMax: ULong?, isNodeRunning: Boolean): ULong = when {
sparkMax == null -> cachedMax
isNodeRunning -> maxOf(cachedMax, sparkMax)
else -> sparkMax
}

/** Whether Spark can pay a Quick Pay invoice; an LNURL one still waits for the node. */
internal fun sparkCanPayQuickPay(data: QuickPayData, sparkState: SparkState): Boolean =
data is QuickPayData.Bolt11 && sparkCanPayInvoice(SendMethod.LIGHTNING, data.sats, sparkState)
Expand All @@ -140,6 +167,24 @@ internal fun waitsForNode(
return hasAnyChannels && !hasUsableChannels
}

/**
* Whether [route] comes before a payment is decoded: choosing, scanning or typing a recipient. Nothing there needs the
* node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step.
*/
internal fun isRecipientStep(route: SendRoute): Boolean = when (route) {
SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner, SendRoute.ComingSoon -> true
else -> false
}

internal fun NavDestination.isRecipientStep(): Boolean =
hasRoute<SendRoute.Recipient>() || hasRoute<SendRoute.Address>() ||
Comment thread
ovitrif marked this conversation as resolved.
Resolved
hasRoute<SendRoute.ContactSelect>() || hasRoute<SendRoute.QrScanner>() || hasRoute<SendRoute.ComingSoon>()

/** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */
internal fun NavDestination.isPastReview(): Boolean =
hasRoute<SendRoute.Pending>() || hasRoute<SendRoute.Success>() || hasRoute<SendRoute.Error>() ||
hasRoute<SendRoute.WithdrawError>() || hasRoute<SendRoute.QuickPay>()

internal fun NavDestination.isPaymentReview(): Boolean =
hasRoute<SendRoute.Confirm>() || hasRoute<SendRoute.PinCheck>() ||
hasRoute<SendRoute.RecoveryPinCheck>() || hasRoute<SendRoute.HardwareSign>()
Expand Down Expand Up @@ -187,21 +232,40 @@ fun SendSheet(
val isOffline by remember { derivedStateOf { connectivityState != ConnectivityState.CONNECTED } }
val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle()
val sendUiState by appViewModel.sendUiState.collectAsStateWithLifecycle()
val isWaitingForNode by appViewModel.isSendWaitingForNode.collectAsStateWithLifecycle()
val contacts by appViewModel.pubkyContacts.collectAsStateWithLifecycle()
var routingCacheResetAttempted by rememberSaveable(startDestination) { mutableStateOf(false) }

val hasAnyChannels = lightningState.channels.isNotEmpty()
val syncNodeVariant = if (hasAnyChannels) SyncNodeVariant.LIGHTNING else SyncNodeVariant.BITCOIN
val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle()
val sparkCanPay = sparkCanPayInvoice(sendUiState.payMethod, sendUiState.decodedInvoice?.amountSatoshis, sparkState)
val invoiceSats = sendUiState.decodedInvoice?.amountSatoshis
val sparkCanPay = sparkCanPayInvoice(
sendUiState.payMethod,
sendInvoiceSats(invoiceSats, sendUiState.amount),
sparkState,
)
val sparkTakesAmount = sparkCanTakeAmount(
payMethod = sendUiState.payMethod,
invoiceSats = invoiceSats,
isLnurl = sendUiState.lnurl != null,
sparkState = sparkState,
)
val navController = rememberNavController()
val entry by navController.currentBackStackEntryAsState()
// Until navigation settles the entry is null, and the sheet shows its start destination
val isRecipientStep = entry?.destination?.isRecipientStep() ?: isRecipientStep(startDestination)
val isAmountStep = entry?.destination?.hasRoute<SendRoute.Amount>() ?: (startDestination == SendRoute.Amount)
// A Spark payment can be submitted before the node runs, and its balance then no longer covers it
val isPastReview = entry?.destination?.isPastReview() == true
val shouldShowSyncOverlay = run {
if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false
if (sendUiState.hardwareWalletId != null) return@run false
if (sendUiState.hardwareWalletId != null || isPastReview) return@run false
waitsForNode(
isNodeRunning = lightningState.nodeLifecycleState.isRunning(),
hasAnyChannels = hasAnyChannels,
hasUsableChannels = lightningState.channels.any { it.isUsable },
sparkCanPay = sparkCanPay,
sparkCanPay = sparkCanPay || isAmountStep && sparkTakesAmount,
)
}

Expand Down Expand Up @@ -239,8 +303,6 @@ fun SendSheet(
.imePadding()
.testTag("SendSheet"),
) {
val navController = rememberNavController()
val entry by navController.currentBackStackEntryAsState()
val reviewing = entry?.destination?.isPaymentReview() == true
LaunchedEffect(reviewing, lifecycle, appViewModel) {
if (!reviewing) return@LaunchedEffect
Expand Down Expand Up @@ -410,6 +472,7 @@ fun SendSheet(
}
composableWithDefaultTransitions<SendRoute.Address> {
val uiState by appViewModel.sendUiState.collectAsStateWithLifecycle()
DisposableEffect(Unit) { onDispose { appViewModel.cancelAddressValidation() } }
SendAddressScreen(
uiState = uiState,
onBack = { navController.popBackStack() },
Expand Down Expand Up @@ -465,13 +528,23 @@ fun SendSheet(
val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle()
SendAmountScreen(
uiState = uiState,
nodeLifecycleState = if (uiState.hardwareWalletId != null) {
// Spark takes an amountless invoice's amount without the node, as a hardware wallet does
nodeLifecycleState = if (uiState.hardwareWalletId != null || sparkTakesAmount) {
NodeLifecycleState.Running
Comment thread
ovitrif marked this conversation as resolved.
Resolved
} else {
lightningState.nodeLifecycleState
},
canGoBack = startDestination != SendRoute.Amount || uiState.isPaymentRequest,
syncNodeVariant = syncNodeVariant,
balances = LocalBalances.current.let { balances ->
balances.copy(
maxSendLightningSats = lightningAmountLimit(
cachedMax = balances.maxSendLightningSats,
sparkMax = sparkState.sendableSats.takeIf { sparkTakesAmount },
isNodeRunning = lightningState.nodeLifecycleState.isRunning(),
),
)
},
Comment thread
ovitrif marked this conversation as resolved.
Resolved
onBack = {
if (!navController.popBackStack()) {
appViewModel.hideSheet()
Expand Down Expand Up @@ -957,7 +1030,8 @@ fun SendSheet(
}

AnimatedVisibility(
visible = shouldShowSyncOverlay && !isOffline,
// A recipient step shows it only while a scanned payment waits for the node
visible = (if (isRecipientStep) isWaitingForNode else shouldShowSyncOverlay) && !isOffline,
enter = fadeIn(),
exit = fadeOut(),
) {
Expand Down
Loading