diff --git a/app/src/main/java/to/bitkit/data/SettingsStore.kt b/app/src/main/java/to/bitkit/data/SettingsStore.kt index 5c092a5e0b..302c60af8b 100644 --- a/app/src/main/java/to/bitkit/data/SettingsStore.kt +++ b/app/src/main/java/to/bitkit/data/SettingsStore.kt @@ -247,7 +247,6 @@ data class SettingsData( val isPinForPaymentsEnabled: Boolean = false, val isDevModeEnabled: Boolean = Env.isDebug, val disableAllToasts: Boolean = false, - val isSavingsSwapEnabled: Boolean = false, val showWidgets: Boolean = true, val lastUsedTags: List = emptyList(), val enableSwipeToHideBalance: Boolean = true, diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index bd16f68e93..d8ac9f0426 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -86,13 +86,6 @@ internal object Env { val ldkLogLevel = LogLevel.TRACE - /** - * Whether LN -> onchain swaps can reach a Boltz backend. Boltz only serves a public API on - * mainnet: its testnet deployment is deprecated and regtest resolves to a local backend that - * no build of ours can reach. Elsewhere the transfer to savings closes a channel instead. - */ - 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. diff --git a/app/src/main/java/to/bitkit/services/BoltzService.kt b/app/src/main/java/to/bitkit/services/BoltzService.kt deleted file mode 100644 index 5b162554dc..0000000000 --- a/app/src/main/java/to/bitkit/services/BoltzService.kt +++ /dev/null @@ -1,208 +0,0 @@ -package to.bitkit.services - -import com.synonym.bitkitcore.BoltzEventListener -import com.synonym.bitkitcore.BoltzNetwork -import com.synonym.bitkitcore.BoltzPairInfo -import com.synonym.bitkitcore.BoltzSwap -import com.synonym.bitkitcore.BoltzSwapEvent -import com.synonym.bitkitcore.ReverseSwapResponse -import com.synonym.bitkitcore.SubmarineSwapResponse -import com.synonym.bitkitcore.boltzClaimReverseSwap -import com.synonym.bitkitcore.boltzCreateReverseSwap -import com.synonym.bitkitcore.boltzCreateSubmarineSwap -import com.synonym.bitkitcore.boltzGetReverseLimits -import com.synonym.bitkitcore.boltzGetSubmarineLimits -import com.synonym.bitkitcore.boltzGetSwap -import com.synonym.bitkitcore.boltzListPendingSwaps -import com.synonym.bitkitcore.boltzListSwaps -import com.synonym.bitkitcore.boltzRefundSubmarineSwap -import com.synonym.bitkitcore.boltzStartSwapUpdates -import com.synonym.bitkitcore.boltzStopSwapUpdates -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.SharedFlow -import kotlinx.coroutines.flow.asSharedFlow -import kotlinx.coroutines.flow.first -import org.lightningdevkit.ldknode.Network -import to.bitkit.data.SettingsStore -import to.bitkit.data.keychain.Keychain -import to.bitkit.env.Env -import to.bitkit.utils.Logger -import to.bitkit.utils.ServiceError -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Thin wrapper around the bitkit-core Boltz swaps FFI (submarine + reverse swaps between onchain - * Bitcoin and Lightning). A Hilt singleton that bridges the [BoltzEventListener] callback to a - * [SharedFlow]; swap keys are re-derived from the wallet mnemonic on demand, never persisted. - */ -@Singleton -class BoltzService @Inject constructor( - private val keychain: Keychain, - private val settingsStore: SettingsStore, -) { - private val _events = MutableSharedFlow(extraBufferCapacity = 64) - - /** Swap lifecycle events emitted while the updates stream is running. */ - val events: SharedFlow = _events.asSharedFlow() - - private val listener = object : BoltzEventListener { - override fun onEvent(event: BoltzSwapEvent) { - Logger.info("Boltz event: $event", context = TAG) - _events.tryEmit(event) - } - } - - // region Limits - - suspend fun submarineLimits(network: BoltzNetwork = boltzNetwork()): BoltzPairInfo = - boltzGetSubmarineLimits(network = network) - - suspend fun reverseLimits(network: BoltzNetwork = boltzNetwork()): BoltzPairInfo = - boltzGetReverseLimits(network = network) - - // endregion - - // region Create - - /** Submarine swap: onchain BTC -> Lightning. Fund the returned lockup address. */ - suspend fun createSubmarineSwap( - invoice: String, - network: BoltzNetwork = boltzNetwork(), - electrumUrl: String? = null, - ): SubmarineSwapResponse { - val (mnemonic, passphrase) = credentials() - return boltzCreateSubmarineSwap( - network = network, - electrumUrl = electrumUrl ?: electrumUrl(), - invoice = invoice, - mnemonic = mnemonic, - bip39Passphrase = passphrase, - ).also { Logger.info("Created Boltz submarine swap ${it.id}", context = TAG) } - } - - /** Reverse swap: Lightning -> onchain BTC. Pay the returned hold invoice. */ - suspend fun createReverseSwap( - amountSat: ULong, - claimAddress: String, - network: BoltzNetwork = boltzNetwork(), - electrumUrl: String? = null, - ): ReverseSwapResponse { - val (mnemonic, passphrase) = credentials() - return boltzCreateReverseSwap( - network = network, - electrumUrl = electrumUrl ?: electrumUrl(), - amountSat = amountSat, - claimAddress = claimAddress, - mnemonic = mnemonic, - bip39Passphrase = passphrase, - ).also { Logger.info("Created Boltz reverse swap ${it.id}", context = TAG) } - } - - // endregion - - // region Query - - suspend fun listSwaps(): List = boltzListSwaps() - - suspend fun listPendingSwaps(): List = boltzListPendingSwaps() - - suspend fun getSwap(id: String): BoltzSwap? = boltzGetSwap(swapId = id) - - // endregion - - // region Manual claim / refund - - suspend fun claimReverseSwap(id: String, feeRateSatPerVb: Double? = null): String { - val (mnemonic, passphrase) = credentials() - return boltzClaimReverseSwap( - swapId = id, - mnemonic = mnemonic, - bip39Passphrase = passphrase, - feeRateSatPerVb = feeRateSatPerVb, - ) - } - - suspend fun refundSubmarineSwap(id: String, refundAddress: String, feeRateSatPerVb: Double? = null): String { - val (mnemonic, passphrase) = credentials() - return boltzRefundSubmarineSwap( - swapId = id, - refundAddress = refundAddress, - mnemonic = mnemonic, - bip39Passphrase = passphrase, - feeRateSatPerVb = feeRateSatPerVb, - ) - } - - // endregion - - // region Updates stream - - /** - * Open the Boltz updates WebSocket, subscribe all pending swaps and auto-claim - * reverse swaps. [feeRateSatPerVb] is the rate used for those auto-claims - * (Bitkit owns fee estimation). [acceptZeroConf] claims a reverse swap as soon - * as its lockup hits the mempool instead of waiting for its confirmation. - * Replaces any running stream. - */ - suspend fun startUpdates( - feeRateSatPerVb: Double?, - acceptZeroConf: Boolean, - network: BoltzNetwork = boltzNetwork(), - ) { - val (mnemonic, passphrase) = credentials() - boltzStartSwapUpdates( - network = network, - listener = listener, - mnemonic = mnemonic, - bip39Passphrase = passphrase, - feeRateSatPerVb = feeRateSatPerVb, - acceptZeroConf = acceptZeroConf, - ) - Logger.info("Started Boltz updates stream on $network", context = TAG) - } - - suspend fun stopUpdates() { - boltzStopSwapUpdates() - Logger.info("Stopped Boltz updates stream", context = TAG) - } - - // endregion - - // region Helpers - - /** Whether the configured network has a reachable Boltz backend. See [Env.isSwapSupported]. */ - val isSwapSupported: Boolean get() = Env.isSwapSupported - - /** - * Whether swaps may run: the network needs a reachable Boltz backend and the savings swap - * flow must be switched on in dev settings, since its UI is not final yet. - */ - suspend fun isSwapEnabled(): Boolean = isSwapSupported && settingsStore.data.first().isSavingsSwapEnabled - - /** The Boltz network matching the app's configured network. */ - fun boltzNetwork(network: Network = Env.network): BoltzNetwork = when (network) { - Network.BITCOIN -> BoltzNetwork.MAINNET - Network.TESTNET -> BoltzNetwork.TESTNET - Network.REGTEST -> BoltzNetwork.REGTEST - // Boltz does not operate on signet; fall back to testnet for development. - else -> BoltzNetwork.TESTNET - } - - /** Current Electrum URL, used by Boltz for claim/refund broadcasting. */ - suspend fun electrumUrl(): String = settingsStore.data.first().electrumServer - - private suspend fun credentials(): Pair { - val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) - ?: throw ServiceError.MnemonicNotFound() - val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) - ?.takeIf { it.isNotEmpty() } - return mnemonic to passphrase - } - - // endregion - - companion object { - private const val TAG = "BoltzService" - } -} diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 8ec94ab942..ed40c20f0a 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -189,8 +189,6 @@ import to.bitkit.ui.settings.LogDetailScreen import to.bitkit.ui.settings.LogsScreen import to.bitkit.ui.settings.OrderDetailScreen import to.bitkit.ui.settings.SettingsScreen -import to.bitkit.ui.settings.SwapDetailScreen -import to.bitkit.ui.settings.SwapsScreen import to.bitkit.ui.settings.advanced.AddressTypePreferenceScreen import to.bitkit.ui.settings.advanced.AddressViewerScreen import to.bitkit.ui.settings.advanced.CoinSelectPreferenceScreen @@ -1085,8 +1083,6 @@ private fun RootNavHost( channelOrdersSettings(navController) orderDetailSettings(navController) cjitDetailSettings(navController) - swapsSettings(navController) - swapDetailSettings(navController) lightningConnections( navController, walletViewModel, @@ -1183,7 +1179,6 @@ private fun RootNavHost( wallet = walletViewModel, transfer = transferViewModel, onContinueClick = { navController.navigateOnSavingsTransferExit() }, - onTransferUnavailable = { navController.navigateOnSavingsTransferExit() }, ) } deepLinkableComposable { @@ -2072,28 +2067,6 @@ private fun NavGraphBuilder.cjitDetailSettings( } } -private fun NavGraphBuilder.swapsSettings( - navController: NavHostController, -) { - deepLinkableComposable { - SwapsScreen( - onBackClick = { navController.popBackStack() }, - onSwapItemClick = { navController.navigateToSwapDetail(it) }, - ) - } -} - -private fun NavGraphBuilder.swapDetailSettings( - navController: NavHostController, -) { - deepLinkableComposable { - SwapDetailScreen( - swapItem = it.toRoute(), - onBackClick = { navController.popBackStack() }, - ) - } -} - private fun NavGraphBuilder.lightningConnections( navController: NavHostController, walletViewModel: WalletViewModel, @@ -2462,7 +2435,6 @@ fun NavController.navigateToLocalCurrencySettings() = navigateTo(Routes.LocalCur fun NavController.navigateToBackupSettings() = navigateTo(Routes.BackupSettings) fun NavController.navigateToOrderDetail(id: String) = navigateTo(Routes.OrderDetail(id)) -fun NavController.navigateToSwapDetail(id: String) = navigateTo(Routes.SwapDetail(id)) fun NavController.navigateToCjitDetail(id: String) = navigateTo(Routes.CjitDetail(id)) @@ -2670,12 +2642,6 @@ sealed interface Routes { @Serializable data object ChannelOrdersSettings : Routes.DeepLinkable - @Serializable - data object SwapsSettings : Routes.DeepLinkable - - @Serializable - data class SwapDetail(val id: String) : Routes.DeepLinkable - @Serializable data object Logs : Routes.DeepLinkable diff --git a/app/src/main/java/to/bitkit/ui/components/Slider.kt b/app/src/main/java/to/bitkit/ui/components/Slider.kt index c9531d61fb..2b7ee12a03 100644 --- a/app/src/main/java/to/bitkit/ui/components/Slider.kt +++ b/app/src/main/java/to/bitkit/ui/components/Slider.kt @@ -20,7 +20,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -36,7 +35,6 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.SubcomposeLayout -import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag @@ -60,9 +58,6 @@ import kotlin.math.abs import kotlin.math.roundToInt private const val KNOB_SIZE_DP = 32 - -/** Horizontal inset so the knob stays clear of the screen edge and its system back-gesture zone. */ -private const val SLIDER_EDGE_INSET_DP = 16 private const val TRACK_HEIGHT_DP = 8 private const val STEP_MARKER_WIDTH_DP = 4 private const val STEP_MARKER_HEIGHT_DP = 16 @@ -354,123 +349,6 @@ private fun StepSliderLabels( } } -/** - * Continuous slider over a [min]..[max] range, styled to match [Slider] (same track and - * knob) but without discrete steps. Used to pick a transfer amount within its allowed limits. - */ -@Composable -fun AmountSlider( - value: Long, - min: Long, - max: Long, - onValueChange: (Long) -> Unit, - modifier: Modifier = Modifier, -) { - val density = LocalDensity.current - val coroutineScope = rememberCoroutineScope() - - var sliderWidth by remember { mutableIntStateOf(0) } - val knobPosition = remember { Animatable(0f) } - val span = (max - min).coerceAtLeast(1) - - fun fractionFor(v: Long): Float = ((v - min).toFloat() / span).coerceIn(0f, 1f) - - fun valueFor(logicalPositionPx: Float): Long { - if (sliderWidth == 0) return min - val fraction = (logicalPositionPx / sliderWidth).coerceIn(0f, 1f) - return (min + (fraction * span).roundToInt()).coerceIn(min, max) - } - - // Keep the knob in sync with external value changes (and initial layout). - LaunchedEffect(value, sliderWidth) { - if (sliderWidth > 0) { - knobPosition.snapTo(fractionFor(value) * sliderWidth) - } - } - - val widthPx = sliderWidth.toFloat() - - Box( - modifier = modifier - .fillMaxWidth() - .systemGestureExclusion() - .padding(horizontal = SLIDER_EDGE_INSET_DP.dp) - .height(KNOB_SIZE_DP.dp) - .onGloballyPositioned { sliderWidth = it.size.width } - ) { - Canvas( - modifier = Modifier - .fillMaxWidth() - .height(KNOB_SIZE_DP.dp) - .pointerInput(sliderWidth, min, max) { - detectTapGestures { offset -> - val v = valueFor(offset.x) - coroutineScope.launch { knobPosition.snapTo(fractionFor(v) * widthPx) } - onValueChange(v) - } - } - ) { - val trackY = center.y - val trackHeight = density.run { TRACK_HEIGHT_DP.dp.toPx() } - val cornerRadius = density.run { 3.dp.toPx() } - - // Inactive track - drawRoundRect( - color = Colors.Green32, - topLeft = Offset(0f, trackY - trackHeight / 2), - size = Size(size.width, trackHeight), - cornerRadius = CornerRadius(cornerRadius), - ) - // Active track - if (knobPosition.value > 0) { - drawRoundRect( - color = Colors.Green, - topLeft = Offset(0f, trackY - trackHeight / 2), - size = Size(knobPosition.value, trackHeight), - cornerRadius = CornerRadius(cornerRadius), - ) - } - } - - // Knob - Box( - modifier = Modifier - .offset { - IntOffset( - x = (knobPosition.value - with(density) { KNOB_SIZE_DP.dp.toPx() / 2 }).roundToInt(), - y = 0, - ) - } - .size(KNOB_SIZE_DP.dp) - .pointerInput(sliderWidth, min, max) { - detectHorizontalDragGestures { _, dragAmount -> - coroutineScope.launch { - val newPosition = (knobPosition.value + dragAmount) - .coerceIn(0f, widthPx) - knobPosition.snapTo(newPosition) - onValueChange(valueFor(newPosition)) - } - } - } - ) { - Box( - modifier = Modifier - .size(KNOB_SIZE_DP.dp) - .clip(CircleShape) - .background(Colors.Green) - ) { - Box( - modifier = Modifier - .size(16.dp) - .clip(CircleShape) - .background(Colors.White) - .align(Alignment.Center) - ) - } - } - } -} - @Preview @Composable private fun Preview() { @@ -486,22 +364,6 @@ private fun Preview() { } } -@Preview -@Composable -private fun PreviewUnitStops() { - AppThemeSurface { - var value by remember { mutableLongStateOf(72_000L) } - Column(modifier = Modifier.padding(32.dp)) { - AmountSlider( - value = value, - min = 50_000L, - max = 100_000L, - onValueChange = { value = it }, - ) - } - } -} - @Preview @Composable private fun PreviewVerticalStack() { diff --git a/app/src/main/java/to/bitkit/ui/screens/settings/DevSettingsScreen.kt b/app/src/main/java/to/bitkit/ui/screens/settings/DevSettingsScreen.kt index 87c111fbeb..7f40a15264 100644 --- a/app/src/main/java/to/bitkit/ui/screens/settings/DevSettingsScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/settings/DevSettingsScreen.kt @@ -57,7 +57,6 @@ fun DevSettingsScreen( val isPaykitEnabled by settings.isPaykitEnabled.collectAsStateWithLifecycle() val areAllowancesEnabled by settings.areAllowancesEnabled.collectAsStateWithLifecycle() val disableAllToasts by settings.disableAllToasts.collectAsStateWithLifecycle() - val isSavingsSwapEnabled by settings.isSavingsSwapEnabled.collectAsStateWithLifecycle() val subscriptionClockOffsetDays by settings.subscriptionClockOffsetDays.collectAsStateWithLifecycle() val wakeState by viewModel.wakeState.collectAsStateWithLifecycle() var showPaykitWarning by remember { mutableStateOf(false) } @@ -86,15 +85,6 @@ fun DevSettingsScreen( switchTestTag = "DisableAllToastsToggle", ) - SectionHeader("SWAPS") - SettingsButtonRow("Swaps") { navController.navigateTo(Routes.SwapsSettings) } - SettingsSwitchRow( - title = "Enable Savings Swap", - isChecked = isSavingsSwapEnabled, - onClick = { settings.setIsSavingsSwapEnabled(!isSavingsSwapEnabled) }, - switchTestTag = "SavingsSwapToggle", - ) - SectionHeader("RECOVERY") SettingsButtonRow("Legacy Close Recovery") { navController.navigateTo(Routes.LegacyRnRecovery) } diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index a8d9cce752..9bc94a47a9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -37,9 +37,7 @@ import kotlinx.coroutines.launch import to.bitkit.R import to.bitkit.ext.amountOnClose import to.bitkit.ext.filterOpen -import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.safe -import to.bitkit.ui.components.AmountSlider import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.ButtonSize import to.bitkit.ui.components.Caption13Up @@ -50,7 +48,6 @@ import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.MoneyDisplay import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SwipeToConfirm -import to.bitkit.ui.components.TertiaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.currencyViewModel import to.bitkit.ui.scaffold.AppTopBar @@ -62,8 +59,6 @@ import to.bitkit.ui.transferViewModel import to.bitkit.ui.utils.withAccent import to.bitkit.ui.walletViewModel import to.bitkit.viewmodels.SavingsSelection -import to.bitkit.viewmodels.SavingsSwapQuote -import to.bitkit.viewmodels.SavingsTransferMode @Composable fun SavingsConfirmScreen( @@ -98,7 +93,6 @@ fun SavingsConfirmScreen( val channelsAmount = channels.sumOf { it.amountOnClose } val sparkAmount = if (withdrawsSpark) sparkSats else 0uL - val swapState by transfer.savingsSwapState.collectAsStateWithLifecycle() val sparkFeeSats by transfer.sparkWithdrawFeeSats.collectAsStateWithLifecycle() val isSparkFeePricing by transfer.isSparkFeePricing.collectAsStateWithLifecycle() @@ -107,19 +101,13 @@ fun SavingsConfirmScreen( wallet.refreshBalances() } - // Present the swap fee before the user commits. Recomputed when the amount changes. - // A zero amount clears an earlier quote, so a Spark-only transfer never swaps channel funds. - LaunchedEffect(channelsAmount) { - transfer.loadSavingsSwapQuote(channelsAmount, channels.totalNextOutboundHtlcLimitSats()) - } - LaunchedEffect(pricesSpark, sparkSats) { if (pricesSpark) transfer.loadSparkWithdrawFee(sparkSats) } Box { SavingsConfirmContent( - fallbackAmount = channelsAmount, + channelsAmount = channelsAmount, sparkAmount = sparkAmount, sparkFeeSats = sparkFeeSats.takeIf { withdrawsSpark }, // Spark's part moves only at the fee shown, so nothing is confirmed before it is priced. @@ -127,12 +115,6 @@ fun SavingsConfirmScreen( isSparkUnpriced = withdrawsSpark && sparkFeeSats == null || isOnlySparkTooSmall, isNothingSelected = channels.isEmpty() && !withdrawsSpark, isSparkTooSmall = isOnlySparkTooSmall, - isSwapEnabled = swapState.isSwapEnabled, - quote = swapState.quote, - isQuoteLoading = swapState.isLoading, - minSat = swapState.minSat, - maxSat = swapState.maxSat, - onAmountChange = { transfer.onSwapAmountChange(it.toULong()) }, hasMultiple = hasMultiple, hasSelected = hasSelected, onBackClick = onBackClick, @@ -144,10 +126,6 @@ fun SavingsConfirmScreen( transfer.confirmSavingsSwipe(channels, withdrawsSpark, shownSparkSats, shownFeeSats) .also { if (it) onConfirm() } }, - onCloseConfirm = { - transfer.onTransferToSavingsConfirm(channels, withdrawsSpark, SavingsTransferMode.CLOSE, sparkFeeSats) - onConfirm() - }, ) AnimatedVisibility( visible = isOffline, @@ -164,19 +142,13 @@ fun SavingsConfirmScreen( @Composable internal fun SavingsConfirmContent( - fallbackAmount: ULong, + channelsAmount: ULong, sparkAmount: ULong, sparkFeeSats: ULong?, isSparkFeePricing: Boolean, isSparkUnpriced: Boolean, isNothingSelected: Boolean = false, isSparkTooSmall: Boolean, - isSwapEnabled: Boolean, - quote: SavingsSwapQuote?, - isQuoteLoading: Boolean, - minSat: ULong, - maxSat: ULong, - onAmountChange: (Long) -> Unit, hasMultiple: Boolean, hasSelected: Boolean, onBackClick: () -> Unit = {}, @@ -185,15 +157,9 @@ internal fun SavingsConfirmContent( onSelectAllClick: () -> Unit = {}, onSparkFeeRetry: () -> Unit = {}, onSwipeConfirm: (shownSparkSats: ULong, shownFeeSats: ULong?) -> Boolean = { _, _ -> true }, - onCloseConfirm: () -> Unit = {}, ) { val scope = rememberCoroutineScope() - val headlineAmount = (quote?.amountSat ?: fallbackAmount).safe() + sparkAmount.safe() - val sparkReceive = sparkAmount.safe() - (sparkFeeSats ?: 0uL).safe() - val receiveAmount = (quote?.receiveSat ?: 0uL).safe() + sparkReceive.safe() - // Only show the swap-pricing spinner while swaps are enabled and a quote is still being fetched; - // otherwise the swipe just falls back to closing the channel and there is nothing to wait for. - val isPricingSwap = isSwapEnabled && quote == null && isQuoteLoading + val headlineAmount = channelsAmount.safe() + sparkAmount.safe() ScreenColumn { AppTopBar( titleText = stringResource(R.string.lightning__transfer__nav_title), @@ -227,49 +193,8 @@ internal fun SavingsConfirmContent( VerticalSpacer(16.dp) MoneyDisplay(sats = headlineAmount.toLong(), onClick = onAmountClick) - if (quote != null) { - VerticalSpacer(24.dp) - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.height(IntrinsicSize.Min), - ) { - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__network_fee), - amount = quote.networkFeeSat.toLong(), - ) - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__service_fee), - amount = quote.swapFeeSat.toLong(), - ) - } - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.height(IntrinsicSize.Min), - ) { - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__amount), - amount = headlineAmount.toLong(), - ) - FeeInfo( - label = stringResource(R.string.lightning__savings_confirm__receive), - amount = receiveAmount.toLong(), - ) - } - - // Adjust how much to move to savings, bounded to a payable range. - if (maxSat > minSat) { - VerticalSpacer(28.dp) - AmountSlider( - value = quote.amountSat.toLong(), - min = minSat.toLong(), - max = maxSat.toLong(), - onValueChange = onAmountChange, - ) - } - } - if (sparkFeeSats != null || isSparkFeePricing) { - VerticalSpacer(if (quote != null) 0.dp else 16.dp) + VerticalSpacer(16.dp) Row( horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.height(IntrinsicSize.Min), @@ -317,15 +242,13 @@ internal fun SavingsConfirmContent( } } - // The swipe always commits the transfer: it swaps when a quote is ready and otherwise - // falls back to the pre-swap behaviour of closing the channel, so it is never inert. var isLoading by remember { mutableStateOf(false) } // Read at swipe time, as the swipe's gesture keeps the lambda from the composition it started in. val shownSpark by rememberUpdatedState(sparkAmount to sparkFeeSats) val commitSwipe by rememberUpdatedState(onSwipeConfirm) SwipeToConfirm( text = stringResource(R.string.lightning__transfer__swipe), - loading = isLoading || isPricingSwap || isSparkFeePricing, + loading = isLoading || isSparkFeePricing, enabled = !isSparkUnpriced && !isNothingSelected, confirmed = isLoading, color = Colors.Brand, @@ -339,15 +262,6 @@ internal fun SavingsConfirmContent( } } ) - if (quote != null) { - VerticalSpacer(12.dp) - // Fallback: drain a whole channel on-chain by closing it instead of swapping. - TertiaryButton( - text = stringResource(R.string.lightning__savings_confirm__close_instead), - enabled = !isSparkUnpriced && !isNothingSelected, - onClick = onCloseConfirm, - ) - } VerticalSpacer(16.dp) } } @@ -381,23 +295,12 @@ private fun SparkFeeError(onRetry: () -> Unit) { private fun SavingsConfirmScreenPreview() { AppThemeSurface { SavingsConfirmContent( - fallbackAmount = 50_123u, + channelsAmount = 50_123u, sparkAmount = 12_000u, sparkFeeSats = 1_470u, isSparkFeePricing = false, isSparkUnpriced = false, isSparkTooSmall = false, - isSwapEnabled = true, - quote = SavingsSwapQuote( - amountSat = 50_123u, - networkFeeSat = 320u, - swapFeeSat = 125u, - receiveSat = 49_678u, - ), - isQuoteLoading = false, - minSat = 25_000u, - maxSat = 72_000u, - onAmountChange = {}, hasMultiple = true, hasSelected = false, ) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt index 69a0a2702f..672fb4e7bf 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsProgressScreen.kt @@ -22,7 +22,6 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay import to.bitkit.R import to.bitkit.models.Toast @@ -43,8 +42,6 @@ import to.bitkit.ui.utils.removeAccentTags import to.bitkit.ui.utils.withAccent import to.bitkit.ui.utils.withAccentBoldBright import to.bitkit.viewmodels.AppViewModel -import to.bitkit.viewmodels.SavingsSwapResult -import to.bitkit.viewmodels.SavingsTransferMode import to.bitkit.viewmodels.TransferViewModel import to.bitkit.viewmodels.WalletViewModel @@ -54,11 +51,9 @@ fun SavingsProgressScreen( transfer: TransferViewModel, wallet: WalletViewModel, onContinueClick: () -> Unit = {}, - onTransferUnavailable: () -> Unit = {}, ) { val resources = LocalResources.current var progressState by remember { mutableStateOf(SavingsProgressState.PROGRESS) } - val swapResult by transfer.savingsSwapResult.collectAsStateWithLifecycle() // Spark's withdrawal failed: its balance stayed in Spending, so the transfer is not reported as done. fun toastSparkFailure(movesChannels: Boolean) { @@ -85,70 +80,22 @@ fun SavingsProgressScreen( // Effect to execute the transfer & update UI LaunchedEffect(Unit) { - when (transfer.savingsTransferMode.value) { - // The swap itself is owned by the viewmodel so it survives leaving this screen; - // the outcome arrives via savingsSwapResult below. Ensure the updates stream is - // running first so the new swap is tracked and auto-claimed once its lockup appears. - SavingsTransferMode.SWAP -> { - wallet.ensureSwapUpdatesRunning() - transfer.startSavingsSwap() - } - - SavingsTransferMode.CLOSE -> runChannelClose( - transfer = transfer, - wallet = wallet, - onSuccess = { - if (transfer.isSparkWithdrawFailed.value) { - showSparkFailure(movesChannels = transfer.hasChannelsToClose()) - } else { - progressState = SavingsProgressState.SUCCESS - } - }, - onInterrupted = { - if (transfer.isSparkWithdrawFailed.value) toastSparkFailure(movesChannels = true) - progressState = SavingsProgressState.INTERRUPTED - }, - onGiveUp = { app.showSheet(Sheet.ForceTransfer) }, - ) - } - } - - LaunchedEffect(swapResult) { - when (val result = swapResult) { - is SavingsSwapResult.Success if transfer.isSparkWithdrawFailed.value -> { - wallet.refreshState() - showSparkFailure(movesChannels = true) - } - - is SavingsSwapResult.Success -> { - wallet.refreshState() - progressState = SavingsProgressState.SUCCESS - } - - // The hold invoice is paid but the on-chain claim has not landed within the wait - // window. The claim is auto-broadcast once the lockup appears, so the transfer is - // committed and settling; show that honestly instead of a completed success. - SavingsSwapResult.Pending if transfer.isSparkWithdrawFailed.value -> { - wallet.refreshState() - showSparkFailure(movesChannels = true) - } - - SavingsSwapResult.Pending -> { - wallet.refreshState() - progressState = SavingsProgressState.SETTLING - } - - is SavingsSwapResult.Failure -> { - app.toast( - type = Toast.ToastType.ERROR, - title = resources.getString(R.string.common__error), - description = result.reason, - ) - onTransferUnavailable() - } - - null -> Unit - } + runChannelClose( + transfer = transfer, + wallet = wallet, + onSuccess = { + if (transfer.isSparkWithdrawFailed.value) { + showSparkFailure(movesChannels = transfer.hasChannelsToClose()) + } else { + progressState = SavingsProgressState.SUCCESS + } + }, + onInterrupted = { + if (transfer.isSparkWithdrawFailed.value) toastSparkFailure(movesChannels = true) + progressState = SavingsProgressState.INTERRUPTED + }, + onGiveUp = { app.showSheet(Sheet.ForceTransfer) }, + ) } SavingsProgressContent( @@ -167,7 +114,7 @@ private const val INNER_RING_SHARE = 207f / 311f /** The figure's square against the outer ring, iOS's 256 of 311 pt. */ private const val FIGURE_SHARE = 256f / 311f -/** Legacy path: cooperatively close the selected channel(s), retrying on failure. */ +/** Cooperatively close the selected channel(s), retrying on failure. */ private suspend fun runChannelClose( transfer: TransferViewModel, wallet: WalletViewModel, @@ -200,13 +147,11 @@ internal fun SavingsProgressContent( onContinueClick: () -> Unit = {}, ) { val inProgress = progressState == SavingsProgressState.PROGRESS - val showAnimation = inProgress || progressState == SavingsProgressState.SETTLING val isSparkFailed = progressState.isSparkFailed ScreenColumn( modifier = modifier.testTag( when (progressState) { SavingsProgressState.PROGRESS -> "TransferSettingUp" - SavingsProgressState.SETTLING -> "TransferSettling" SavingsProgressState.SPARK_FAILED, SavingsProgressState.SPARK_FAILED_PARTIAL, -> "SavingsSparkFailed" @@ -218,7 +163,6 @@ internal fun SavingsProgressContent( AppTopBar( titleText = when (progressState) { SavingsProgressState.PROGRESS, - SavingsProgressState.SETTLING, SavingsProgressState.SPARK_FAILED, SavingsProgressState.SPARK_FAILED_PARTIAL, -> stringResource(R.string.lightning__transfer__nav_title) @@ -240,7 +184,7 @@ internal fun SavingsProgressContent( VerticalSpacer(12.dp) ProgressMessage(progressState = progressState) FillHeight() - if (showAnimation) { + if (inProgress) { TransferAnimationView( largeCircleRes = R.drawable.onchain_sync_large, smallCircleRes = R.drawable.onchain_sync_small, @@ -299,9 +243,6 @@ private fun ProgressMessage(progressState: SavingsProgressState) { SavingsProgressState.PROGRESS -> R.string.lightning__savings_progress__title to R.string.lightning__savings_progress__text - SavingsProgressState.SETTLING -> - R.string.lightning__savings_settling__title to R.string.lightning__savings_settling__text - SavingsProgressState.SUCCESS -> R.string.lightning__transfer_success__title_savings to R.string.lightning__transfer_success__text_savings @@ -324,7 +265,7 @@ private fun ProgressMessage(progressState: SavingsProgressState) { /** `SPARK_FAILED_PARTIAL`: Spark's balance did not move, while the selected channels still did. */ enum class SavingsProgressState { - PROGRESS, SETTLING, SUCCESS, INTERRUPTED, SPARK_FAILED, SPARK_FAILED_PARTIAL; + PROGRESS, SUCCESS, INTERRUPTED, SPARK_FAILED, SPARK_FAILED_PARTIAL; val isSparkFailed get() = this == SPARK_FAILED || this == SPARK_FAILED_PARTIAL } @@ -339,16 +280,6 @@ private fun PreviewProgress() { } } -@Preview(showSystemUi = true) -@Composable -private fun PreviewSettling() { - AppThemeSurface { - SavingsProgressContent( - progressState = SavingsProgressState.SETTLING, - ) - } -} - @Preview(showSystemUi = true) @Composable private fun PreviewSuccess() { diff --git a/app/src/main/java/to/bitkit/ui/settings/SwapsScreen.kt b/app/src/main/java/to/bitkit/ui/settings/SwapsScreen.kt deleted file mode 100644 index c95687a0ab..0000000000 --- a/app/src/main/java/to/bitkit/ui/settings/SwapsScreen.kt +++ /dev/null @@ -1,282 +0,0 @@ -package to.bitkit.ui.settings - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material3.Card -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.synonym.bitkitcore.BoltzSwap -import kotlinx.collections.immutable.ImmutableList -import to.bitkit.ext.formatToString -import to.bitkit.models.Toast -import to.bitkit.models.formatToModernDisplay -import to.bitkit.ui.Routes -import to.bitkit.ui.appViewModel -import to.bitkit.ui.components.BodyS -import to.bitkit.ui.components.CaptionB -import to.bitkit.ui.components.Footnote -import to.bitkit.ui.components.HorizontalSpacer -import to.bitkit.ui.components.PrimaryButton -import to.bitkit.ui.components.settings.DetailRow -import to.bitkit.ui.components.settings.InfoCard -import to.bitkit.ui.components.settings.InfoCell -import to.bitkit.ui.components.settings.cardColors -import to.bitkit.ui.scaffold.AppTopBar -import to.bitkit.ui.shared.modifiers.clickableAlpha -import to.bitkit.ui.theme.AppShapes -import to.bitkit.ui.theme.Colors -import to.bitkit.ui.utils.copyToClipboard -import to.bitkit.viewmodels.SwapsViewModel -import to.bitkit.viewmodels.isClaimable - -@Composable -fun SwapsScreen( - onBackClick: () -> Unit, - onSwapItemClick: (String) -> Unit, - viewModel: SwapsViewModel = hiltViewModel(), -) { - val swaps by viewModel.swaps.collectAsStateWithLifecycle() - val error by viewModel.error.collectAsStateWithLifecycle() - - SwapsContent( - swaps = swaps, - error = error, - onBack = onBackClick, - onClickSwap = onSwapItemClick, - ) -} - -@Composable -private fun SwapsContent( - swaps: ImmutableList, - error: String?, - modifier: Modifier = Modifier, - onBack: () -> Unit = {}, - onClickSwap: (String) -> Unit = {}, -) { - Scaffold( - topBar = { AppTopBar(titleText = "Swaps", onBackClick = onBack) }, - modifier = modifier, - ) { padding -> - LazyColumn( - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.padding(padding), - ) { - error?.let { - item { BodyS(text = "Error: $it") } - } - if (swaps.isEmpty()) { - item { BodyS(text = "No swaps found…") } - } else { - items(swaps) { swap -> SwapCard(swap, onClickSwap) } - } - } - } -} - -@Composable -private fun SwapCard(model: BoltzSwap, onClick: (String) -> Unit) { - Card( - colors = cardColors, - modifier = Modifier - .fillMaxWidth() - .clickableAlpha { onClick(model.id) } - ) { - Column( - verticalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier - .fillMaxWidth() - .padding(16.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - CaptionB( - text = model.id, - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - modifier = Modifier - .weight(1f) - .clickableAlpha(onClick = copyToClipboard(model.id)) - ) - HorizontalSpacer(8.dp) - Surface(color = Colors.White16, shape = AppShapes.small) { - Footnote( - text = model.status.toString(), - color = Colors.White64, - maxLines = 1, - modifier = Modifier.padding(4.dp) - ) - } - } - - Row( - horizontalArrangement = Arrangement.SpaceBetween, - modifier = Modifier.fillMaxWidth(), - ) { - InfoCell(label = "Type", value = model.swapType.toString()) - InfoCell( - label = "Amount", - value = "${model.amountSat.formatToModernDisplay()} sats", - alignment = Alignment.End, - ) - } - - Row( - horizontalArrangement = Arrangement.SpaceBetween, - modifier = Modifier.fillMaxWidth(), - ) { - InfoCell( - label = "Receives", - value = model.onchainAmountSat?.let { "${it.formatToModernDisplay()} sats" } ?: "-", - ) - InfoCell( - label = "Created", - value = model.createdAt.formatToString().orEmpty(), - alignment = Alignment.End, - ) - } - } - } -} - -@Composable -fun SwapDetailScreen( - swapItem: Routes.SwapDetail, - onBackClick: () -> Unit = {}, - viewModel: SwapsViewModel = hiltViewModel(), -) { - val app = appViewModel ?: return - val swaps by viewModel.swaps.collectAsStateWithLifecycle() - val swap = swaps.find { it.id == swapItem.id } - val canClaim = swap?.isClaimable == true - - SwapDetailContent( - swap = swap, - onBack = onBackClick, - canClaim = canClaim, - onClaim = { - val id = swap?.id ?: return@SwapDetailContent - viewModel.claimReverseSwap(id) { result -> - result - .onSuccess { txid -> - app.toast( - type = Toast.ToastType.SUCCESS, - title = "Claim broadcast", - description = txid, - ) - } - .onFailure { e -> - app.toast( - type = Toast.ToastType.ERROR, - title = "Claim failed", - description = e.message ?: "Unknown error", - ) - } - } - }, - ) -} - -@Composable -private fun SwapDetailContent( - swap: BoltzSwap?, - modifier: Modifier = Modifier, - onBack: () -> Unit = {}, - canClaim: Boolean = false, - onClaim: () -> Unit = {}, -) { - Scaffold( - topBar = { AppTopBar(titleText = "Swap Details", onBackClick = onBack) }, - modifier = modifier, - ) { padding -> - if (swap == null) { - Box( - modifier = Modifier - .fillMaxSize() - .padding(padding), - contentAlignment = Alignment.Center, - ) { - BodyS(text = "Loading…") - } - return@Scaffold - } - LazyColumn( - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.padding(padding), - ) { - item { - InfoCard(header = "Overview") { - DetailRow("ID", swap.id) - DetailRow("Type", swap.swapType.toString()) - DetailRow("Status", swap.status.toString()) - DetailRow("Network", swap.network.toString()) - } - } - item { - InfoCard(header = "Amounts") { - DetailRow("Amount", "${swap.amountSat.formatToModernDisplay()} sats") - DetailRow( - "Onchain amount", - swap.onchainAmountSat?.let { "${it.formatToModernDisplay()} sats" } ?: "-", - ) - } - } - item { - InfoCard(header = "Addresses") { - DetailRow("Lockup", swap.lockupAddress ?: "-") - DetailRow("Claim / onchain", swap.onchainAddress ?: "-") - } - } - swap.invoice?.let { invoice -> - item { - InfoCard(header = "Lightning") { - DetailRow("Invoice", invoice) - } - } - } - item { - InfoCard(header = "Transactions") { - DetailRow("Claim txid", swap.claimTxId ?: "-") - DetailRow("Refund txid", swap.refundTxId ?: "-") - } - } - item { - InfoCard(header = "Recovery") { - DetailRow("Swap index", swap.swapIndex.toString()) - DetailRow("Timeout block", swap.timeoutBlockHeight.toString()) - } - } - item { - InfoCard(header = "Timestamps") { - DetailRow("Created", swap.createdAt.formatToString().orEmpty()) - } - } - if (canClaim) { - item { - PrimaryButton(text = "Claim now", onClick = onClaim) - } - } - } - } -} diff --git a/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt index b52cb50c3c..441150f0cc 100644 --- a/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt @@ -246,15 +246,6 @@ class SettingsViewModel @Inject constructor( } } - val isSavingsSwapEnabled = settingsStore.data.map { it.isSavingsSwapEnabled } - .asStateFlow(initialValue = false) - - fun setIsSavingsSwapEnabled(value: Boolean) { - viewModelScope.launch { - settingsStore.update { it.copy(isSavingsSwapEnabled = value) } - } - } - val isPaykitEnabled = settingsStore.isPaykitEnabled.map { PaykitFeatureFlags.isUiEnabled(it) } .asStateFlow(initialValue = false) diff --git a/app/src/main/java/to/bitkit/viewmodels/SwapsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/SwapsViewModel.kt deleted file mode 100644 index 90350b2626..0000000000 --- a/app/src/main/java/to/bitkit/viewmodels/SwapsViewModel.kt +++ /dev/null @@ -1,96 +0,0 @@ -package to.bitkit.viewmodels - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.synonym.bitkitcore.BoltzSwap -import com.synonym.bitkitcore.BoltzSwapStatus -import com.synonym.bitkitcore.BoltzSwapType -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.collections.immutable.ImmutableList -import kotlinx.collections.immutable.persistentListOf -import kotlinx.collections.immutable.toImmutableList -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import to.bitkit.ext.runSuspendCatching -import to.bitkit.services.BoltzService -import to.bitkit.utils.Logger -import javax.inject.Inject - -/** - * Dev-tools view model backing the Swaps history screen. Reads persisted swaps from - * bitkit-core (submarine + reverse) so they can be inspected/tracked, and allows a manual - * reverse-swap claim for recovery when the automatic claim did not fire. - */ -@HiltViewModel -class SwapsViewModel @Inject constructor( - private val boltzService: BoltzService, -) : ViewModel() { - private val _swaps = MutableStateFlow>(persistentListOf()) - val swaps = _swaps.asStateFlow() - - private val _error = MutableStateFlow(null) - val error = _error.asStateFlow() - - init { - refresh() - } - - fun refresh() { - viewModelScope.launch { - runSuspendCatching { boltzService.listSwaps() } - .onSuccess { list -> - _swaps.update { list.sortedByDescending { swap -> swap.createdAt }.toImmutableList() } - _error.update { null } - } - .onFailure { e -> - Logger.error("Failed to list swaps", e, context = TAG) - _error.update { e.message } - } - } - } - - /** Manually broadcast the claim for a reverse swap (recovery when auto-claim didn't fire). */ - fun claimReverseSwap(id: String, onResult: (Result) -> Unit) { - viewModelScope.launch { - val result = runSuspendCatching { boltzService.claimReverseSwap(id) } - result - .onSuccess { refresh() } - .onFailure { Logger.error("Manual claim failed for '$id'", it, context = TAG) } - onResult(result) - } - } - - companion object { - private const val TAG = "SwapsViewModel" - } -} - -/** - * Whether a manual claim is worth attempting: a reverse swap with no claim broadcast yet that has - * not reached a terminal state. - * - * Deliberately permissive about [BoltzSwapStatus]. The persisted status only advances while the - * updates stream is delivering events, so gating on it hides the recovery tool in exactly the case - * it exists for: a stalled stream leaves the swap at [BoltzSwapStatus.SwapCreated] locally even - * after Boltz has locked up on-chain and the funds are claimable. The chain, not the cached status, - * is the source of truth here, so offer the claim and let [boltzClaimReverseSwap] decide; when - * there is nothing to claim it fails harmlessly and the error surfaces to the caller. - */ -val BoltzSwap.isClaimable: Boolean - get() = swapType == BoltzSwapType.REVERSE && - claimTxId == null && - when (status) { - BoltzSwapStatus.InvoiceExpired, - BoltzSwapStatus.InvoiceFailedToPay, - BoltzSwapStatus.InvoiceSettled, - BoltzSwapStatus.SwapExpired, - BoltzSwapStatus.TransactionClaimed, - BoltzSwapStatus.TransactionFailed, - BoltzSwapStatus.TransactionLockupFailed, - BoltzSwapStatus.TransactionRefunded, - -> false - - else -> true - } diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index 5744b8ff59..2115a62a4f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -5,13 +5,9 @@ import androidx.annotation.VisibleForTesting import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import com.synonym.bitkitcore.BoltzPairInfo -import com.synonym.bitkitcore.BoltzSwapEvent import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableSet -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.async @@ -19,37 +15,25 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.filterIsInstance -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.ChannelDetails -import org.lightningdevkit.ldknode.Event -import org.lightningdevkit.ldknode.PaymentId import to.bitkit.R import to.bitkit.env.Env import to.bitkit.ext.amountOnClose -import to.bitkit.ext.runSuspendCatching -import to.bitkit.ext.toUserMessage import to.bitkit.models.Toast import to.bitkit.models.TransferType import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo -import to.bitkit.services.BoltzService import to.bitkit.services.SparkError import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.Logger import javax.inject.Inject -import kotlin.math.roundToLong import kotlin.time.Clock -import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime @@ -62,7 +46,6 @@ class TransferViewModel @Inject constructor( @ApplicationContext private val context: Context, private val lightningRepo: LightningRepo, private val transferRepo: TransferRepo, - private val boltzService: BoltzService, private val sparkRepo: SparkRepo, private val clock: Clock, ) : ViewModel() { @@ -93,9 +76,6 @@ class TransferViewModel @Inject constructor( private var sparkFeeBalanceSats: ULong? = null private var sparkAddress: String? = null - private val isNodeRunning = lightningRepo.lightningState.map { it.nodeStatus?.isRunning ?: false } - .stateIn(viewModelScope, SharingStarted.Lazily, false) - // region Savings private var channelsToClose = emptyList() @@ -105,217 +85,6 @@ class TransferViewModel @Inject constructor( private val _isSparkWithdrawFailed = MutableStateFlow(false) val isSparkWithdrawFailed = _isSparkWithdrawFailed.asStateFlow() - /** - * How the LN -> onchain "transfer to savings" is executed. Closing a channel is the - * default because it always works; swapping funds out keeps channels open and is used - * whenever a priced quote is available. - */ - private val _savingsTransferMode = MutableStateFlow(SavingsTransferMode.CLOSE) - val savingsTransferMode = _savingsTransferMode.asStateFlow() - - private val _savingsSwapState = MutableStateFlow(SavingsSwapUiState()) - val savingsSwapState = _savingsSwapState.asStateFlow() - - /** Outcome of the swap started by [startSavingsSwap]; null while none has finished. */ - private val _savingsSwapResult = MutableStateFlow(null) - val savingsSwapResult = _savingsSwapResult.asStateFlow() - - private var savingsSwapJob: Job? = null - - /** The amount (sat) that will actually be swapped out; adjustable via the confirm slider. */ - private var pendingSwapAmountSat: ULong = 0uL - - /** Cached swap limits so the slider can re-price locally without hitting the network. */ - private var reverseLimits: BoltzPairInfo? = null - - private var savingsSwapQuoteJob: Job? = null - - /** - * Fetch swap limits, derive the adjustable amount range, and publish an initial fee quote - * (defaulting to the maximum transferable) so the user sees the cost before confirming. - * The confirm slider then re-prices locally via [onSwapAmountChange]. A quote is the only - * thing that unlocks the swap, so every failure simply leaves it null and the transfer - * falls back to closing a channel. - * Cancels any in-flight quote so a slower earlier request cannot overwrite a newer one. - * [channelSendableSat] is what the selected channels can send, so Spark's balance never sizes the swap. - */ - fun loadSavingsSwapQuote(requestedSat: ULong, channelSendableSat: ULong) { - if (!boltzService.isSwapSupported) return - savingsSwapQuoteJob?.cancel() - if (requestedSat == 0uL) { - pendingSwapAmountSat = 0uL - _savingsSwapState.update { it.copy(isLoading = false, quote = null, minSat = 0uL, maxSat = 0uL) } - return - } - savingsSwapQuoteJob = viewModelScope.launch { - val isSwapEnabled = boltzService.isSwapEnabled() - _savingsSwapState.update { it.copy(isSwapEnabled = isSwapEnabled) } - if (!isSwapEnabled) return@launch - _savingsSwapState.update { it.copy(isLoading = true) } - awaitNodeRunning() - - // Bounded so a hanging Boltz request cannot leave the confirm swipe stuck loading. - val limits = withTimeoutOrNull(SWAP_QUOTE_TIMEOUT) { - runSuspendCatching { boltzService.reverseLimits() } - .onFailure { Logger.error("Failed to load reverse swap limits", it, context = TAG) } - .getOrNull() - } - if (limits == null) { - reverseLimits = null - _savingsSwapState.update { it.copy(isLoading = false, quote = null) } - return@launch - } - reverseLimits = limits - - // Reserve headroom for Lightning routing fees. Paying an invoice for 100% of - // outbound capacity leaves nothing for fees and fails with RouteNotFound, so cap - // the swap at outbound minus ~1% (with a small floor). - val spendable = channelSendableSat.toLong() - val routingReserve = (spendable / 100).coerceAtLeast(MIN_LN_ROUTING_FEE_RESERVE_SATS) - val sendable = (spendable - routingReserve).coerceAtLeast(0).toULong() - val maxSat = minOf(requestedSat, limits.maximalSat, sendable) - val minSat = limits.minimalSat - - if (maxSat < minSat) { - // Below the swap minimum: revert to the pre-swap view where the swipe closes - // the channel instead. No error text or extra close action is shown. - pendingSwapAmountSat = 0uL - _savingsSwapState.update { - it.copy( - isLoading = false, - quote = null, - minSat = 0uL, - maxSat = 0uL, - ) - } - return@launch - } - - // Default to transferring as much as possible; the slider can lower it. - pendingSwapAmountSat = maxSat - _savingsSwapState.update { - it.copy( - isLoading = false, - minSat = minSat, - maxSat = maxSat, - quote = buildQuote(maxSat, limits), - ) - } - } - } - - /** Re-price the swap for a slider-selected amount, clamped to the allowed range. */ - fun onSwapAmountChange(sat: ULong) { - val limits = reverseLimits ?: return - val state = _savingsSwapState.value - if (state.maxSat < state.minSat) return - val amount = sat.coerceIn(state.minSat, state.maxSat) - pendingSwapAmountSat = amount - _savingsSwapState.update { it.copy(quote = buildQuote(amount, limits)) } - } - - private fun buildQuote(amount: ULong, limits: BoltzPairInfo): SavingsSwapQuote { - val swapFee = (amount.toDouble() * limits.feePercentage / 100.0).roundToLong().coerceAtLeast(0).toULong() - val networkFee = limits.minerFeesSat - val receive = (amount.toLong() - swapFee.toLong() - networkFee.toLong()).coerceAtLeast(0).toULong() - return SavingsSwapQuote( - amountSat = amount, - networkFeeSat = networkFee, - swapFeeSat = swapFee, - receiveSat = receive, - ) - } - - /** - * Run the swap in [viewModelScope] so it outlives the progress screen: navigating away - * mid-flight must not cancel a swap whose hold invoice is already paid. Idempotent once - * started: a swap already in flight, or one whose outcome is already in [savingsSwapResult], - * is never re-run, so re-entering the screen or a configuration change cannot create and pay - * a second swap. A fresh journey clears the outcome in [onTransferToSavingsConfirm]. - */ - fun startSavingsSwap() { - if (savingsSwapJob?.isActive == true || _savingsSwapResult.value != null) return - savingsSwapJob = viewModelScope.launch { - if (withdrawsSpark) withdrawSparkToSavings() - val result = executeSavingsSwap() - _savingsSwapResult.update { result } - } - } - - /** - * Execute the LN -> onchain swap: derive a fresh claim address, create the swap, - * pay the returned hold invoice over Lightning, then wait for the on-chain claim. - * The claim is auto-broadcast by the updates stream as soon as the lockup hits the - * mempool, so a timeout here is not a failure; the swap completes in the background. - */ - private suspend fun executeSavingsSwap(): SavingsSwapResult { - val amount = pendingSwapAmountSat.takeIf { it > 0uL } - ?: return SavingsSwapResult.Failure( - context.getString(R.string.lightning__savings_confirm__amount_too_low), - ) - - return runSuspendCatching { - val claimAddress = lightningRepo.newAddress().getOrThrow() - val swap = boltzService.createReverseSwap(amountSat = amount, claimAddress = claimAddress) - Logger.info("Created savings transfer swap ${swap.id}", context = TAG) - - coroutineScope { - // Whichever resolves first wins: an on-chain claim, a Boltz error, or a Lightning - // routing failure. The losing watcher is cancelled so this scope can return. - val outcome = CompletableDeferred() - - // UNDISPATCHED so the collector actually subscribes before we pay: the events - // flow has no replay, so a claim settling faster than the payment call returns - // would otherwise be missed and the swap would idle until the claim timeout. - val claim = launch(start = CoroutineStart.UNDISPATCHED) { - outcome.complete(awaitSwapClaim(swap.id)) - } - - // Pay the hold invoice (amount is encoded) from the channels it was quoted on, never Spark. - // It stays pending until Boltz locks funds on-chain and we claim them, the expected happy path. - val paymentHash = lightningRepo.payInvoiceWithNode(swap.invoice).getOrThrow() - - // payInvoice returns as soon as the HTLC is dispatched, and a hold invoice never - // settles until Boltz claims, so nothing else notices a payment that fails to route. - // Watch for it so an unroutable payment surfaces as an error instead of idling into - // the claim timeout and reporting a settling transfer that never completes. - val failure = launch { - outcome.complete(awaitPaymentFailure(paymentHash)) - } - - outcome.await().also { - claim.cancel() - failure.cancel() - } - } - }.getOrElse { e -> - Logger.error("Savings transfer swap failed", e, context = TAG) - SavingsSwapResult.Failure(e.message ?: context.getString(R.string.common__error_body)) - } - } - - private suspend fun awaitSwapClaim(swapId: String): SavingsSwapResult { - val event = withTimeoutOrNull(SWAP_CLAIM_TIMEOUT) { - boltzService.events.first { - (it is BoltzSwapEvent.Claimed && it.swapId == swapId) || - (it is BoltzSwapEvent.Error && it.swapId == swapId) - } - } - return when (event) { - is BoltzSwapEvent.Claimed -> SavingsSwapResult.Success(event.txid) - is BoltzSwapEvent.Error -> SavingsSwapResult.Failure(event.message) - else -> SavingsSwapResult.Pending - } - } - - /** Suspends until the paid hold invoice fails to route on Lightning, then maps it to a reason. */ - private suspend fun awaitPaymentFailure(paymentHash: PaymentId): SavingsSwapResult { - val event = lightningRepo.nodeEvents - .filterIsInstance() - .first { it.paymentHash == paymentHash } - return SavingsSwapResult.Failure(event.reason.toUserMessage(context)) - } - /** Opens Transfer to Savings with nothing left from an earlier visit that ended before the swipe. */ fun beginSavingsTransfer() { // A wallet wipe keeps this view model, so an address kept from before may belong to the wiped wallet. @@ -343,7 +112,7 @@ class TransferViewModel @Inject constructor( val job = viewModelScope.launch { val address = sparkWithdrawAddress() val result = address?.let { - withTimeoutOrNull(SWAP_QUOTE_TIMEOUT) { sparkRepo.estimateWithdrawAllFeeSats(it) } + withTimeoutOrNull(SPARK_FEE_TIMEOUT) { sparkRepo.estimateWithdrawAllFeeSats(it) } } if (address != null && result == null) { Logger.warn("Timed out estimating Spark withdrawal fee", context = TAG) @@ -396,20 +165,15 @@ class TransferViewModel @Inject constructor( sparkRepo.state.value.balanceSats == balanceSats /** - * Commit the transfer and pick how it runs. A swap needs a priced quote, so without one - * (swaps unsupported on this network, Boltz unreachable, or an amount below the swap - * minimum) the transfer closes a channel exactly as it did before swaps existed. Spark's withdrawal pays at most - * [confirmedSparkFeeSats], the fee shown when the user confirmed, even if the screen prices it again after. + * Commit the transfer: closes [channels] and withdraws Spark's balance when [withdrawSpark]. Spark's withdrawal + * pays at most [confirmedSparkFeeSats], the fee shown when the user confirmed, even if the screen prices it again + * after. */ fun onTransferToSavingsConfirm( channels: List, withdrawSpark: Boolean, - mode: SavingsTransferMode = resolveSavingsTransferMode(channels), confirmedSparkFeeSats: ULong? = _sparkWithdrawFeeSats.value, ) { - _savingsTransferMode.update { mode } - // Drop any outcome from an earlier attempt so the progress screen cannot act on it. - _savingsSwapResult.update { null } _isSparkWithdrawFailed.update { false } // A withdrawal still going out is kept, so a transfer confirmed again joins it rather than sending it twice. if (sparkWithdrawJob?.isActive != true) sparkWithdrawJob = null @@ -420,13 +184,6 @@ class TransferViewModel @Inject constructor( this.confirmedSparkFeeSats = confirmedSparkFeeSats } - private fun resolveSavingsTransferMode(channels: List): SavingsTransferMode = - if (channels.isNotEmpty() && _savingsSwapState.value.quote != null) { - SavingsTransferMode.SWAP - } else { - SavingsTransferMode.CLOSE - } - /** Whether Transfer to Savings closes channels, rather than only withdrawing Spark's balance. */ fun hasChannelsToClose(): Boolean = channelsToClose.isNotEmpty() @@ -600,23 +357,11 @@ class TransferViewModel @Inject constructor( // endregion - private suspend fun awaitNodeRunning() { - withTimeoutOrNull(1.minutes) { - isNodeRunning.first { it } - } - } - companion object { private const val TAG = "TransferViewModel" - /** How long the confirm/progress flow waits for the on-chain claim before backgrounding it. */ - private val SWAP_CLAIM_TIMEOUT = 30.seconds - - /** Upper bound for fetching swap limits before the confirm screen gives up on a quote. */ - private val SWAP_QUOTE_TIMEOUT = 15.seconds - - /** Minimum sats held back from a swap to cover Lightning routing fees. */ - private const val MIN_LN_ROUTING_FEE_RESERVE_SATS = 10L + /** Upper bound for estimating Spark's withdrawal fee before the confirm screen gives up on it. */ + private val SPARK_FEE_TIMEOUT = 15.seconds } } @@ -638,36 +383,4 @@ data class SavingsSelection( fun withdrawsSpark(sparkSats: ULong, isSparkTooSmall: Boolean = false): Boolean = includesSpark && sparkSats > 0uL && !isSparkTooSmall } - -/** Whether a transfer to savings swaps funds out or closes a channel (default). */ -enum class SavingsTransferMode { SWAP, CLOSE } - -@Immutable -data class SavingsSwapQuote( - val amountSat: ULong, - val networkFeeSat: ULong, - val swapFeeSat: ULong, - val receiveSat: ULong, -) - -@Immutable -data class SavingsSwapUiState( - /** Whether swaps are switched on for this network and in dev settings; see [BoltzService.isSwapEnabled]. */ - val isSwapEnabled: Boolean = false, - val isLoading: Boolean = false, - val quote: SavingsSwapQuote? = null, - /** Inclusive adjustable range for the confirm slider (sat). Equal/zero when unavailable. */ - val minSat: ULong = 0uL, - val maxSat: ULong = 0uL, -) - -sealed interface SavingsSwapResult { - /** Funds landed on-chain during the flow. */ - data class Success(val txid: String) : SavingsSwapResult - - /** Swap created and invoice paid; the claim completes in the background. */ - data object Pending : SavingsSwapResult - - data class Failure(val reason: String) : SavingsSwapResult -} // endregion diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index f8910ba2b9..3a59cf8367 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -7,11 +7,9 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import com.synonym.bitkitcore.BoltzSwapEvent import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope @@ -55,7 +53,6 @@ import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo import to.bitkit.repositories.WipeInProgressError -import to.bitkit.services.BoltzService import to.bitkit.services.MigrationService import to.bitkit.ui.onboarding.LOADING_MS import to.bitkit.ui.settings.lightning.MoveToSparkManager @@ -81,7 +78,6 @@ class WalletViewModel @Inject constructor( private val pubkyRepo: PubkyRepo, private val migrationService: MigrationService, private val connectivityRepo: ConnectivityRepo, - private val boltzService: BoltzService, private val connectionRecovery: WalletConnectionRecovery, private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, sparkRepo: SparkRepo, @@ -90,18 +86,6 @@ class WalletViewModel @Inject constructor( companion object { private const val TAG = "WalletViewModel" private val TIMEOUT_RESTORE_WAIT = 30.seconds - - /** Base backoff between swap updates stream attempts; scales linearly per attempt. */ - private val SWAP_UPDATES_RETRY_DELAY = 5.seconds - - /** Upper bound for the backoff between swap updates stream attempts. */ - private val SWAP_UPDATES_RETRY_CAP = 60.seconds - - /** - * Ceiling on swap updates stream start attempts per run (~14 min of backoff). Giving up is - * safe: the stream is retried on the next node start and when entering a swap flow. - */ - private const val SWAP_UPDATES_MAX_ATTEMPTS = 20 } val lightningState = lightningRepo.lightningState @@ -833,80 +817,12 @@ class WalletViewModel @Inject constructor( if (_restoreState.value.isIdle()) { walletRepo.refreshBip21() } - ensureSwapUpdatesRunning() if (pubkySwapsRouteRepo.isEnabled) pubkySwapsRouteRepo.resumeUnfinishedSwaps() // checkForOrphanedChannelMonitorRecovery() } } private var openedReceivePresentationId: String? = null - private var swapEventsCollected = false - private var swapUpdatesJob: Job? = null - - @Volatile - private var swapUpdatesRunning = false - - /** - * Ensure the swap updates stream is running so pending LN -> onchain swaps are tracked and - * auto-claimed. A live stream is left untouched: restarting it would abort bitkit-core's - * background tasks and could race an in-flight claim. New swaps are reconciled at creation - * inside bitkit-core, and the stream reconciles every pending swap periodically, so a - * running stream is always enough. Runs only where swaps are supported and enabled in dev - * settings, see [BoltzService.isSwapEnabled]. - */ - fun ensureSwapUpdatesRunning() { - if (!boltzService.isSwapSupported) return - if (swapUpdatesRunning || swapUpdatesJob?.isActive == true) return - swapUpdatesJob = viewModelScope.launch { - if (!boltzService.isSwapEnabled()) return@launch - collectSwapEventsOnce() - startSwapUpdates() - } - } - - /** - * Open the swap updates stream so any pending LN -> onchain swaps resume and auto-claim. - * Uses the wallet's current fee rate for the claim tx. Retries up to a ceiling: without the - * stream a paid swap has nothing to broadcast its claim, so give up only after - * [SWAP_UPDATES_MAX_ATTEMPTS] and leave the next trigger to retry. Once started, bitkit-core - * keeps the WebSocket alive with its own reconnect loop. - */ - private suspend fun startSwapUpdates() { - var attempt = 0 - while (attempt < SWAP_UPDATES_MAX_ATTEMPTS) { - val started = runSuspendCatching { - val speed = settingsStore.data.first().defaultTransactionSpeed - val feeRate = lightningRepo.getFeeRateForSpeed(speed).getOrNull()?.toDouble() - boltzService.startUpdates(feeRateSatPerVb = feeRate, acceptZeroConf = true) - }.onFailure { - Logger.warn("Failed to start swap updates, attempt '${attempt + 1}'", it, context = TAG) - }.isSuccess - - if (started) { - swapUpdatesRunning = true - return - } - attempt++ - delay((SWAP_UPDATES_RETRY_DELAY * attempt).coerceAtMost(SWAP_UPDATES_RETRY_CAP)) - } - Logger.warn("Gave up starting swap updates after '$attempt' attempts", context = TAG) - } - - /** Refresh balances when a swap lands on-chain so savings reflect it without a manual sync. */ - private fun collectSwapEventsOnce() { - if (swapEventsCollected) return - swapEventsCollected = true - // UNDISPATCHED so we subscribe before the updates stream starts: the events flow has - // no replay, so a swap claimed early would otherwise leave balances stale. - viewModelScope.launch(start = CoroutineStart.UNDISPATCHED) { - boltzService.events.collect { event -> - if (event is BoltzSwapEvent.Claimed) { - Logger.info("Savings swap claimed: ${event.swapId}", context = TAG) - walletRepo.syncBalances() - } - } - } - } private suspend fun connectMigrationPeers() { val peerUris = migrationService.tryFetchMigrationPeersFromBackup() @@ -923,19 +839,9 @@ class WalletViewModel @Inject constructor( fun stop() { if (!walletExists) return - swapUpdatesJob?.cancel() - swapUpdatesRunning = false - viewModelScope.launch(bgDispatcher) { - stopSwapUpdates() - } lightningRepo.stopDebounced() } - private suspend fun stopSwapUpdates() { - runSuspendCatching { boltzService.stopUpdates() } - .onFailure { Logger.error("Failed to stop swap updates", it, context = TAG) } - } - fun refreshState() = viewModelScope.launch { walletRepo.syncNodeAndWallet() .onFailure { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 9974725578..f11f508725 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1446,15 +1446,8 @@ لم يتم العثور على القناة تم تحويل الأموال في رصيد إنفاقك إلى مدخراتك. تم إغلاق الاتصال - إلى المدخرات المبلغ منخفض جدًا للتحويل إلى المدخرات. - إغلاق القناة بدلاً من ذلك - رسوم الشبكة - ستستلم - رسوم الخدمة رسوم Spark - بدأ التحويل وهو <accent>قيد التسوية على السلسلة</accent>. سيتم تحديث رصيد مدخراتك تلقائيًا عند اكتماله. - التحويل\n<accent>في الطريق</accent> تعذّر نقل رصيدك المدعوم بـ Spark إلى المدخرات ويبقى في رصيد الإنفاق. أموال قنواتك في طريقها إلى المدخرات، لكن رصيد Spark الخاص بك تعذّر نقله ويبقى في رصيد الإنفاق. <accent>جارٍ الاتصال</accent>\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 2b43e6d8b9..5f724c00a7 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1473,15 +1473,8 @@ Falló la verificación de la dirección. Revise la dirección en su dispositivo y vuelva a intentarlo. Este dispositivo contiene una billetera distinta a la que vinculó. Conecte la billetera vinculada o añada esta como una nueva billetera de hardware. Canal no encontrado - A ahorros El monto es demasiado bajo para transferirlo a ahorros. - Cerrar el canal en su lugar - Comisión de red - Recibirá - Comisión de servicio Comisión de Spark - Su transferencia se inició y se está <accent>liquidando onchain</accent>. Su saldo de ahorros se actualizará automáticamente cuando termine. - Transferencia\n<accent>en camino</accent> Tu saldo con tecnología de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. Los fondos de tus canales se están moviendo a ahorros, pero tu saldo de Spark no se pudo mover y permanece en tu saldo para gastos. <accent>Conectando</accent>\na la red diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 495851f6e2..3d722bf095 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1467,15 +1467,8 @@ Aquest dispositiu conté una cartera diferent de la que has vinculat. Connecta la cartera vinculada o afegeix aquesta com a nova cartera de maquinari. Canal no trobat Els fons del teu saldo de despesa s\'han transferit als teus estalvis. - A estalvis L\'import és massa baix per transferir-lo a estalvis. - Tancar el canal - Tarifa de xarxa - Rebràs - Tarifa de servei Tarifa de Spark - La teva transferència s\'ha iniciat i <accent>s\'està liquidant onchain</accent>. El teu saldo d\'estalvis s\'actualitzarà automàticament quan es completi. - Transferència\n<accent>en camí</accent> El teu saldo amb tecnologia de Spark no s\'ha pogut moure als estalvis i es queda al teu saldo de despesa. Els fons dels teus canals es mouen als estalvis, però el teu saldo de Spark no s\'ha pogut moure i es queda al teu saldo de despesa. <accent>Connectant</accent>\na la xarxa diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 6994891bd2..a0a88404d2 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1472,15 +1472,8 @@ Ověření adresy se nezdařilo. Zkontrolujte adresu na zařízení a zkuste to znovu. Toto zařízení obsahuje jinou peněženku než tu, kterou jste spárovali. Připojte spárovanou peněženku, nebo tuto přidejte jako novou hardwarovou peněženku. Kanál nenalezen - Do úspor Částka je příliš nízká pro převod do úspor. - Místo toho uzavřít kanál - Síťový poplatek - Obdržíte - Poplatek za službu Poplatek Spark - Váš převod byl zahájen a <accent>vypořádává se on-chain</accent>. Zůstatek vašich úspor se po dokončení automaticky aktualizuje. - Převod\n<accent>je na cestě</accent> Váš zůstatek ve Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. Prostředky z vašich kanálů se přesouvají do úspor, ale váš zůstatek ve Spark se nepodařilo přesunout a zůstává ve zůstatku pro výdaje. <accent>Připojování</accent>\nk síti diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 8a05a8219e..026e53ac04 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1467,15 +1467,8 @@ Adressüberprüfung fehlgeschlagen. Überprüfe die Adresse auf deinem Gerät und versuche es erneut. Auf diesem Gerät befindet sich ein anderes Wallet als das gekoppelte. Verbinde das gekoppelte Wallet oder füge dieses als neues Hardware-Wallet hinzu. Kanal nicht gefunden - Zum Sparkonto Der Betrag ist zu niedrig für eine Übertragung auf das Sparkonto. - Stattdessen Kanal schließen - Netzwerkgebühr - Du erhältst - Servicegebühr Spark-Gebühr - Deine Übertragung wurde gestartet und wird <accent>onchain abgewickelt</accent>. Dein Sparguthaben wird automatisch aktualisiert, sobald sie abgeschlossen ist. - Übertragung\n<accent>unterwegs</accent> Dein Spark-Guthaben konnte nicht auf dein Sparkonto verschoben werden und bleibt in deinem Ausgabenguthaben. Deine Kanalgelder werden aufs Sparkonto verschoben, aber dein Spark-Guthaben konnte nicht verschoben werden und bleibt in deinem Ausgabenguthaben. <accent>Verbinde</accent>\nmit Netzwerk diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 23ce36067c..aac4b64a6e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1448,15 +1448,8 @@ Το κανάλι δεν βρέθηκε Τα κεφάλαια στο υπόλοιπο δαπανών σας έχουν μεταφερθεί στις αποταμιεύσεις σας. Η Σύνδεση Έκλεισε - Προς αποταμιεύσεις Το ποσό είναι πολύ χαμηλό για μεταφορά στις αποταμιεύσεις. - Κλείσιμο καναλιού αντί αυτού - Τέλος δικτύου - Θα λάβεις - Τέλος υπηρεσίας Τέλος Spark - Η μεταφορά σου ξεκίνησε και <accent>εκκαθαρίζεται onchain</accent>. Το υπόλοιπο αποταμιεύσεων θα ενημερωθεί αυτόματα μόλις ολοκληρωθεί. - Η μεταφορά\n<accent>είναι καθ\' οδόν</accent> Το υπόλοιπό σας στο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. Τα κεφάλαια του καναλιού σου μεταφέρονται στις αποταμιεύσεις, αλλά το υπόλοιπό σου στο Spark δεν μπόρεσε να μεταφερθεί και παραμένει στο υπόλοιπο δαπανών σου. <accent>Σύνδεση</accent>\nστο δίκτυο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 761fd95195..cd5196b190 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1465,15 +1465,8 @@ Este dispositivo contiene un monedero distinto del que vinculaste. Conecta el monedero vinculado o añade este como un nuevo monedero de hardware. Canal no encontrado Los fondos de tu saldo de gasto se han transferido a tus ahorros. - A ahorros La cantidad es demasiado baja para transferirla a ahorros. - Cerrar el canal en su lugar - Comisión de red - Recibirás - Comisión de servicio Comisión de Spark - Tu transferencia se ha iniciado y se está <accent>liquidando en cadena</accent>. Tu saldo de ahorro se actualizará automáticamente cuando se complete. - Transferencia\n<accent>en camino</accent> Tu saldo con tecnología de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Los fondos de tu canal se están moviendo a ahorro, pero tu saldo de Spark no se pudo mover y permanece en tu saldo de gasto. <accent>Conectando</accent>\na la red diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 735be8c4d2..706270b45e 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1464,15 +1464,8 @@ Canal no encontrado Los fondos de su saldo de gasto han sido transferidos a sus ahorros. Conexión Cerrada - A ahorros La cantidad es demasiado baja para transferirla a ahorros. - Cerrar el canal en su lugar - Comisión de red - Recibirá - Comisión de servicio Comisión de Spark - Su transferencia se ha iniciado y se está <accent>liquidando onchain</accent>. Su saldo de ahorro se actualizará automáticamente cuando se complete. - Transferencia\n<accent>en camino</accent> Tu saldo con tecnología de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Los fondos de tu canal se están moviendo a ahorro, pero tu saldo de Spark no se pudo mover y permanece en tu saldo de gasto. <accent>Conectando</accent>\na la red diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index bc702256c9..72d3ead8a7 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1467,15 +1467,8 @@ Échec de la vérification de l\'adresse. Vérifiez l\'adresse sur votre appareil et réessayez. Cet appareil contient un autre portefeuille que celui que vous avez associé. Connectez le portefeuille associé ou ajoutez celui-ci comme nouveau portefeuille matériel. Canal introuvable - Vers l\'épargne Le montant est trop faible pour être transféré vers l\'épargne. - Fermer plutôt le canal - Frais de réseau - Vous recevrez - Frais de service Frais Spark - Votre transfert a été initié et est <accent>en cours de règlement on-chain</accent>. Votre solde d\'épargne se mettra à jour automatiquement une fois terminé. - Transfert\n<accent>en cours</accent> Votre solde basé sur Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. Les fonds de votre canal passent à l\'épargne, mais votre solde Spark n\'a pas pu être déplacé et reste dans votre solde dépenses. <accent>Connexion</accent>\nau réseau diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 43a0f693df..e5c23b7299 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1470,15 +1470,8 @@ Questo dispositivo contiene un wallet diverso da quello associato. Connetti il wallet associato o aggiungi questo come nuovo hardware wallet. Canale non trovato I fondi sul tuo saldo di spesa sono stati trasferiti ai tuoi risparmi. - Ai risparmi L\'importo è troppo basso per essere trasferito ai risparmi. - Chiudi invece il canale - Commissione di rete - Riceverai - Commissione di servizio Commissione Spark - Il tuo trasferimento è stato avviato ed è <accent>in regolamento on-chain</accent>. Il saldo dei tuoi risparmi si aggiornerà automaticamente al termine. - Trasferimento\n<accent>in corso</accent> Il tuo saldo basato su Spark non ha potuto spostarsi nei risparmi e resta nel tuo saldo di spesa. I fondi del tuo canale vengono spostati nei risparmi, ma il tuo saldo Spark non è stato spostato e resta nel tuo saldo di spesa. <accent>Connessione</accent>\nalla rete diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 5472b65607..f61f3e3e7b 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1465,15 +1465,8 @@ Kanaal niet gevonden Het geld op uw bestedingssaldo is overgemaakt naar uw spaargeld. Verbinding Gesloten - Naar spaargeld Bedrag is te laag om naar spaargeld over te boeken. - In plaats daarvan kanaal sluiten - Netwerkvergoeding - U ontvangt - Servicevergoeding Spark-vergoeding - Uw overboeking is gestart en wordt <accent>on-chain afgehandeld</accent>. Uw spaargeld wordt automatisch bijgewerkt zodra deze is voltooid. - Overboeking\n<accent>onderweg</accent> Je saldo via Spark kon niet naar spaargeld en blijft in je bestedingssaldo. Je kanaalfondsen worden naar spaargeld overgeboekt, maar je Spark-saldo kon niet worden verplaatst en blijft in je bestedingssaldo. <accent>Verbinden</accent>\nmet netwerk diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 463128e459..ab2208e96f 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1471,15 +1471,8 @@ Weryfikacja adresu nie powiodła się. Sprawdź adres na urządzeniu i spróbuj ponownie. To urządzenie zawiera inny portfel niż sparowany. Połącz sparowany portfel lub dodaj ten jako nowy portfel sprzętowy. Nie znaleziono kanału - Na oszczędności Kwota jest zbyt niska, aby przesłać ją na oszczędności. - Zamiast tego zamknij kanał - Opłata sieciowa - Otrzymasz - Opłata serwisowa Opłata Spark - Twój transfer został zainicjowany i jest <accent>rozliczany on-chain</accent>. Saldo oszczędności zaktualizuje się automatycznie po jego zakończeniu. - Transfer\n<accent>w drodze</accent> Twoje saldo oparte na Spark nie mogło zostać przeniesione do oszczędności i pozostaje w saldzie wydatków. Środki z Twoich kanałów są przenoszone do Oszczędności, ale Twojego salda Spark nie udało się przenieść i pozostaje ono w saldzie wydatków. <accent>Łączenie</accent>\nz siecią diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index bc92f3b64c..871c729eb7 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1472,15 +1472,8 @@ Falha na verificação do endereço. Confira o endereço no seu dispositivo e tente novamente. Este dispositivo contém uma carteira diferente da que você pareou. Conecte a carteira pareada ou adicione esta como uma nova carteira de hardware. Canal não encontrado - Para poupança O valor é baixo demais para transferir para a poupança. - Fechar o canal em vez disso - Taxa de rede - Você receberá - Taxa de serviço Taxa do Spark - Sua transferência foi iniciada e está sendo <accent>liquidada onchain</accent>. Seu saldo de poupança será atualizado automaticamente quando ela for concluída. - Transferência\n<accent>a caminho</accent> Seu saldo com tecnologia Spark não pôde ser movido para a poupança e continua no saldo de gastos. Os fundos dos seus canais estão sendo movidos para a poupança, mas seu saldo Spark não pôde ser movido e fica no seu saldo de gastos. <accent>Conectando</accent>\nà rede diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 9c855936f5..009af23b30 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1441,15 +1441,8 @@ Canal não encontrado Os fundos do seu saldo de gastos foram transferidos para a sua poupança. Ligação fechada - Para a poupança O montante é demasiado baixo para transferir para a poupança. - Fechar o canal - Taxa de rede - Vai receber - Taxa de serviço Taxa do Spark - A sua transferência foi iniciada e está a ser <accent>liquidada on-chain</accent>. O saldo de poupança será atualizado automaticamente quando terminar. - Transferência\n<accent>a caminho</accent> O seu saldo com tecnologia Spark não pôde ser movido para a poupança e continua no saldo de gastos. Os fundos dos seus canais estão a ser movidos para a poupança, mas o seu saldo Spark não pôde ser movido e fica no seu saldo de gastos. <accent>A ligar</accent>\nà rede diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6eeb0af1b1..31116ee437 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1487,15 +1487,8 @@ Проверка адреса не удалась. Сверьте адрес на устройстве и попробуйте снова. На этом устройстве другой кошелёк, а не тот, который вы сопрягли. Подключите сопряжённый кошелёк или добавьте этот как новый аппаратный кошелёк. Канал не найден - В сбережения Сумма слишком мала для перевода в сбережения. - Вместо этого закрыть канал - Сетевая комиссия - Вы получите - Сервисная комиссия Комиссия Spark - Ваш перевод инициирован и <accent>проводится в блокчейне</accent>. Баланс сбережений обновится автоматически после завершения. - Перевод\n<accent>в пути</accent> Баланс на базе Spark не удалось перевести в сбережения, он остаётся в балансе расходов. Средства ваших каналов переводятся в сбережения, но баланс Spark перевести не удалось, он остаётся на балансе расходов. <accent>Подключение</accent>\nк сети diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 981c0e3e1c..ab034c5891 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -376,13 +376,8 @@ You can transfer part of your spending balance to savings, because you have multiple active Lightning Connections. Select funds\n<accent>to transfer</accent> Total selected - To savings Amount is too low to transfer to savings. - Close channel instead Transfer to savings - Network fee - You\'ll receive - Service fee Spark fee Transfer all Transfer\n<accent>interrupted</accent> @@ -393,8 +388,6 @@ Transfer\n<accent>to savings</accent> Please wait, your funds transfer is in progress. This should take <accent>±10 seconds.</accent> Funds\n<accent>in transfer</accent> - Your transfer has been initiated and is <accent>settling on-chain</accent>. Your savings balance will update automatically once it completes. - Transfer\n<accent>on the way</accent> Your balance powered by Spark couldn\'t move to savings and stays in your spending balance. Transfer\n<accent>failed</accent> Your channel funds are moving to savings, but your Spark balance could not move and stays in your spending balance. diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 5626853975..7063ae4b09 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -6,7 +6,6 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf @@ -56,7 +55,6 @@ import to.bitkit.repositories.RestoredPubkySwaps import to.bitkit.repositories.SyncSource import to.bitkit.repositories.WalletRepo import to.bitkit.repositories.WalletState -import to.bitkit.services.BoltzService import to.bitkit.services.MigrationService import to.bitkit.services.PendingChannelMigration import to.bitkit.test.BaseUnitTest @@ -91,7 +89,6 @@ class WalletViewModelTest : BaseUnitTest() { private val pubkyRepo = mock() private val migrationService = mock() private val connectivityRepo = mock() - private val boltzService = mock() private val pubkySwapsRouteRepo = mock() private val sparkRepo = idleSparkRepo() private val moveToSparkManager = mock { @@ -119,9 +116,7 @@ class WalletViewModelTest : BaseUnitTest() { whenever { migrationService.getRNRemoteBackupTimestamp() }.thenReturn(null) whenever { backupRepo.hasPendingWalletRestore() }.thenReturn(false) whenever(connectivityRepo.isOnline).thenReturn(isOnline) - whenever(boltzService.events).thenReturn(MutableSharedFlow()) whenever(settingsStore.data).thenReturn(flowOf(SettingsData())) - whenever { lightningRepo.getFeeRateForSpeed(any(), anyOrNull()) }.thenReturn(Result.success(1uL)) connectionRecovery = connectionRecoveryFixture(settingsStore, recoveryKeychain) { currentBinding } sut = WalletViewModel( @@ -135,7 +130,6 @@ class WalletViewModelTest : BaseUnitTest() { pubkyRepo = pubkyRepo, migrationService = migrationService, connectivityRepo = connectivityRepo, - boltzService = boltzService, connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, @@ -143,38 +137,6 @@ class WalletViewModelTest : BaseUnitTest() { ) } - @Test - fun `ensureSwapUpdatesRunning should start updates when swaps are enabled`() = test { - whenever(boltzService.isSwapSupported).thenReturn(true) - whenever(boltzService.isSwapEnabled()).thenReturn(true) - - sut.ensureSwapUpdatesRunning() - advanceUntilIdle() - - verify(boltzService).startUpdates(anyOrNull(), any(), anyOrNull()) - } - - @Test - fun `ensureSwapUpdatesRunning should do nothing when swaps are unsupported`() = test { - whenever(boltzService.isSwapSupported).thenReturn(false) - - sut.ensureSwapUpdatesRunning() - advanceUntilIdle() - - verify(boltzService, never()).startUpdates(anyOrNull(), any(), anyOrNull()) - } - - @Test - fun `ensureSwapUpdatesRunning should do nothing when swaps are disabled in dev settings`() = test { - whenever(boltzService.isSwapSupported).thenReturn(true) - whenever(boltzService.isSwapEnabled()).thenReturn(false) - - sut.ensureSwapUpdatesRunning() - advanceUntilIdle() - - verify(boltzService, never()).startUpdates(anyOrNull(), any(), anyOrNull()) - } - @Test fun `setInitNodeLifecycleState should call lightningRepo`() = test { sut.setInitNodeLifecycleState() @@ -1282,7 +1244,6 @@ class WalletViewModelTest : BaseUnitTest() { pubkyRepo = pubkyRepo, migrationService = migrationService, connectivityRepo = connectivityRepo, - boltzService = boltzService, connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, @@ -1352,7 +1313,6 @@ class WalletViewModelTest : BaseUnitTest() { pubkyRepo = pubkyRepo, migrationService = migrationService, connectivityRepo = connectivityRepo, - boltzService = boltzService, connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, @@ -1411,7 +1371,6 @@ class WalletViewModelTest : BaseUnitTest() { pubkyRepo = pubkyRepo, migrationService = migrationService, connectivityRepo = connectivityRepo, - boltzService = boltzService, connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, @@ -1454,7 +1413,6 @@ class WalletViewModelTest : BaseUnitTest() { pubkyRepo = pubkyRepo, migrationService = migrationService, connectivityRepo = connectivityRepo, - boltzService = boltzService, connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, @@ -1548,7 +1506,6 @@ class WalletViewModelTest : BaseUnitTest() { pubkyRepo = pubkyRepo, migrationService = migrationService, connectivityRepo = connectivityRepo, - boltzService = boltzService, connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt index 824c9acc2c..e7574517cb 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreenTest.kt @@ -59,18 +59,12 @@ class SavingsConfirmScreenTest { composeRule.setContent { AppThemeSurface { SavingsConfirmContent( - fallbackAmount = 0u, + channelsAmount = 0u, sparkAmount = 12_000u, sparkFeeSats = null, isSparkFeePricing = isSparkFeePricing, isSparkUnpriced = isSparkUnpriced, isSparkTooSmall = isSparkTooSmall, - isSwapEnabled = false, - quote = null, - isQuoteLoading = false, - minSat = 0u, - maxSat = 0u, - onAmountChange = {}, hasMultiple = false, hasSelected = false, onSparkFeeRetry = onSparkFeeRetry, diff --git a/app/src/test/java/to/bitkit/viewmodels/SwapsViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/SwapsViewModelTest.kt deleted file mode 100644 index 51f5dc2e91..0000000000 --- a/app/src/test/java/to/bitkit/viewmodels/SwapsViewModelTest.kt +++ /dev/null @@ -1,120 +0,0 @@ -package to.bitkit.viewmodels - -import com.synonym.bitkitcore.BoltzNetwork -import com.synonym.bitkitcore.BoltzSwap -import com.synonym.bitkitcore.BoltzSwapStatus -import com.synonym.bitkitcore.BoltzSwapType -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.advanceUntilIdle -import org.junit.Test -import org.mockito.kotlin.any -import org.mockito.kotlin.anyOrNull -import org.mockito.kotlin.mock -import org.mockito.kotlin.whenever -import to.bitkit.services.BoltzService -import to.bitkit.test.BaseUnitTest -import to.bitkit.utils.AppError -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -@OptIn(ExperimentalCoroutinesApi::class) -class SwapsViewModelTest : BaseUnitTest() { - private val boltzService = mock() - - @Test - fun `refresh sorts swaps by creation time descending`() = test { - whenever(boltzService.listSwaps()).thenReturn( - listOf( - swap(id = "older", createdAt = 100uL), - swap(id = "newer", createdAt = 200uL), - ), - ) - - val sut = SwapsViewModel(boltzService) - advanceUntilIdle() - - assertEquals(listOf("newer", "older"), sut.swaps.value.map { it.id }) - } - - @Test - fun `refresh surfaces the error when listing swaps fails`() = test { - whenever(boltzService.listSwaps()).thenAnswer { throw AppError(LIST_ERROR) } - - val sut = SwapsViewModel(boltzService) - advanceUntilIdle() - - assertEquals(LIST_ERROR, sut.error.value) - assertTrue(sut.swaps.value.isEmpty()) - } - - @Test - fun `claimReverseSwap reports the broadcast txid`() = test { - whenever(boltzService.listSwaps()).thenReturn(emptyList()) - whenever(boltzService.claimReverseSwap(any(), anyOrNull())).thenReturn(TXID) - val sut = SwapsViewModel(boltzService) - - var result: Result? = null - sut.claimReverseSwap(SWAP_ID) { result = it } - advanceUntilIdle() - - assertEquals(TXID, result?.getOrNull()) - } - - @Test - fun `isClaimable while a reverse swap is unclaimed and not in a terminal state`() { - assertTrue(swap(status = BoltzSwapStatus.TransactionMempool).isClaimable) - assertTrue(swap(status = BoltzSwapStatus.TransactionConfirmed).isClaimable) - assertTrue(swap(status = BoltzSwapStatus.TransactionClaimPending).isClaimable) - assertTrue(swap(status = BoltzSwapStatus.InvoicePending).isClaimable) - - // A stalled updates stream leaves the swap at SwapCreated locally even once Boltz has - // locked up on-chain, so the claim must stay reachable: this is the recovery case. - assertTrue(swap(status = BoltzSwapStatus.SwapCreated).isClaimable) - } - - @Test - fun `isClaimable is false for terminal, already claimed, and submarine swaps`() { - assertFalse(swap(status = BoltzSwapStatus.SwapExpired).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.TransactionFailed).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.TransactionLockupFailed).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.TransactionRefunded).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.TransactionClaimed).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.InvoiceSettled).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.InvoiceExpired).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.InvoiceFailedToPay).isClaimable) - assertFalse(swap(status = BoltzSwapStatus.TransactionConfirmed, claimTxId = TXID).isClaimable) - assertFalse( - swap(swapType = BoltzSwapType.SUBMARINE, status = BoltzSwapStatus.TransactionConfirmed).isClaimable, - ) - } - - private fun swap( - id: String = SWAP_ID, - swapType: BoltzSwapType = BoltzSwapType.REVERSE, - status: BoltzSwapStatus = BoltzSwapStatus.TransactionConfirmed, - claimTxId: String? = null, - createdAt: ULong = 0uL, - ) = BoltzSwap( - id = id, - swapType = swapType, - status = status, - network = BoltzNetwork.REGTEST, - swapIndex = 0uL, - amountSat = 100_000uL, - onchainAmountSat = 99_000uL, - invoice = null, - lockupAddress = null, - onchainAddress = null, - timeoutBlockHeight = 800uL, - createdAt = createdAt, - claimTxId = claimTxId, - refundTxId = null, - ) - - private companion object { - const val SWAP_ID = "swap1" - const val TXID = "txid1" - const val LIST_ERROR = "database unavailable" - } -} diff --git a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt index 9037287837..bff1eae702 100644 --- a/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/TransferViewModelTest.kt @@ -2,14 +2,10 @@ package to.bitkit.viewmodels import android.content.Context import app.cash.turbine.test -import com.synonym.bitkitcore.BoltzPairInfo -import com.synonym.bitkitcore.BoltzSwapEvent -import com.synonym.bitkitcore.ReverseSwapResponse import kotlinx.collections.immutable.persistentSetOf import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy @@ -17,9 +13,6 @@ import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Test -import org.lightningdevkit.ldknode.Event -import org.lightningdevkit.ldknode.NodeStatus -import org.lightningdevkit.ldknode.PaymentFailureReason import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer @@ -29,22 +22,16 @@ import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -import to.bitkit.R import to.bitkit.ext.createChannelDetails -import to.bitkit.models.BalanceState import to.bitkit.repositories.LightningRepo -import to.bitkit.repositories.LightningState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState import to.bitkit.repositories.TransferRepo -import to.bitkit.services.BoltzService import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError -import kotlin.math.roundToLong import kotlin.test.assertEquals import kotlin.test.assertFalse -import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -59,24 +46,12 @@ class TransferViewModelTest : BaseUnitTest() { private val lightningRepo = mock() private val transferRepo = mock() private val clock = mock() - private val boltzService = mock() private val sparkState = MutableStateFlow(SparkState()) private val sparkRepo = mock() - private val balanceState = MutableStateFlow(BalanceState()) - private val boltzEvents = MutableSharedFlow(extraBufferCapacity = 8) - private val nodeEvents = MutableSharedFlow(extraBufferCapacity = 8) - @Before fun setUp() { whenever(context.getString(any())).thenReturn("") - val nodeStatus = mock() - whenever(nodeStatus.isRunning).thenReturn(true) - whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState(nodeStatus = nodeStatus))) - whenever(boltzService.events).thenReturn(boltzEvents) - whenever(lightningRepo.nodeEvents).thenReturn(nodeEvents) - whenever(boltzService.isSwapSupported).thenReturn(true) - whenever { boltzService.isSwapEnabled() }.thenReturn(true) whenever(sparkRepo.state).thenReturn(sparkState) whenever { sparkRepo.withdrawAll(any(), any()) }.thenReturn(Result.success(Unit)) whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) }.thenReturn(Result.success(SPARK_FEE)) @@ -87,7 +62,6 @@ class TransferViewModelTest : BaseUnitTest() { context = context, lightningRepo = lightningRepo, transferRepo = transferRepo, - boltzService = boltzService, clock = clock, sparkRepo = sparkRepo, ) @@ -140,7 +114,6 @@ class TransferViewModelTest : BaseUnitTest() { sut.loadSparkWithdrawFee(SPARK_SATS) sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) assertFalse(sut.hasChannelsToClose()) assertTrue(sut.closeSelectedChannels().isEmpty()) verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) @@ -238,18 +211,6 @@ class TransferViewModelTest : BaseUnitTest() { verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) } - @Test - fun `closing instead withdraws spark at the fee shown when spark is priced again before the withdrawal`() = test { - sparkState.value = SparkState(balanceSats = SPARK_SATS) - sut.loadSparkWithdrawFee(SPARK_SATS) - sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true, SavingsTransferMode.CLOSE) - repriceSpark() - - sut.closeSelectedChannels() - - verify(sparkRepo).withdrawAll(CLAIM_ADDRESS, SPARK_FEE) - } - /** A receive lands during the transition, so the confirm screen prices Spark's new balance. */ private suspend fun repriceSpark() { whenever { sparkRepo.estimateWithdrawAllFeeSats(any()) }.thenReturn(Result.success(NEW_SPARK_FEE)) @@ -296,38 +257,6 @@ class TransferViewModelTest : BaseUnitTest() { verify(lightningRepo).closeChannel(CHANNEL_B, false, null) } - @Test - fun `transfer to savings with only spark ignores a quote left from a channel selection`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - assertNotNull(sut.savingsSwapState.value.quote) - - sut.loadSavingsSwapQuote(0uL, 0uL) - advanceUntilIdle() - assertNull(sut.savingsSwapState.value.quote) - - sut.onTransferToSavingsConfirm(channels = emptyList(), withdrawSpark = true) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) - } - - @Test - fun `swap to savings withdraws spark only when it is selected`() = test { - stubSavingsSwapHappyPath() - sparkState.value = SparkState(balanceSats = SPARK_SATS) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.onTransferToSavingsConfirm(channels = listOf(CHANNEL_A), withdrawSpark = false) - assertEquals(SavingsTransferMode.SWAP, sut.savingsTransferMode.value) - sut.startSavingsSwap() - advanceUntilIdle() - - verify(sparkRepo, never()).withdrawAll(any(), any()) - verify(lightningRepo, never()).closeChannel(any(), any(), anyOrNull()) - } - @Test fun `spark is not withdrawn at a fee the user was never shown`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) @@ -388,26 +317,6 @@ class TransferViewModelTest : BaseUnitTest() { assertEquals(SPARK_FEE, sut.sparkWithdrawFeeSats.value) } - @Test - fun `loadSavingsSwapQuote defaults to max transferable within limits and spendable balance`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - val state = sut.savingsSwapState.value - val expectedMax = SPENDABLE_LN - SPENDABLE_LN / 100uL // 1% routing fee reserve - assertEquals(SWAP_MIN, state.minSat) - assertEquals(expectedMax, state.maxSat) - val quote = assertNotNull(state.quote) - assertEquals(expectedMax, quote.amountSat) - assertEquals(SWAP_MINER_FEE, quote.networkFeeSat) - val expectedSwapFee = (expectedMax.toLong() * SWAP_FEE_PERCENT / 100.0).roundToLong().toULong() - assertEquals(expectedSwapFee, quote.swapFeeSat) - assertEquals(expectedMax - expectedSwapFee - SWAP_MINER_FEE, quote.receiveSat) - } - @Test fun `a new transfer to savings withdraws spark to a fresh address`() = test { sparkState.value = SparkState(balanceSats = SPARK_SATS) @@ -518,268 +427,6 @@ class TransferViewModelTest : BaseUnitTest() { verify(sparkRepo, times(1)).withdrawAll(any(), any()) } - @Test - fun `loadSavingsSwapQuote sizes the swap by the selected channels, not spark`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - - sut.loadSavingsSwapQuote(REQUESTED_SAT, channelSendableSat = CHANNEL_SENDABLE) - advanceUntilIdle() - - assertEquals(CHANNEL_SENDABLE - CHANNEL_SENDABLE / 100uL, sut.savingsSwapState.value.maxSat) - } - - @Test - fun `loadSavingsSwapQuote falls back to close when below the swap minimum`() = test { - whenever(context.getString(R.string.lightning__savings_confirm__amount_too_low)).thenReturn(TOO_LOW) - balanceState.value = BalanceState(maxSendLightningSats = SWAP_MIN - 1uL) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - val state = sut.savingsSwapState.value - assertNull(state.quote) - assertEquals(0uL, state.maxSat) - - sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) - - sut.startSavingsSwap() - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Failure(TOO_LOW), sut.savingsSwapResult.value) - } - - @Test - fun `loadSavingsSwapQuote falls back to close when the limits fetch fails`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenAnswer { throw AppError(BOLTZ_ERROR) } - - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - assertNull(sut.savingsSwapState.value.quote) - assertFalse(sut.savingsSwapState.value.isLoading) - - sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) - } - - @Test - fun `loadSavingsSwapQuote skips the network when swaps are unsupported`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.isSwapSupported).thenReturn(false) - - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - assertEquals(SavingsSwapUiState(), sut.savingsSwapState.value) - verify(boltzService, never()).reverseLimits(anyOrNull()) - - sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) - } - - @Test - fun `loadSavingsSwapQuote skips the network when swaps are disabled in dev settings`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.isSwapEnabled()).thenReturn(false) - - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - assertEquals(SavingsSwapUiState(), sut.savingsSwapState.value) - verify(boltzService, never()).reverseLimits(anyOrNull()) - - sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) - } - - @Test - fun `onTransferToSavingsConfirm swaps when a quote is ready and closes when the user opts out`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.onTransferToSavingsConfirm(listOf(CHANNEL_A), withdrawSpark = false) - assertEquals(SavingsTransferMode.SWAP, sut.savingsTransferMode.value) - - sut.onTransferToSavingsConfirm(listOf(CHANNEL_A), withdrawSpark = false, SavingsTransferMode.CLOSE) - assertEquals(SavingsTransferMode.CLOSE, sut.savingsTransferMode.value) - } - - @Test - fun `onTransferToSavingsConfirm clears the outcome of an earlier swap`() = test { - stubSavingsSwapHappyPath() - whenever(lightningRepo.payInvoiceWithNode(any())).thenReturn(Result.failure(AppError(PAY_ERROR))) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - sut.startSavingsSwap() - advanceUntilIdle() - assertEquals(SavingsSwapResult.Failure(PAY_ERROR), sut.savingsSwapResult.value) - - sut.onTransferToSavingsConfirm(emptyList(), withdrawSpark = false) - - assertNull(sut.savingsSwapResult.value) - } - - @Test - fun `onSwapAmountChange clamps to the allowed range and reprices`() = test { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.onSwapAmountChange(SWAP_MIN - 10_000uL) - - assertEquals(SWAP_MIN, sut.savingsSwapState.value.quote?.amountSat) - } - - @Test - fun `startSavingsSwap succeeds when the claim event arrives`() = test { - stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - runCurrent() - boltzEvents.emit(BoltzSwapEvent.Claimed(swapId = SWAP_ID, txid = TXID)) - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Success(TXID), sut.savingsSwapResult.value) - } - - @Test - fun `startSavingsSwap fails when the swap reports an error event`() = test { - stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - runCurrent() - boltzEvents.emit(BoltzSwapEvent.Error(swapId = SWAP_ID, message = BOLTZ_ERROR)) - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Failure(BOLTZ_ERROR), sut.savingsSwapResult.value) - } - - @Test - fun `startSavingsSwap returns pending when the claim does not arrive in time`() = test { - stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - runCurrent() - advanceTimeBy(31.seconds) - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Pending, sut.savingsSwapResult.value) - } - - @Test - fun `startSavingsSwap fails when the invoice payment fails`() = test { - stubSavingsSwapHappyPath() - whenever(lightningRepo.payInvoiceWithNode(any())).thenReturn(Result.failure(AppError(PAY_ERROR))) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Failure(PAY_ERROR), sut.savingsSwapResult.value) - } - - @Test - fun `startSavingsSwap ignores a second start while a swap is in flight`() = test { - stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - runCurrent() - sut.startSavingsSwap() - runCurrent() - boltzEvents.emit(BoltzSwapEvent.Claimed(swapId = SWAP_ID, txid = TXID)) - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Success(TXID), sut.savingsSwapResult.value) - verify(boltzService).createReverseSwap(any(), any(), anyOrNull(), anyOrNull()) - verify(lightningRepo).payInvoiceWithNode(any()) - } - - @Test - fun `startSavingsSwap fails when the paid invoice reports a lightning routing failure`() = test { - stubSavingsSwapHappyPath() - whenever(context.getString(R.string.wallet__payment_route_not_found)) - .thenReturn(ROUTE_NOT_FOUND_MSG) - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - runCurrent() - // payInvoiceWithNode returns as soon as the HTLC is dispatched; the routing failure lands later. - nodeEvents.emit( - Event.PaymentFailed( - paymentId = PAYMENT_ID, - paymentHash = PAYMENT_ID, - reason = PaymentFailureReason.ROUTE_NOT_FOUND, - ), - ) - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Failure(ROUTE_NOT_FOUND_MSG), sut.savingsSwapResult.value) - } - - @Test - fun `startSavingsSwap ignores a restart once an outcome is already delivered`() = test { - stubSavingsSwapHappyPath() - sut.loadSavingsSwapQuote(REQUESTED_SAT, balanceState.value.maxSendLightningSats) - advanceUntilIdle() - - sut.startSavingsSwap() - runCurrent() - boltzEvents.emit(BoltzSwapEvent.Claimed(swapId = SWAP_ID, txid = TXID)) - advanceUntilIdle() - assertEquals(SavingsSwapResult.Success(TXID), sut.savingsSwapResult.value) - - // A configuration change re-fires startSavingsSwap; the delivered outcome must block a rerun. - sut.startSavingsSwap() - advanceUntilIdle() - - assertEquals(SavingsSwapResult.Success(TXID), sut.savingsSwapResult.value) - verify(boltzService).createReverseSwap(any(), any(), anyOrNull(), anyOrNull()) - verify(lightningRepo).payInvoiceWithNode(any()) - } - - private suspend fun stubSavingsSwapHappyPath() { - balanceState.value = BalanceState(maxSendLightningSats = SPENDABLE_LN) - whenever(boltzService.reverseLimits(anyOrNull())).thenReturn(reverseLimits()) - whenever(lightningRepo.newAddress()).thenReturn(Result.success(CLAIM_ADDRESS)) - whenever(boltzService.createReverseSwap(any(), any(), anyOrNull(), anyOrNull())) - .thenReturn(reverseSwapResponse()) - whenever(lightningRepo.payInvoiceWithNode(any())).thenReturn(Result.success(PAYMENT_ID)) - } - - private fun reverseLimits() = BoltzPairInfo( - hash = "hash", - rate = 1.0, - minimalSat = SWAP_MIN, - maximalSat = SWAP_MAX, - feePercentage = SWAP_FEE_PERCENT, - minerFeesSat = SWAP_MINER_FEE, - ) - - private fun reverseSwapResponse() = ReverseSwapResponse( - id = SWAP_ID, - invoice = "lnbc1invoice", - lockupAddress = "bcrt1qlockup", - onchainAmountSat = SWAP_MIN, - timeoutBlockHeight = 800uL, - ) - private companion object { val CHANNEL_A = createChannelDetails().copy(channelId = "channel_a") val CHANNEL_B = createChannelDetails().copy(channelId = "channel_b") @@ -787,20 +434,7 @@ class TransferViewModelTest : BaseUnitTest() { const val NEW_SPARK_SATS = 52_000uL const val SPARK_FEE = 1_470uL const val NEW_SPARK_FEE = 1_620uL - const val CHANNEL_SENDABLE = 60_000uL - const val TXID = "tx-abc" - const val SPENDABLE_LN = 150_000uL - const val REQUESTED_SAT = 200_000uL - const val SWAP_MIN = 25_000uL - const val SWAP_MAX = 1_000_000uL - const val SWAP_FEE_PERCENT = 0.5 - const val SWAP_MINER_FEE = 300uL - const val SWAP_ID = "swap1" const val CLAIM_ADDRESS = "bcrt1qclaim" - const val TOO_LOW = "Amount is too low" const val PAY_ERROR = "no route found" - const val BOLTZ_ERROR = "boltz unavailable" - const val PAYMENT_ID = "paymentId" - const val ROUTE_NOT_FOUND_MSG = "No route to destination" } } diff --git a/docs/screens-map.md b/docs/screens-map.md index af6cbd0dd3..77ad3921dc 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -258,7 +258,6 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | LanguageSettingsScreen.kt | Settings > General › Settings Language | | LogsScreen.kt | `n/a` | | SettingsScreen.kt | Settings Categories › Settings General | -| SwapsScreen.kt | `n/a` | ## ui/settings/advanced