From a1c412ddd38f8195b3a22a19f58e921a179a161f Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 3 Nov 2026 22:22:02 -0800 Subject: [PATCH 01/13] feat(payments): add the Advanced payments screen and route to it when Advanced mode is on AdvancedPaymentsFragment is a regular nav_home destination with the Receive / Internal / Send picker from Figma (6860:47472). Its tabs host the existing child fragments for now; later PRs replace the Receive tab. The bottom-nav payments item and the Home Send/Receive shortcuts share paymentsRoute(): Advanced mode on opens the new screen, off (or an unreadable setting) opens PaymentsFragment as before. The payments item stays highlighted on either screen. The Explore deep link still opens the basic screen. SegmentedPicker gains style options (icon above label, inset, thumb corners, dividers) whose defaults keep the current look. Co-Authored-By: Claude Opus 5.5 --- .../ui/segmented_picker/SegmentedPicker.kt | 64 ++-- .../res/layout/fragment_advanced_payments.xml | 27 ++ wallet/res/navigation/nav_home.xml | 41 +++ .../wallet/ui/main/MainActivityExt.kt | 17 +- .../wallet/ui/main/MainViewModel.kt | 15 + .../wallet/ui/main/WalletFragment.kt | 36 +-- .../ui/payments/AdvancedPaymentsFragment.kt | 283 ++++++++++++++++++ .../ui/payments/AdvancedPaymentsViewModel.kt | 89 ++++++ .../wallet/ui/payments/PaymentsPayFragment.kt | 5 +- .../wallet/ui/payments/PaymentsRoute.kt | 81 +++++ .../ui/payments/AdvancedPaymentsTabsTest.kt | 108 +++++++ .../wallet/ui/payments/PaymentsRouteTest.kt | 93 ++++++ .../util/viewModels/MainViewModelTest.kt | 50 ++++ 13 files changed, 868 insertions(+), 41 deletions(-) create mode 100644 wallet/res/layout/fragment_advanced_payments.xml create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index 249feab879..b630ad6c54 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -73,7 +73,16 @@ data class SegmentedPickerStyle( // slot. Zero by default so existing fixed-height horizontal/vertical toggles are unaffected; // set this for pickers whose options should have visible breathing room between them. val optionPaddingHorizontal: Float = 0f, - val optionPaddingVertical: Float = 0f + val optionPaddingVertical: Float = 0f, + // Inset between the container edge and the thumb/options. The defaults below keep the + // original look (1dp inset, thumb corner = cornerRadius - 2, dividers, icon left of title). + val containerPadding: Float = 1f, + // Null means cornerRadius - 2, the original thumb shape. + val thumbCornerRadius: Float? = null, + val showDividers: Boolean = true, + // Stack each option's icon above its title (e.g. the Advanced payments tabs, Figma 7062:49306) + // instead of placing it to the left. + val iconAboveTitle: Boolean = false ) @Composable @@ -110,7 +119,7 @@ fun SegmentedPicker( modifier = modifier .clip(RoundedCornerShape(style.cornerRadius.dp)) .background(backgroundColor) - .padding(1.dp) + .padding(style.containerPadding.dp) .onGloballyPositioned { coordinates -> containerWidth = coordinates.size.width containerHeight = coordinates.size.height @@ -152,7 +161,7 @@ fun SegmentedPicker( } ) // Draw dividers between options - if (isHorizontal) { + if (isHorizontal && style.showDividers) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly @@ -175,7 +184,7 @@ fun SegmentedPicker( // Draw the animated selection indicator if (containerSize > 0 && showSelection) { Surface( - shape = RoundedCornerShape((style.cornerRadius - 2).dp), + shape = RoundedCornerShape((style.thumbCornerRadius ?: (style.cornerRadius - 2)).dp), color = thumbColor, shadowElevation = style.shadowElevation.dp, modifier = Modifier @@ -213,7 +222,8 @@ fun SegmentedPicker( }, modifier = Modifier.weight(1f), paddingHorizontal = style.optionPaddingHorizontal.dp, - paddingVertical = style.optionPaddingVertical.dp + paddingVertical = style.optionPaddingVertical.dp, + iconAboveTitle = style.iconAboveTitle ) } } @@ -235,7 +245,8 @@ fun SegmentedPicker( modifier = Modifier.weight(1f), isHorizontal = false, paddingHorizontal = style.optionPaddingHorizontal.dp, - paddingVertical = style.optionPaddingVertical.dp + paddingVertical = style.optionPaddingVertical.dp, + iconAboveTitle = style.iconAboveTitle ) } } @@ -252,7 +263,8 @@ private fun OptionContent( modifier: Modifier = Modifier, isHorizontal: Boolean = true, paddingHorizontal: Dp = 0.dp, - paddingVertical: Dp = 0.dp + paddingVertical: Dp = 0.dp, + iconAboveTitle: Boolean = false ) { Box( modifier = modifier @@ -263,23 +275,18 @@ private fun OptionContent( ), contentAlignment = Alignment.Center ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.Center, - modifier = Modifier - .then(if (isHorizontal) Modifier.fillMaxHeight() else Modifier.fillMaxWidth()) - .padding(horizontal = paddingHorizontal, vertical = paddingVertical) - ) { - val colors = LocalDashColors.current + val colors = LocalDashColors.current + val icon: @Composable (Modifier) -> Unit = { iconModifier -> option.icon?.let { Icon( painter = painterResource(id = it), contentDescription = null, tint = if (isSelected) Color.Unspecified else colors.textPrimary.copy(alpha = 0.4f), - modifier = Modifier.padding(end = 6.dp) + modifier = iconModifier ) } - + } + val title: @Composable () -> Unit = { Text( text = option.title, color = if (isSelected) colors.textPrimary else colors.textPrimary.copy(alpha = 0.4f), @@ -287,6 +294,29 @@ private fun OptionContent( textAlign = TextAlign.Center ) } + val contentModifier = Modifier + .then(if (isHorizontal) Modifier.fillMaxHeight() else Modifier.fillMaxWidth()) + .padding(horizontal = paddingHorizontal, vertical = paddingVertical) + + if (iconAboveTitle) { + Column( + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + modifier = contentModifier + ) { + icon(Modifier.padding(bottom = 6.dp)) + title() + } + } else { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center, + modifier = contentModifier + ) { + icon(Modifier.padding(end = 6.dp)) + title() + } + } } } diff --git a/wallet/res/layout/fragment_advanced_payments.xml b/wallet/res/layout/fragment_advanced_payments.xml new file mode 100644 index 0000000000..62b517c2c4 --- /dev/null +++ b/wallet/res/layout/fragment_advanced_payments.xml @@ -0,0 +1,27 @@ + + + + + + + + diff --git a/wallet/res/navigation/nav_home.xml b/wallet/res/navigation/nav_home.xml index 673297a8fd..7adce9a19d 100644 --- a/wallet/res/navigation/nav_home.xml +++ b/wallet/res/navigation/nav_home.xml @@ -162,6 +162,47 @@ app:popExitAnim="@anim/slide_out_left" /> + + + + + + + + + + + + + + { viewModel.logEvent(AnalyticsConstants.Home.SEND_RECEIVE_BUTTON) + // The menu item id stays paymentsFragment; Advanced mode opens + // advancedPaymentsFragment instead (see paymentsRoute). + val route = paymentsRoute(viewModel.advancedMode.value) navController.navigate( - R.id.paymentsFragment, + route.destinationId, null, - NavOptions.Builder() + route.applyAnimations(NavOptions.Builder()) .setLaunchSingleTop(true) .setPopUpTo(navController.graph.startDestinationId, false, true) .setRestoreState(true) @@ -194,8 +199,14 @@ object MainActivityExt { } } } - navController.addOnDestinationChangedListener { _, _, arguments -> + navController.addOnDestinationChangedListener { _, destination, arguments -> navView.isVisible = arguments?.getBoolean("ShowNavBar", false) == true + // NavigationUI only highlights an item whose id matches the destination; + // the Advanced payments screen belongs to the payments item too, so + // reselect then behaves as it does on paymentsFragment. + if (isPaymentsDestination(destination.id)) { + navView.menu.findItem(R.id.paymentsFragment)?.isChecked = true + } } } diff --git a/wallet/src/de/schildbach/wallet/ui/main/MainViewModel.kt b/wallet/src/de/schildbach/wallet/ui/main/MainViewModel.kt index 72356d48c2..ae2a1bcfc5 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/MainViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/MainViewModel.kt @@ -265,6 +265,21 @@ class MainViewModel @Inject constructor( started = SharingStarted.Eagerly, initialValue = true ) + /** + * The Settings "Advanced mode" switch, which picks the payments screen (see + * [de.schildbach.wallet.ui.payments.paymentsRoute]). Held here so a tap on the + * bottom-nav payments item or a Home shortcut reads it without touching disk. + * False (basic mode) until the first read lands and while a read is failing: + * observeAdvancedMode() emits false on an error and keeps retrying, so this + * Eagerly-collected flow never completes. + */ + val advancedMode: StateFlow = walletUIConfig.observeAdvancedMode() + .stateIn( + scope = viewModelScope, + started = SharingStarted.Eagerly, + initialValue = false + ) + private val _remindMetadata = MutableStateFlow(false) val remindMetadata = _remindMetadata.asStateFlow() val showTapToHideHint = walletUIConfig.observe(WalletUIConfig.SHOW_TAP_TO_HIDE_HINT).asLiveData() diff --git a/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt b/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt index cf96e0b233..b988ff4a63 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt @@ -57,6 +57,7 @@ import de.schildbach.wallet.ui.main.shortcuts.ShortcutsViewModel import org.dash.wallet.common.data.PaymentIntent import de.schildbach.wallet.ui.* import de.schildbach.wallet.ui.payments.PaymentsFragment +import de.schildbach.wallet.ui.payments.paymentsRoute import de.schildbach.wallet.ui.payments.SweepWalletActivity import de.schildbach.wallet.ui.send.SendCoinsActivity import de.schildbach.wallet.ui.staking.StakingActivity @@ -388,6 +389,19 @@ class WalletFragment : Fragment(R.layout.home_content) { ) } + /** Opens the payments screen the Advanced mode setting picks, on [activeTab]. */ + private fun navigateToPayments(activeTab: Int) { + val route = paymentsRoute(viewModel.advancedMode.value, activeTab) + findNavController().navigate( + route.destinationId, + bundleOf(PaymentsFragment.ARG_ACTIVE_TAB to activeTab), + route.applyAnimations(NavOptions.Builder()) + .setLaunchSingleTop(true) + .setPopUpTo(R.id.walletFragment, false) + .build() + ) + } + private fun onShortcutTap(shortcut: ShortcutOption) { when (shortcut) { ShortcutOption.SECURE_NOW -> { @@ -415,29 +429,11 @@ class WalletFragment : Fragment(R.layout.home_content) { } ShortcutOption.SEND -> { viewModel.logEvent(AnalyticsConstants.Home.SHORTCUT_SEND) - findNavController().navigate( - R.id.paymentsFragment, - bundleOf( - PaymentsFragment.ARG_ACTIVE_TAB to PaymentsFragment.ACTIVE_TAB_PAY - ), - NavOptions.Builder() - .setLaunchSingleTop(true) - .setPopUpTo(R.id.walletFragment, false) - .build() - ) + navigateToPayments(PaymentsFragment.ACTIVE_TAB_PAY) } ShortcutOption.RECEIVE -> { viewModel.logEvent(AnalyticsConstants.Home.SHORTCUT_RECEIVE) - findNavController().navigate( - R.id.paymentsFragment, - bundleOf( - PaymentsFragment.ARG_ACTIVE_TAB to PaymentsFragment.ACTIVE_TAB_RECEIVE - ), - NavOptions.Builder() - .setLaunchSingleTop(true) - .setPopUpTo(R.id.walletFragment, false) - .build() - ) + navigateToPayments(PaymentsFragment.ACTIVE_TAB_RECEIVE) } ShortcutOption.EXPLORE -> { viewModel.logEvent(AnalyticsConstants.Home.SHORTCUT_EXPLORE) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt new file mode 100644 index 0000000000..6fbb7907ab --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -0,0 +1,283 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import android.annotation.SuppressLint +import android.content.Context +import android.os.Bundle +import android.view.View +import androidx.annotation.VisibleForTesting +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.core.content.edit +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.viewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import androidx.navigation.fragment.findNavController +import androidx.viewpager2.adapter.FragmentStateAdapter +import androidx.viewpager2.widget.ViewPager2 +import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_INTERNAL +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_RECEIVE +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ARG_ACTIVE_TAB +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ARG_SOURCE +import de.schildbach.wallet_test.R +import de.schildbach.wallet_test.databinding.FragmentAdvancedPaymentsBinding +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.ui.components.LocalDashColors +import org.dash.wallet.common.ui.components.MyImages +import org.dash.wallet.common.ui.components.TopNavBase +import org.dash.wallet.common.ui.observeOnDestroy +import org.dash.wallet.common.ui.segmented_picker.SegmentedOption +import org.dash.wallet.common.ui.segmented_picker.SegmentedPicker +import org.dash.wallet.common.ui.segmented_picker.SegmentedPickerStyle +import org.dash.wallet.common.ui.viewBinding + +/** + * The Advanced mode payments screen (MO-1123, Figma 6860:47472): a close button and a + * Receive / Internal / Send picker over the same child pages as [PaymentsFragment]. + * + * It is a plain `` destination for now and is meant to become a sheet, so: + * all navigation goes through the NavController; the tab set is (re)applied on the + * view's lifecycle from [AdvancedPaymentsViewModel], not once in [onViewCreated]; the + * screen pads itself for the system bars and the IME and never touches status-bar + * colours; the close control is in the screen's own content; and the enter/exit + * transitions are on the NavOptions (see [paymentsRoute]), not set here. + * + * The pages are hosted by ViewPager2 like [PaymentsFragment]'s: + * [PaymentsReceiveFragment] relies on ViewPager2 keeping an offscreen page at STARTED + * and only the selected one at RESUMED (see its `shouldSurfaceAddressFailure`). + */ +@AndroidEntryPoint +class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { + + companion object { + // Separate from PaymentsFragment's recent tab, which is private to it. + private const val PREFS_RECENT_TAB = "advanced_payments_recent_tab" + private const val STATE_SELECTED_TAB = "selected_tab" + + /** The pager position of [tabId] in [tabIds]; the first page if it is not shown. */ + @VisibleForTesting + fun positionOf(tabIds: List, tabId: Int): Int = + tabIds.indexOf(tabId).takeIf { it >= 0 } ?: 0 + } + + private val binding by viewBinding(FragmentAdvancedPaymentsBinding::bind) + private val viewModel by viewModels() + + private var tabIds by mutableStateOf>(emptyList()) + private var selectedPosition by mutableIntStateOf(0) + + /** The logical tab the user is on; kept across view recreation and tab-set changes. */ + private var selectedTabId: Int? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (savedInstanceState?.containsKey(STATE_SELECTED_TAB) == true) { + selectedTabId = savedInstanceState.getInt(STATE_SELECTED_TAB) + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + val binding = this.binding + + // Own insets: under MainActivity's fitsSystemWindows container these arrive + // already consumed (zero), so nothing is doubled; hosted anywhere else (a + // sheet), the screen still clears the system bars and the keyboard. + ViewCompat.setOnApplyWindowInsetsListener(binding.root) { root, insets -> + val bars = insets.getInsets( + WindowInsetsCompat.Type.systemBars() or + WindowInsetsCompat.Type.displayCutout() or + WindowInsetsCompat.Type.ime() + ) + root.updatePadding(left = bars.left, top = bars.top, right = bars.right, bottom = bars.bottom) + WindowInsetsCompat.CONSUMED + } + + binding.header.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + binding.header.setContent { + DashWalletTheme { + Header() + } + } + + val adapter = TabsAdapter(this, source = arguments?.getString(ARG_SOURCE) ?: "") + binding.pager.adapter = adapter + viewLifecycleOwner.observeOnDestroy { binding.pager.adapter = null } + binding.pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { + override fun onPageSelected(position: Int) { + val tabId = adapter.tabIds.getOrNull(position) ?: return + selectedPosition = position + selectedTabId = tabId + + if (arguments?.containsKey(ARG_ACTIVE_TAB) != true) { + requireActivity().getPreferences(Context.MODE_PRIVATE) + .edit { putInt(PREFS_RECENT_TAB, tabId) } + } + } + }) + + viewLifecycleOwner.lifecycleScope.launch { + viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { + viewModel.uiState + .map { it.tabIds } + .filterNotNull() + .distinctUntilChanged() + .collect { showTabs(adapter, it) } + } + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + selectedTabId?.let { outState.putInt(STATE_SELECTED_TAB, it) } + } + + private fun showTabs(adapter: TabsAdapter, newTabIds: List) { + // Decide the tab before the adapter changes: a data-set change can report a + // page selection of its own. + val wanted = selectedTabId ?: initialTabId() + val position = positionOf(newTabIds, wanted) + adapter.submit(newTabIds) + tabIds = newTabIds + selectedPosition = position + selectedTabId = newTabIds[position] + binding.pager.setCurrentItem(position, false) + } + + private fun initialTabId(): Int = + if (arguments?.containsKey(ARG_ACTIVE_TAB) == true) { + requireArguments().getInt(ARG_ACTIVE_TAB, ACTIVE_TAB_RECEIVE) + } else { + requireActivity().getPreferences(Context.MODE_PRIVATE) + .getInt(PREFS_RECENT_TAB, ACTIVE_TAB_RECEIVE) + } + + private fun close() { + findNavController().popBackStack() + } + + @Composable + private fun Header() { + val colors = LocalDashColors.current + Column(modifier = Modifier.fillMaxWidth()) { + // Figma 7062:49304: no title, a circled close button on the right. + TopNavBase( + leadingPart = false, + centralPart = false, + trailingIcon = MyImages.NavBarClose, + trailingContentDescription = stringResource(org.dash.wallet.common.R.string.button_close), + onTrailingClick = ::close + ) + + val ids = tabIds + if (ids.isNotEmpty()) { + val options = ids.map { tabId -> + when (tabId) { + ACTIVE_TAB_RECEIVE -> SegmentedOption( + stringResource(R.string.payments_tab_receive_label), + R.drawable.ic_arrow_down + ) + ACTIVE_TAB_INTERNAL -> SegmentedOption( + stringResource(R.string.shielded_tab_internal), + R.drawable.ic_arrows_internal + ) + else -> SegmentedOption( + stringResource(R.string.payments_tab_pay_label), + R.drawable.ic_arrow_up + ) + } + } + // Figma 7062:49306: 70dp, 20dp corners, 4dp inset, 16dp thumb corners, + // icon above the title, no dividers, gray300 @ 20% track. + SegmentedPicker( + options = options, + modifier = Modifier + .padding(start = 20.dp, end = 20.dp, top = 10.dp, bottom = 20.dp) + .fillMaxWidth() + .height(70.dp), + selectedIndex = selectedPosition, + style = SegmentedPickerStyle( + backgroundColor = colors.gray300.copy(alpha = 0.2f), + cornerRadius = 20f, + containerPadding = 4f, + thumbCornerRadius = 16f, + showDividers = false, + iconAboveTitle = true + ) + ) { _, index -> + selectedPosition = index + binding.pager.currentItem = index + } + } + } + } + + /** + * Pages keyed by logical tab id (stable ids), so a change of tab set — the + * shielded flag flipping — keeps the pages that remain and drops only the + * one that went away. + */ + private class TabsAdapter( + fragment: Fragment, + private val source: String + ) : FragmentStateAdapter(fragment) { + var tabIds: List = emptyList() + private set + + @SuppressLint("NotifyDataSetChanged") + fun submit(newTabIds: List) { + if (newTabIds == tabIds) return + tabIds = newTabIds + notifyDataSetChanged() + } + + override fun getItemCount(): Int = tabIds.size + + override fun getItemId(position: Int): Long = tabIds[position].toLong() + + override fun containsItem(itemId: Long): Boolean = tabIds.any { it.toLong() == itemId } + + override fun createFragment(position: Int): Fragment = when (tabIds[position]) { + ACTIVE_TAB_RECEIVE -> PaymentsReceiveFragment.newInstance() + ACTIVE_TAB_INTERNAL -> PaymentsInternalFragment.newInstance() + else -> PaymentsPayFragment.newInstance(source = source) + } + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt new file mode 100644 index 0000000000..2d73125485 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.Constants +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.retryWhen +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import org.slf4j.LoggerFactory +import javax.inject.Inject + +/** + * @property tabIds the logical tab ids in display order (see [PaymentsFragment.tabIdsFor]), + * or null until the shielded flag has been read: the screen builds no pages until then. + */ +data class AdvancedPaymentsUIState( + val tabIds: List? = null +) + +@HiltViewModel +class AdvancedPaymentsViewModel @Inject constructor( + dashPayConfig: DashPayConfig +) : ViewModel() { + companion object { + private val log = LoggerFactory.getLogger(AdvancedPaymentsViewModel::class.java) + } + + private val _uiState = MutableStateFlow(AdvancedPaymentsUIState()) + val uiState: StateFlow = _uiState.asStateFlow() + + init { + viewModelScope.launch { + advancedPaymentsTabsFlow( + shieldedFlag = dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED), + supportsPlatform = Constants.SUPPORTS_PLATFORM, + onError = { e, attempt -> log.warn("shielded flag read failed (attempt {})", attempt, e) } + ).collect { tabIds -> + _uiState.update { it.copy(tabIds = tabIds) } + } + } + } +} + +/** + * The tab set for the Advanced payments screen. Same gating as [PaymentsFragment]: the + * "Internal" tab needs `SUPPORTS_PLATFORM` and `USE_KOTLIN_SDK_SHIELDED`. A failed read + * hides it (as [DashPayConfig.get] reading absent does for [PaymentsFragment]) and keeps + * retrying, so the flow never completes on an error. + */ +internal fun advancedPaymentsTabsFlow( + shieldedFlag: Flow, + supportsPlatform: Boolean, + onError: (Throwable, Long) -> Unit = { _, _ -> }, + retryDelayMs: (Long) -> Long = { attempt -> (attempt.coerceIn(0L, 11L) + 1) * 5_000L } +): Flow> = shieldedFlag + .map { PaymentsFragment.tabIdsFor(supportsPlatform && it == true) } + .retryWhen { e, attempt -> + onError(e, attempt) + emit(PaymentsFragment.tabIdsFor(false)) + delay(retryDelayMs(attempt)) + true + } + .distinctUntilChanged() diff --git a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt index ddc76a219f..5dbdc7d4a2 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt @@ -110,7 +110,10 @@ class PaymentsPayFragment : Fragment(R.layout.fragment_payments_pay), OnContactI analytics.logEvent(AnalyticsConstants.SendReceive.SEND_TO_ADDRESS, mapOf()) val destination = findNavController().currentDestination as? FragmentNavigator.Destination - if (destination?.className == PaymentsFragment::class.java.name) { + // Either payments screen hosts this page; both declare payments_to_addressInput. + if (destination?.className == PaymentsFragment::class.java.name || + destination?.className == AdvancedPaymentsFragment::class.java.name + ) { findNavController().navigate(PaymentsFragmentDirections.paymentsToAddressInput()) } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt new file mode 100644 index 0000000000..86671ea6b2 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt @@ -0,0 +1,81 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import androidx.annotation.AnimRes +import androidx.annotation.IdRes +import androidx.navigation.NavOptions +import de.schildbach.wallet_test.R + +/** + * Where a "payments" entry point (the bottom-nav payments item, the Home Send + * and Receive shortcuts) goes. + * + * @property destinationId the nav destination: [R.id.advancedPaymentsFragment] + * in Advanced mode, [R.id.paymentsFragment] otherwise. + * @property activeTab the logical tab to open ([PaymentsFragment.ACTIVE_TAB_RECEIVE], + * [PaymentsFragment.ACTIVE_TAB_PAY], ...), or null to let the screen restore + * the most recent one. + * @property enterAnim / [popExitAnim] the transition for this route, set on the + * [NavOptions] rather than in the fragment; null keeps the destination's + * existing behaviour (basic mode animates inside [PaymentsFragment]). + */ +data class PaymentsRoute( + @IdRes val destinationId: Int, + val activeTab: Int?, + @AnimRes val enterAnim: Int?, + @AnimRes val popExitAnim: Int? +) { + /** Adds this route's transition, if any, to [builder]. */ + fun applyAnimations(builder: NavOptions.Builder): NavOptions.Builder { + enterAnim?.let { builder.setEnterAnim(it) } + popExitAnim?.let { builder.setPopExitAnim(it) } + return builder + } +} + +/** + * The single routing decision shared by every payments entry point. + * + * [advancedMode] is the value held by MainViewModel.advancedMode: false until + * the setting has been read, and false while a read is failing, so an unknown + * setting always opens the basic screen. + */ +fun paymentsRoute(advancedMode: Boolean, activeTab: Int? = null): PaymentsRoute = + if (advancedMode) { + PaymentsRoute( + destinationId = R.id.advancedPaymentsFragment, + activeTab = activeTab, + enterAnim = R.anim.slide_in_bottom, + popExitAnim = R.anim.slide_out_bottom + ) + } else { + PaymentsRoute( + destinationId = R.id.paymentsFragment, + activeTab = activeTab, + enterAnim = null, + popExitAnim = null + ) + } + +/** + * Whether [destinationId] is one of the payments screens, i.e. whether the + * bottom-nav payments item ([R.id.paymentsFragment]) should be shown selected. + */ +fun isPaymentsDestination(@IdRes destinationId: Int): Boolean = + destinationId == R.id.paymentsFragment || destinationId == R.id.advancedPaymentsFragment diff --git a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt new file mode 100644 index 0000000000..c7569a1fd7 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt @@ -0,0 +1,108 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_INTERNAL +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_PAY +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_RECEIVE +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.Dispatchers +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test +import java.io.IOException + +@OptIn(ExperimentalCoroutinesApi::class) +class AdvancedPaymentsTabsTest { + private val twoTabs = listOf(ACTIVE_TAB_RECEIVE, ACTIVE_TAB_PAY) + private val threeTabs = listOf(ACTIVE_TAB_RECEIVE, ACTIVE_TAB_INTERNAL, ACTIVE_TAB_PAY) + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `same gating as PaymentsFragment`() = runBlocking { + assertEquals(threeTabs, advancedPaymentsTabsFlow(flowOf(true), supportsPlatform = true).first()) + assertEquals(twoTabs, advancedPaymentsTabsFlow(flowOf(false), supportsPlatform = true).first()) + assertEquals(twoTabs, advancedPaymentsTabsFlow(flowOf(null), supportsPlatform = true).first()) + assertEquals(twoTabs, advancedPaymentsTabsFlow(flowOf(true), supportsPlatform = false).first()) + } + + @Test + fun `an unreadable flag hides Internal, then recovers`() = runBlocking { + var reads = 0 + val flag = flow { + if (reads++ == 0) throw IOException("datastore unreadable") + emit(true) + } + val emitted = advancedPaymentsTabsFlow(flag, supportsPlatform = true, retryDelayMs = { 0L }) + .take(2) + .toList() + assertEquals(listOf(twoTabs, threeTabs), emitted) + } + + @Test + fun `view model state is empty until the flag is read, then follows it`() { + val flag = MutableStateFlow(false) + val config = mockk { + every { observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) } returns flag + } + val viewModel = AdvancedPaymentsViewModel(config) + // Constants.SUPPORTS_PLATFORM decides whether a set flag can add Internal. + val expectedWhenOn = PaymentsFragment.tabIdsFor(de.schildbach.wallet.Constants.SUPPORTS_PLATFORM) + + assertEquals(twoTabs, viewModel.uiState.value.tabIds) + flag.value = true + assertEquals(expectedWhenOn, viewModel.uiState.value.tabIds) + } + + @Test + fun `initial state has no tabs`() { + assertNull(AdvancedPaymentsUIState().tabIds) + } + + @Test + fun `a tab that is not shown falls back to the first page`() { + assertEquals(1, AdvancedPaymentsFragment.positionOf(threeTabs, ACTIVE_TAB_INTERNAL)) + assertEquals(2, AdvancedPaymentsFragment.positionOf(threeTabs, ACTIVE_TAB_PAY)) + assertEquals(1, AdvancedPaymentsFragment.positionOf(twoTabs, ACTIVE_TAB_PAY)) + assertEquals(0, AdvancedPaymentsFragment.positionOf(twoTabs, ACTIVE_TAB_INTERNAL)) + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt new file mode 100644 index 0000000000..19f85cbe53 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt @@ -0,0 +1,93 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import de.schildbach.wallet_test.R +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.runBlocking +import org.dash.wallet.common.data.advancedModeFlow +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.IOException + +class PaymentsRouteTest { + private val tabs = listOf( + PaymentsFragment.ACTIVE_TAB_RECEIVE, + PaymentsFragment.ACTIVE_TAB_INTERNAL, + PaymentsFragment.ACTIVE_TAB_PAY + ) + + @Test + fun `advanced mode off opens the basic screen with no extra transition`() { + val route = paymentsRoute(advancedMode = false) + assertEquals(R.id.paymentsFragment, route.destinationId) + assertNull(route.activeTab) + assertNull(route.enterAnim) + assertNull(route.popExitAnim) + } + + @Test + fun `advanced mode on opens the advanced screen with its transition`() { + val route = paymentsRoute(advancedMode = true) + assertEquals(R.id.advancedPaymentsFragment, route.destinationId) + assertNull(route.activeTab) + assertEquals(R.anim.slide_in_bottom, route.enterAnim) + assertEquals(R.anim.slide_out_bottom, route.popExitAnim) + } + + @Test + fun `every tab is passed through unchanged in both modes`() { + for (advanced in listOf(false, true)) { + for (tab in tabs) { + val route = paymentsRoute(advanced, tab) + assertEquals(tab, route.activeTab) + assertEquals( + if (advanced) R.id.advancedPaymentsFragment else R.id.paymentsFragment, + route.destinationId + ) + } + } + } + + @Test + fun `an unreadable setting routes to the basic screen`() = runBlocking { + // What MainViewModel.advancedMode holds while the read fails. + val advanced = advancedModeFlow( + flow { throw IOException("datastore unreadable") }, + retryDelayMs = { 0L } + ).first() + assertEquals(R.id.paymentsFragment, paymentsRoute(advanced).destinationId) + } + + @Test + fun `an unset setting routes to the basic screen`() = runBlocking { + val advanced = advancedModeFlow(flow { emit(null) }).first() + assertEquals(R.id.paymentsFragment, paymentsRoute(advanced).destinationId) + } + + @Test + fun `both payments screens highlight the payments item`() { + assertTrue(isPaymentsDestination(R.id.paymentsFragment)) + assertTrue(isPaymentsDestination(R.id.advancedPaymentsFragment)) + assertFalse(isPaymentsDestination(R.id.walletFragment)) + } +} diff --git a/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt b/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt index 348996c4e6..e7e826038c 100644 --- a/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt @@ -206,6 +206,7 @@ class MainViewModelTest { every { observe(any>()) } returns MutableStateFlow(false) every { observe(WalletUIConfig.SELECTED_CURRENCY) } returns MutableStateFlow("USD") every { observePreservingErrors(any>()) } returns MutableStateFlow(false) + every { observeAdvancedMode() } returns MutableStateFlow(false) } private val identityRepository = mockk() { @@ -564,6 +565,55 @@ class MainViewModelTest { assertEquals(true, viewModel.hideBalance.value) } + /** + * [MainViewModel.advancedMode] is what the payments entry points route on: it must + * start as basic mode before the read lands and then mirror the saved setting, + * including a later change, without anyone collecting it (Eagerly). + */ + @Test(timeout = 1000) + fun `advancedMode starts basic, then mirrors the saved setting`() { + val saved = MutableStateFlow(false) + every { uiConfigMock.observeAdvancedMode() } returns saved + + val viewModel = MainViewModel( + analyticsService, + configMock, + uiConfigMock, + exchangeRatesMock, + walletDataMock, + walletApp, + identityRepository, + platformRepo, + platformService, + platformSyncService, + blockchainIdentityConfigMock, + savedStateMock, + blockchainStateMock, + biometricHelper, + deviceInfoProvider, + invitationsDaoMock, + usernameRequestDaoMock, + userAgentDaoMock, + dashPayProfileDaoMock, + mockDashPayConfig, + dashPayContactRequestDao, + txDisplayCacheService, + crowdNodeApi, + coinJoinFundsMigrationService, + l1SyncStatusService, + contactRequestNotificationService, + swapProvider, + sdkBindRetryService, + shieldedBalanceService + ) + + assertEquals(false, viewModel.advancedMode.value) + saved.value = true + assertEquals(true, viewModel.advancedMode.value) + saved.value = false + assertEquals(false, viewModel.advancedMode.value) + } + /** * Companion to the fail-closed test above: pins the *recovery* half of the same * contract. `retryWhen` must resubscribe to the upstream read after failing closed, From c24a3cda234caed50de34cf493bec96962b6e127 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 09:17:52 -0800 Subject: [PATCH 02/13] feat(payments): build the Advanced Receive tab to the Figma design The Advanced payments screen now matches Figma 7062:49303: no close button, the bottom nav stays visible, and the Receive tab is a Compose card with a Core / Shield / Platform / Identity switch, the QR code, Username and address rows with copy buttons, and Share address / Specify amount buttons. - Core keeps the existing live-address path and its fail-closed rule; the QR is the dash: URI. Specify amount still opens ReceiveFragment. - Shield, Platform and Identity show the bare address or identity ID in the QR and hide Specify amount. Shield and Platform follow the same gating as the Internal tab; Identity needs a username. - ShieldedBalanceService gains platformReceiveAddress(). - SegmentedPicker gains a left-aligned, scrollable fit-to-content mode; DashButton gains optional side padding and shrink-to-fit text. Both default to the current look. - Swiping between Receive / Internal / Send is off on this screen so a drag on the balance switch scrolls it. The basic payments screen and PaymentsReceiveFragment are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../wallet/common/ui/components/DashButton.kt | 46 ++- .../ui/segmented_picker/SegmentedPicker.kt | 105 +++++- wallet/res/navigation/nav_home.xml | 7 +- wallet/res/values/strings.xml | 15 + .../platform/sdk/ShieldedBalanceService.kt | 9 + .../sdk/ShieldedBalanceServiceImpl.kt | 12 + .../ui/payments/AdvancedPaymentsFragment.kt | 47 +-- .../ui/payments/AdvancedReceiveFragment.kt | 109 ++++++ .../ui/payments/ReceiveAddressSources.kt | 75 ++++ .../wallet/ui/payments/ReceivePage.kt | 331 +++++++++++++++++ .../wallet/ui/payments/ReceiveViewModel.kt | 327 +++++++++++++++++ .../sdk/ShieldedBalanceServiceTest.kt | 21 ++ .../ui/payments/ReceiveViewModelTest.kt | 338 ++++++++++++++++++ 13 files changed, 1410 insertions(+), 32 deletions(-) create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt diff --git a/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt b/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt index 77e02a5227..200a2fa1fe 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt @@ -19,9 +19,15 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector @@ -45,6 +51,11 @@ fun DashButton( stretch: Boolean = true, isEnabled: Boolean = true, isLoading: Boolean = false, + // Overrides [size]'s side padding when set; null keeps the size's own (every existing use). + horizontalPadding: Dp? = null, + // Keep the label on one line and shrink its font until it fits instead of ellipsizing it, + // for buttons that share a narrow row (large font scales). Off by default. + shrinkTextToFit: Boolean = false, onClick: () -> Unit ) { val colors = LocalDashColors.current @@ -109,7 +120,10 @@ fun DashButton( contentColor = contentColor, disabledContainerColor = Color.Transparent ), - contentPadding = PaddingValues(horizontal = size.paddingHorizontal, vertical = size.paddingVertical), + contentPadding = PaddingValues( + horizontal = horizontalPadding ?: size.paddingHorizontal, + vertical = size.paddingVertical + ), elevation = null ) { if (leadingIcon != null) { @@ -131,7 +145,9 @@ fun DashButton( ) Spacer(modifier = Modifier.width(size.iconSpacing)) } - if (text != null) { + if (text != null && shrinkTextToFit) { + ShrinkToFitText(text, size, contentColor) + } else if (text != null) { Text( text, fontSize = size.fontSize, @@ -155,6 +171,32 @@ fun DashButton( } } +/** One-line label whose font steps down (to at most half of [size]'s) until it fits. */ +@Composable +private fun ShrinkToFitText(text: String, size: Size, color: Color) { + var scale by remember(text, size) { mutableFloatStateOf(1f) } + var fits by remember(text, size) { mutableStateOf(false) } + Text( + text, + fontSize = size.fontSize * scale, + lineHeight = size.lineSize * scale, + style = OverlineSemibold, + color = color, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Clip, + onTextLayout = { result -> + if (result.hasVisualOverflow && scale > 0.5f) { + scale -= 0.05f + } else { + fits = true + } + }, + // Draw only the size that fits, so the steps down never flash on screen. + modifier = Modifier.drawWithContent { if (fits) drawContent() } + ) +} + enum class Style { Plain, Outlined, diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index b630ad6c54..54121a83c6 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -23,7 +23,9 @@ import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon @@ -35,6 +37,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.colorResource @@ -82,7 +85,12 @@ data class SegmentedPickerStyle( val showDividers: Boolean = true, // Stack each option's icon above its title (e.g. the Advanced payments tabs, Figma 7062:49306) // instead of placing it to the left. - val iconAboveTitle: Boolean = false + val iconAboveTitle: Boolean = false, + // Size each option to its own content (plus optionPaddingHorizontal) and start-align them, + // scrolling horizontally when they overflow, instead of splitting the width equally. The + // thumb then follows the selected option's measured bounds (e.g. the Receive balance tabs, + // Figma 7062:49313). Horizontal mode only; off by default. + val fitOptionsToContent: Boolean = false ) @Composable @@ -97,6 +105,10 @@ fun SegmentedPicker( onOptionSelected: (SegmentedOption, Int) -> Unit = { _, _ -> }, ) { if (options.isEmpty()) return + if (style.fitOptionsToContent && style.displayMode == PickerDisplayMode.Horizontal) { + FitContentSegmentedPicker(options, modifier, selectedIndex, showSelection, style, onOptionSelected) + return + } var internalSelectedIndex by remember { mutableIntStateOf(selectedIndex) } var isInitialPosition by remember { mutableStateOf(true) } @@ -254,6 +266,97 @@ fun SegmentedPicker( } } +/** + * [SegmentedPicker] with [SegmentedPickerStyle.fitOptionsToContent]: options keep their own + * width, start-aligned, and scroll horizontally when they do not fit. The thumb is drawn under + * the selected option's measured bounds. + */ +@Composable +private fun FitContentSegmentedPicker( + options: List, + modifier: Modifier, + selectedIndex: Int, + showSelection: Boolean, + style: SegmentedPickerStyle, + onOptionSelected: (SegmentedOption, Int) -> Unit +) { + var internalSelectedIndex by remember { mutableIntStateOf(selectedIndex) } + LaunchedEffect(selectedIndex) { + internalSelectedIndex = selectedIndex + } + + val density = LocalDensity.current + val colors = LocalDashColors.current + val backgroundColor = style.backgroundColor ?: colors.gray400.copy(alpha = 0.1f) + val thumbColor = style.thumbColor ?: colors.backgroundSecondary + + // Each option's x offset and width inside the row, in px; filled in on layout. + val bounds = remember(options.size) { + mutableStateListOf?>().apply { repeat(options.size) { add(null) } } + } + val selectedBounds = bounds.getOrNull(internalSelectedIndex) + var hasPlacedThumb by remember { mutableStateOf(false) } + val animationSpec = tween(durationMillis = if (hasPlacedThumb) 200 else 0) + val thumbOffset by animateDpAsState( + targetValue = with(density) { (selectedBounds?.first ?: 0).toDp() }, + animationSpec = animationSpec, + label = "fitThumbOffset", + finishedListener = { hasPlacedThumb = true } + ) + val thumbWidth by animateDpAsState( + targetValue = with(density) { (selectedBounds?.second ?: 0).toDp() }, + animationSpec = animationSpec, + label = "fitThumbWidth" + ) + + Box( + modifier = modifier + .clip(RoundedCornerShape(style.cornerRadius.dp)) + .background(backgroundColor) + .padding(style.containerPadding.dp) + .horizontalScroll(rememberScrollState()) + ) { + Box(modifier = Modifier.fillMaxHeight()) { + if (showSelection && selectedBounds != null) { + Surface( + shape = RoundedCornerShape((style.thumbCornerRadius ?: (style.cornerRadius - 2)).dp), + color = thumbColor, + shadowElevation = style.shadowElevation.dp, + modifier = Modifier + .offset(x = thumbOffset) + .width(thumbWidth) + .fillMaxHeight() + ) { } + } + Row(modifier = Modifier.fillMaxHeight()) { + options.forEachIndexed { index, option -> + OptionContent( + option = option, + isSelected = showSelection && index == internalSelectedIndex, + textStyle = style.textStyle, + onSelect = { + hasPlacedThumb = true + internalSelectedIndex = index + onOptionSelected(option, index) + }, + modifier = Modifier + .fillMaxHeight() + .onGloballyPositioned { coordinates -> + val entry = coordinates.positionInParent().x.toInt() to coordinates.size.width + if (index < bounds.size && bounds[index] != entry) { + bounds[index] = entry + } + }, + paddingHorizontal = style.optionPaddingHorizontal.dp, + paddingVertical = style.optionPaddingVertical.dp, + iconAboveTitle = style.iconAboveTitle + ) + } + } + } + } +} + @Composable private fun OptionContent( option: SegmentedOption, diff --git a/wallet/res/navigation/nav_home.xml b/wallet/res/navigation/nav_home.xml index 7adce9a19d..f7df1022b9 100644 --- a/wallet/res/navigation/nav_home.xml +++ b/wallet/res/navigation/nav_home.xml @@ -163,7 +163,8 @@ + Core + Shield + Platform + Identity + DASH address + Shielded address + Platform address + Identity ID + Share address + Specify amount + Copy username + Copy address + QR code for the address below + This address is not available right now diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt index 99b509bd8b..b0a653152a 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -332,6 +332,15 @@ interface ShieldedBalanceService { */ suspend fun shieldedReceiveAddress(): String? + /** + * The wallet's own Platform (DIP-17) receive address as stored by the SDK + * — the lowest unused index, else the lowest index of any state, the same + * row [unshieldToCredits] pays itself to — or null when the flag is off, + * the runtime is not ready, or the SDK's address store has no row for the + * wallet yet. Never throws (except cancellation). + */ + suspend fun platformReceiveAddress(): String? + /** * Shield [amount] from the wallet's own Platform credit balance into * its own shielded pool (Type 15). Self-shield only — Rust always diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt index 7551393e85..df57cadf56 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -2050,6 +2050,18 @@ class ShieldedBalanceServiceImpl internal constructor( } } + override suspend fun platformReceiveAddress(): String? { + if (!ensureShieldedReady()) return null + val walletId = readyWalletIdHex.value?.let(::walletIdFromHex) ?: return null + return try { + source.ownPlatformAddressOrNull(walletId) + } catch (t: Throwable) { + if (t is CancellationException) throw t + log.warn("failed to read the platform receive address", t) + null + } + } + override suspend fun shieldFromCredits(amount: Dash): SdkWriteResult = runShieldedWrite("shieldFromCredits", amount) { walletId, credits -> source.shield(walletId, credits) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt index 6fbb7907ab..77448a0cdb 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -44,7 +44,6 @@ import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle -import androidx.navigation.fragment.findNavController import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import dagger.hilt.android.AndroidEntryPoint @@ -60,8 +59,6 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import org.dash.wallet.common.ui.components.DashWalletTheme import org.dash.wallet.common.ui.components.LocalDashColors -import org.dash.wallet.common.ui.components.MyImages -import org.dash.wallet.common.ui.components.TopNavBase import org.dash.wallet.common.ui.observeOnDestroy import org.dash.wallet.common.ui.segmented_picker.SegmentedOption import org.dash.wallet.common.ui.segmented_picker.SegmentedPicker @@ -69,19 +66,23 @@ import org.dash.wallet.common.ui.segmented_picker.SegmentedPickerStyle import org.dash.wallet.common.ui.viewBinding /** - * The Advanced mode payments screen (MO-1123, Figma 6860:47472): a close button and a - * Receive / Internal / Send picker over the same child pages as [PaymentsFragment]. + * The Advanced mode payments screen (MO-1123, Figma 6860:47472 / 7062:49303): a + * Receive / Internal / Send picker right under the status bar, above the bottom + * navigation (`ShowNavBar` on the destination), over the payments pages. * - * It is a plain `` destination for now and is meant to become a sheet, so: - * all navigation goes through the NavController; the tab set is (re)applied on the + * Receive is [AdvancedReceiveFragment] (the Compose [ReceivePage]); Internal and Send + * are the same child pages as [PaymentsFragment]'s. + * + * All navigation goes through the NavController; the tab set is (re)applied on the * view's lifecycle from [AdvancedPaymentsViewModel], not once in [onViewCreated]; the * screen pads itself for the system bars and the IME and never touches status-bar - * colours; the close control is in the screen's own content; and the enter/exit - * transitions are on the NavOptions (see [paymentsRoute]), not set here. + * colours; and the enter/exit transitions are on the NavOptions (see [paymentsRoute]), + * not set here. There is no close control: like the other bottom-nav screens it is + * left through the bottom navigation or Back. * - * The pages are hosted by ViewPager2 like [PaymentsFragment]'s: - * [PaymentsReceiveFragment] relies on ViewPager2 keeping an offscreen page at STARTED - * and only the selected one at RESUMED (see its `shouldSurfaceAddressFailure`). + * The pages are hosted by ViewPager2 like [PaymentsFragment]'s: ViewPager2 keeps an + * offscreen page at STARTED and lifts only the selected one to RESUMED, which is when + * [AdvancedReceiveFragment] (re)reads its address. */ @AndroidEntryPoint class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { @@ -139,6 +140,9 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { val adapter = TabsAdapter(this, source = arguments?.getString(ARG_SOURCE) ?: "") binding.pager.adapter = adapter + // Only the top picker changes tabs: a sideways drag belongs to the page's own + // content (the Receive balance switch scrolls sideways), never to the pager. + binding.pager.isUserInputEnabled = false viewLifecycleOwner.observeOnDestroy { binding.pager.adapter = null } binding.pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { @@ -189,23 +193,10 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { .getInt(PREFS_RECENT_TAB, ACTIVE_TAB_RECEIVE) } - private fun close() { - findNavController().popBackStack() - } - @Composable private fun Header() { val colors = LocalDashColors.current Column(modifier = Modifier.fillMaxWidth()) { - // Figma 7062:49304: no title, a circled close button on the right. - TopNavBase( - leadingPart = false, - centralPart = false, - trailingIcon = MyImages.NavBarClose, - trailingContentDescription = stringResource(org.dash.wallet.common.R.string.button_close), - onTrailingClick = ::close - ) - val ids = tabIds if (ids.isNotEmpty()) { val options = ids.map { tabId -> @@ -224,12 +215,12 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { ) } } - // Figma 7062:49306: 70dp, 20dp corners, 4dp inset, 16dp thumb corners, + // Figma 7062:49306 (20dp margins, 7062:49303): 70dp, 20dp corners, 4dp inset, 16dp thumb corners, // icon above the title, no dividers, gray300 @ 20% track. SegmentedPicker( options = options, modifier = Modifier - .padding(start = 20.dp, end = 20.dp, top = 10.dp, bottom = 20.dp) + .padding(20.dp) .fillMaxWidth() .height(70.dp), selectedIndex = selectedPosition, @@ -275,7 +266,7 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { override fun containsItem(itemId: Long): Boolean = tabIds.any { it.toLong() == itemId } override fun createFragment(position: Int): Fragment = when (tabIds[position]) { - ACTIVE_TAB_RECEIVE -> PaymentsReceiveFragment.newInstance() + ACTIVE_TAB_RECEIVE -> AdvancedReceiveFragment.newInstance() ACTIVE_TAB_INTERNAL -> PaymentsInternalFragment.newInstance() else -> PaymentsPayFragment.newInstance(source = source) } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt new file mode 100644 index 0000000000..61c13eb36d --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt @@ -0,0 +1,109 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.compose.runtime.getValue +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.fragment.app.Fragment +import androidx.fragment.app.viewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import androidx.navigation.fragment.findNavController +import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet_test.R +import kotlinx.coroutines.launch +import org.dash.wallet.common.services.SystemActionsService +import org.dash.wallet.common.services.analytics.AnalyticsConstants +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.util.shareText +import javax.inject.Inject + +/** + * The Receive page of [AdvancedPaymentsFragment]: hosts [ReceivePage] in its ViewPager2. + * The basic payments screen keeps [PaymentsReceiveFragment]. + * + * ViewPager2 lifts only the selected page to RESUMED, so the address is (re)read when the + * user is actually on Receive, as in [PaymentsReceiveFragment]. + */ +@AndroidEntryPoint +class AdvancedReceiveFragment : Fragment() { + + companion object { + fun newInstance() = AdvancedReceiveFragment() + } + + private val viewModel by viewModels() + + @Inject + lateinit var systemActions: SystemActionsService + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = + ComposeView(requireContext()).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { + DashWalletTheme { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + ReceivePage( + uiState = uiState, + onSelectTab = viewModel::selectTab, + onCopyUsername = { username -> + systemActions.copyText(username, "Dash Username") + }, + onCopyAddress = { address -> + viewModel.logEvent(AnalyticsConstants.SendReceive.COPY_ADDRESS) + systemActions.copyText(address, "Dash address") + }, + onShareAddress = { address -> + viewModel.logEvent(AnalyticsConstants.SendReceive.SHARE) + requireContext().shareText( + address, + getString(org.dash.wallet.common.R.string.request_coins_share_dialog_title) + ) + }, + onSpecifyAmount = ::specifyAmount + ) + } + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + viewModel.logEvent(AnalyticsConstants.SendReceive.SHOW_QR_CODE) + + viewLifecycleOwner.lifecycleScope.launch { + viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) { + viewModel.refresh() + } + } + } + + private fun specifyAmount() { + val navController = findNavController() + // A second tap while the transition runs would find the action missing. + if (navController.currentDestination?.id != R.id.advancedPaymentsFragment) return + viewModel.logEvent(AnalyticsConstants.SendReceive.SPECIFY_AMOUNT) + navController.navigate(PaymentsFragmentDirections.paymentsToReceive()) + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt new file mode 100644 index 0000000000..e3f9b539ed --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import de.schildbach.wallet.data.WalletData +import de.schildbach.wallet.service.platform.sdk.ShieldedBalanceService +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.bitcoinj.core.Context +import org.dash.wallet.common.services.ReceiveAddressUnavailableException +import org.slf4j.LoggerFactory +import javax.inject.Inject + +/** + * Where one balance tab of the Advanced Receive page gets the value it advertises. + */ +fun interface ReceiveAddressSource { + /** + * The address (or ID) to advertise, or null when there is nothing safe to show + * right now. Null is retryable: the page asks again on its next resume. + */ + suspend fun address(): String? +} + +/** + * The Core (L1) receive address: the same live read as [PaymentsViewModel.getCurrentAddress]. + * Post-cutover the dashj key chain is held and its "current" pointer frozen on an address + * the wallet may already have been paid on (SR-03), so this asks the SDK engine and, when + * the engine cannot answer, advertises nothing rather than any dashj fallback. + */ +class CoreReceiveAddressSource(private val walletData: WalletData) : ReceiveAddressSource { + private companion object { + private val log = LoggerFactory.getLogger(CoreReceiveAddressSource::class.java) + } + + override suspend fun address(): String? = withContext(Dispatchers.IO) { + val wallet = walletData.wallet ?: return@withContext null + Context.propagate(wallet.context) + try { + walletData.currentReceiveAddressLive().toBase58() + } catch (ex: ReceiveAddressUnavailableException) { + log.warn("receive address unavailable; advertising nothing", ex) + null + } + } +} + +/** The address sources of the Receive page's balance tabs, except Identity (see [ReceiveViewModel]). */ +class ReceiveAddressSources( + val core: ReceiveAddressSource, + val shielded: ReceiveAddressSource, + val platform: ReceiveAddressSource +) { + @Inject + constructor(walletData: WalletData, shieldedBalanceService: ShieldedBalanceService) : this( + core = CoreReceiveAddressSource(walletData), + shielded = ReceiveAddressSource { shieldedBalanceService.shieldedReceiveAddress() }, + platform = ReceiveAddressSource { shieldedBalanceService.platformReceiveAddress() } + ) +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt new file mode 100644 index 0000000000..e46b2efcce --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -0,0 +1,331 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.BlendMode +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import de.schildbach.wallet_test.R +import org.dash.wallet.common.ui.components.DashButton +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.ui.components.LocalDashColors +import org.dash.wallet.common.ui.components.MyTheme +import org.dash.wallet.common.ui.components.Size +import org.dash.wallet.common.ui.components.Style +import org.dash.wallet.common.ui.segmented_picker.SegmentedOption +import org.dash.wallet.common.ui.segmented_picker.SegmentedPicker +import org.dash.wallet.common.ui.segmented_picker.SegmentedPickerStyle +import org.dash.wallet.common.util.Qr + +/** + * The Receive tab of the Advanced payments screen (Figma 7062:49303, block 7062:49310): + * one card with the balance picker, the QR code, the username and address rows, and the + * Share / Specify amount buttons. + */ +@Composable +fun ReceivePage( + uiState: ReceiveUIState, + onSelectTab: (ReceiveBalanceTab) -> Unit, + onCopyUsername: (String) -> Unit, + onCopyAddress: (String) -> Unit, + onShareAddress: (String) -> Unit, + onSpecifyAmount: () -> Unit, + modifier: Modifier = Modifier +) { + val colors = LocalDashColors.current + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 20.dp, end = 20.dp, bottom = 20.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + // Figma shadows/xs: 0 5 20 #B8C1CC @ 10%. + .shadow( + elevation = 20.dp, + shape = RoundedCornerShape(20.dp), + ambientColor = Color(0x1AB8C1CC), + spotColor = Color(0x1AB8C1CC) + ) + .background(colors.backgroundSecondary, RoundedCornerShape(20.dp)) + ) { + if (uiState.tabs.size > 1) { + BalancePicker(uiState.tabs, uiState.selectedTab, onSelectTab) + } + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(40.dp) + ) { + QrCode(uiState) + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(20.dp) + ) { + val username = uiState.username + if (uiState.showUsername && username != null) { + CopyRow( + label = stringResource(org.dash.wallet.common.R.string.username), + value = username, + copyDescription = stringResource(R.string.receive_copy_username), + onCopy = { onCopyUsername(username) } + ) + } + val address = uiState.address + if (address != null) { + CopyRow( + label = stringResource(addressLabelFor(uiState.selectedTab)), + value = address, + copyDescription = stringResource(R.string.receive_copy_address), + onCopy = { onCopyAddress(address) } + ) + } + } + } + + val address = uiState.address + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 20.dp, end = 20.dp, top = 10.dp, bottom = 20.dp), + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.receive_share_address), + style = Style.TintedGray, + size = Size.Medium, + // Two buttons share the row: Figma 160dp each; keep the full label at large font scales. + horizontalPadding = 8.dp, + shrinkTextToFit = true, + isEnabled = address != null, + onClick = { address?.let(onShareAddress) } + ) + if (uiState.showSpecifyAmount) { + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.receive_specify_amount), + style = Style.TintedGray, + size = Size.Medium, + // Two buttons share the row: Figma 160dp each; keep the full label at large font scales. + horizontalPadding = 8.dp, + shrinkTextToFit = true, + onClick = onSpecifyAmount + ) + } + } + } + } +} + +private fun addressLabelFor(tab: ReceiveBalanceTab): Int = when (tab) { + ReceiveBalanceTab.CORE -> R.string.receive_core_address_label + ReceiveBalanceTab.SHIELD -> R.string.receive_shielded_address_label + ReceiveBalanceTab.PLATFORM -> R.string.receive_platform_address_label + ReceiveBalanceTab.IDENTITY -> R.string.receive_identity_id_label +} + +private fun tabTitleFor(tab: ReceiveBalanceTab): Int = when (tab) { + ReceiveBalanceTab.CORE -> R.string.receive_balance_core + ReceiveBalanceTab.SHIELD -> R.string.receive_balance_shield + ReceiveBalanceTab.PLATFORM -> R.string.receive_balance_platform + ReceiveBalanceTab.IDENTITY -> R.string.receive_balance_identity +} + +/** Figma 7062:49313: text-only segments sized to their labels, the selected one on a gray pill. */ +@Composable +private fun BalancePicker( + tabs: List, + selectedTab: ReceiveBalanceTab, + onSelectTab: (ReceiveBalanceTab) -> Unit +) { + val colors = LocalDashColors.current + val options = tabs.map { SegmentedOption(stringResource(tabTitleFor(it))) } + SegmentedPicker( + options = options, + modifier = Modifier + .padding(horizontal = 20.dp, vertical = 20.dp) + .fillMaxWidth() + .height(40.dp), + selectedIndex = tabs.indexOf(selectedTab).coerceAtLeast(0), + style = SegmentedPickerStyle( + backgroundColor = Color.Transparent, + thumbColor = colors.gray400.copy(alpha = 0.15f), + cornerRadius = 12f, + thumbCornerRadius = 12f, + containerPadding = 0f, + shadowElevation = 0, + showDividers = false, + textStyle = MyTheme.Typography.BodyMediumSemibold, + optionPaddingHorizontal = 20f, + fitOptionsToContent = true + ) + ) { _, index -> + tabs.getOrNull(index)?.let(onSelectTab) + } +} + +/** Figma 7062:49318: a 200dp code on a white 10dp-padded wrap, the Dash logo in the centre. */ +@Composable +private fun QrCode(uiState: ReceiveUIState) { + val colors = LocalDashColors.current + val payload = uiState.qrPayload + Box( + modifier = Modifier + .size(220.dp) + .clip(RoundedCornerShape(10.dp)) + // Always dark modules on white, whatever the theme: many scanners reject an + // inverted code. + .background(if (payload != null) Color.White else colors.backgroundSecondary), + contentAlignment = Alignment.Center + ) { + val bitmap = remember(payload) { payload?.let { Qr.qrBitmap(it) } } + when { + bitmap != null -> { + val description = stringResource(R.string.receive_qr_code_description) + Image( + bitmap = bitmap.asImageBitmap(), + contentDescription = description, + colorFilter = ColorFilter.tint(Color.Black, BlendMode.SrcIn), + modifier = Modifier.size(200.dp) + ) + Image( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_dash_d_circle), + contentDescription = null, + modifier = Modifier.size(44.dp) + ) + } + // Not read yet, or reading: only a read that failed says so. + !uiState.unavailable -> CircularProgressIndicator( + color = colors.dashBlue, + strokeWidth = 2.dp, + modifier = Modifier.size(32.dp) + ) + else -> Text( + text = stringResource(R.string.receive_address_unavailable), + style = MyTheme.Typography.BodyMedium, + color = colors.textSecondary, + textAlign = TextAlign.Center, + modifier = Modifier.padding(20.dp) + ) + } + } +} + +/** Figma 7062:49320 / 7062:49391: label over value, a gray tinted copy button on the right. */ +@Composable +private fun CopyRow(label: String, value: String, copyDescription: String, onCopy: () -> Unit) { + val colors = LocalDashColors.current + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + Text(text = label, style = MyTheme.Typography.Footnote, color = colors.textSecondary) + Text(text = value, style = MyTheme.Typography.BodyLarge, color = colors.textPrimary) + } + CopyButton(description = copyDescription, onClick = onCopy) + } +} + +/** `btn-m tinted-gray` with only an icon: the same tokens as [DashButton]'s TintedGray/Medium. */ +@Composable +private fun CopyButton(description: String, onClick: () -> Unit) { + val colors = LocalDashColors.current + Box( + modifier = Modifier + .size(width = 49.dp, height = 40.dp) + .clip(RoundedCornerShape(14.dp)) + .background(colors.gray.copy(alpha = 0.10f)) + .clickable(role = Role.Button, onClick = onClick) + .semantics { contentDescription = description }, + contentAlignment = Alignment.Center + ) { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_copy), + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(18.dp) + ) + } +} + +@Preview(showBackground = true, widthDp = 420, heightDp = 760) +@Composable +private fun ReceivePagePreview() { + DashWalletTheme { + Box(modifier = Modifier.background(LocalDashColors.current.backgroundPrimary)) { + ReceivePage( + uiState = ReceiveUIState( + tabs = ReceiveBalanceTab.entries, + address = "yZ3XpruChNgctwFvCzQ5WpFg7RpytQVwkA", + qrPayload = "dash:yZ3XpruChNgctwFvCzQ5WpFg7RpytQVwkA", + username = "johndoe" + ), + onSelectTab = {}, + onCopyUsername = {}, + onCopyAddress = {}, + onShareAddress = {}, + onSpecifyAmount = {} + ) + } + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt new file mode 100644 index 0000000000..d1aeb525d5 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -0,0 +1,327 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import androidx.annotation.VisibleForTesting +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.Constants +import de.schildbach.wallet.database.entity.BlockchainIdentityConfig +import de.schildbach.wallet.database.entity.BlockchainIdentityData +import de.schildbach.wallet.ui.dashpay.PlatformRepo +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.retryWhen +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.PaymentURI +import org.dash.wallet.common.services.analytics.AnalyticsService +import org.slf4j.LoggerFactory +import javax.inject.Inject + +/** A balance the Advanced Receive page can receive into, in display order. */ +enum class ReceiveBalanceTab { + CORE, + SHIELD, + PLATFORM, + IDENTITY +} + +/** + * @property tabs the balance tabs on show; Core is always first. + * @property selectedTab the tab whose [address] is on show. + * @property address what [selectedTab] advertises, or null when there is nothing safe to show + * (still loading, or unavailable — see [unavailable]). + * @property qrPayload the QR content for [address]: a `dash:` URI on Core, the bare address or + * ID elsewhere. + * @property loading a read for [selectedTab] is in flight. [address] may still hold the value + * being revalidated, so a resume does not blank the QR. + * @property unavailable the last read for [selectedTab] could not produce an address. + * @property username the user's username, or null when they have none. + */ +data class ReceiveUIState( + val tabs: List = listOf(ReceiveBalanceTab.CORE), + val selectedTab: ReceiveBalanceTab = ReceiveBalanceTab.CORE, + val address: String? = null, + val qrPayload: String? = null, + val loading: Boolean = false, + val unavailable: Boolean = false, + val username: String? = null +) { + /** Specify amount builds a `dash:` payment request, so only Core offers it. */ + val showSpecifyAmount: Boolean get() = selectedTab == ReceiveBalanceTab.CORE + + /** A username identifies a DashPay user, who is paid on Core; the Identity tab is theirs too. */ + val showUsername: Boolean + get() = username != null && + (selectedTab == ReceiveBalanceTab.CORE || selectedTab == ReceiveBalanceTab.IDENTITY) +} + +/** + * The Receive tab of the Advanced payments screen (Figma 7062:49303). + * + * Each balance tab reads its own [ReceiveAddressSource]; Core uses exactly the live read + * of [PaymentsViewModel.requestReceiveAddress], fail-closed: a failed read shows no QR, never + * a stale or dashj address. Reads are single-flight per tab, and a read whose tab is no longer + * selected (or that was superseded) never publishes. + */ +@OptIn(ExperimentalCoroutinesApi::class) +@HiltViewModel +class ReceiveViewModel internal constructor( + private val sources: ReceiveAddressSources, + platformRepo: PlatformRepo, + identityConfig: BlockchainIdentityConfig, + dashPayConfig: DashPayConfig, + private val analytics: AnalyticsService, + private val supportsPlatform: Boolean +) : ViewModel() { + + @Inject + constructor( + sources: ReceiveAddressSources, + platformRepo: PlatformRepo, + identityConfig: BlockchainIdentityConfig, + dashPayConfig: DashPayConfig, + analytics: AnalyticsService + ) : this(sources, platformRepo, identityConfig, dashPayConfig, analytics, Constants.SUPPORTS_PLATFORM) + + companion object { + private val log = LoggerFactory.getLogger(ReceiveViewModel::class.java) + + /** The balance tabs to show, in display order. */ + @VisibleForTesting + fun tabsFor(supportsPlatform: Boolean, shieldedEnabled: Boolean, hasUsername: Boolean): List = + buildList { + add(ReceiveBalanceTab.CORE) + if (supportsPlatform && shieldedEnabled) { + add(ReceiveBalanceTab.SHIELD) + add(ReceiveBalanceTab.PLATFORM) + } + if (hasUsername) { + add(ReceiveBalanceTab.IDENTITY) + } + } + + /** + * The QR content for [address] on [tab]. Core keeps today's `dash:` URI (with the + * username, as [org.dash.wallet.common.ui.receive.ReceiveInfoView] does); the other + * tabs are not base58 L1 addresses, which [PaymentURI] cannot carry, so they encode + * the bare value. + */ + @VisibleForTesting + fun qrPayloadFor(tab: ReceiveBalanceTab, address: String, username: String?): String = + when (tab) { + ReceiveBalanceTab.CORE -> PaymentURI.convertToPaymentURI( + AddressNetwork.fromDashAddress(address), + address, + null, + null, + null, + username + ) + else -> address + } + + /** + * The shielded flag as a never-failing flow: a failed read hides the + * Shield and Platform tabs and is retried, like the Internal tab + * ([advancedPaymentsTabsFlow]). + */ + internal fun shieldedEnabledFlow( + shieldedFlag: Flow, + retryDelayMs: (Long) -> Long = { attempt -> (attempt.coerceIn(0L, 11L) + 1) * 5_000L } + ): Flow = shieldedFlag + .map { it == true } + .retryWhen { e, attempt -> + log.warn("shielded flag read failed (attempt {})", attempt, e) + emit(false) + delay(retryDelayMs(attempt)) + true + } + .distinctUntilChanged() + } + + private val _uiState = MutableStateFlow(ReceiveUIState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private var shieldedEnabled = false + private var identity: BlockchainIdentityData? = null + private var profileUsername: String? = null + + /** The in-flight read, the tab it is for, and its generation: only the latest may publish. */ + private var loadJob: Job? = null + private var loadingTab: ReceiveBalanceTab? = null + private var loadGeneration = 0 + + init { + shieldedEnabledFlow(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) + .onEach { + shieldedEnabled = it + applyTabs() + } + .launchIn(viewModelScope) + + // Same wiring as PaymentsViewModel's profile observer. + identityConfig.observe() + .onEach { data -> + val previousId = identity?.userId + identity = data + applyTabs() + if (_uiState.value.selectedTab == ReceiveBalanceTab.IDENTITY && previousId != data.userId) { + load(ReceiveBalanceTab.IDENTITY, force = true) + } + } + .flatMapLatest { data -> + val userId = data.userId + if (userId != null && data.hasUsername) { + platformRepo.observeProfileByUserId(userId) + } else { + flowOf(null) + } + } + .onEach { profile -> + profileUsername = profile?.username + publishUsername() + } + .launchIn(viewModelScope) + } + + /** Re-read the selected tab's address: on every resume, like [PaymentsReceiveFragment]. */ + fun refresh() { + load(_uiState.value.selectedTab, force = false) + } + + fun selectTab(tab: ReceiveBalanceTab) { + val state = _uiState.value + if (tab == state.selectedTab || tab !in state.tabs) return + _uiState.update { + it.copy(selectedTab = tab, address = null, qrPayload = null, loading = false, unavailable = false) + } + load(tab, force = true) + } + + fun logEvent(eventName: String) { + analytics.logEvent(eventName, mapOf()) + } + + private fun hasUsername(): Boolean = identity?.hasUsername == true + + private fun publishUsername() { + val username = if (hasUsername()) profileUsername ?: identity?.activeUsername else null + _uiState.update { state -> + val payload = state.address?.let { qrPayloadOrNull(state.selectedTab, it, username) } + state.copy(username = username, qrPayload = payload) + } + } + + private fun applyTabs() { + val tabs = tabsFor(supportsPlatform, shieldedEnabled, hasUsername()) + val state = _uiState.value + if (tabs == state.tabs) { + publishUsername() + return + } + if (state.selectedTab in tabs) { + _uiState.update { it.copy(tabs = tabs) } + publishUsername() + } else { + // The selected balance went away (flag off, username gone): back to Core. + _uiState.update { + it.copy( + tabs = tabs, + selectedTab = ReceiveBalanceTab.CORE, + address = null, + qrPayload = null, + loading = false, + unavailable = false + ) + } + publishUsername() + load(ReceiveBalanceTab.CORE, force = true) + } + } + + private fun sourceFor(tab: ReceiveBalanceTab): ReceiveAddressSource = when (tab) { + ReceiveBalanceTab.CORE -> sources.core + ReceiveBalanceTab.SHIELD -> sources.shielded + ReceiveBalanceTab.PLATFORM -> sources.platform + ReceiveBalanceTab.IDENTITY -> ReceiveAddressSource { identity?.takeIf { it.hasUsername }?.userId } + } + + /** + * Start a read for [tab]. A read already in flight for the same tab is reused unless + * [force]; any other in-flight read is superseded and will not publish. + */ + private fun load(tab: ReceiveBalanceTab, force: Boolean) { + if (!force && loadJob?.isActive == true && loadingTab == tab) return + loadJob?.cancel() + val generation = ++loadGeneration + loadingTab = tab + // Keep what is on screen while revalidating it; a failure below takes it down. + _uiState.update { it.copy(loading = true) } + loadJob = viewModelScope.launch { + val address = try { + sourceFor(tab).address() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("receive address read failed for {}; advertising nothing", tab, e) + null + } + if (generation != loadGeneration) return@launch + _uiState.update { state -> + if (state.selectedTab != tab) { + state + } else { + val payload = address?.let { qrPayloadOrNull(tab, it, state.username) } + val shown = address.takeIf { payload != null } + state.copy( + address = shown, + qrPayload = payload, + loading = false, + unavailable = shown == null + ) + } + } + } + } + + private fun qrPayloadOrNull(tab: ReceiveBalanceTab, address: String, username: String?): String? = + try { + qrPayloadFor(tab, address, username) + } catch (e: IllegalArgumentException) { + // Fail closed: an address the URI builder rejects is not advertised. + log.warn("cannot build the receive QR payload for {}", tab, e) + null + } +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt index fcce73cbb9..632fe88987 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -1463,6 +1463,27 @@ class ShieldedBalanceServiceTest { assertNull(service(source).shieldedReceiveAddress()) } + @Test + fun platformReceiveAddress_isTheSourcesOwnPlatformAddress() = runBlocking { + val source = readySource().apply { platformAddress = { "tdash1qown" } } + assertEquals("tdash1qown", service(source).platformReceiveAddress()) + } + + @Test + fun platformReceiveAddress_nullWhenFlagOffOrNotReady() = runBlocking { + assertNull(service(readySource(), enabled = false).platformReceiveAddress()) + val notBound = FakeSource(hasSupport = true, boundWalletId = { null }) + assertNull(service(notBound).platformReceiveAddress()) + } + + @Test + fun platformReceiveAddress_lookupFailure_isNullNotThrown() = runBlocking { + val source = readySource().apply { + platformAddress = { throw DashSdkError.InternalError("room read failed") } + } + assertNull(service(source).platformReceiveAddress()) + } + // ── Writes: preflights are NotBroadcast without a broadcast attempt ─── @Test diff --git a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt new file mode 100644 index 0000000000..20ec100e60 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt @@ -0,0 +1,338 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import de.schildbach.wallet.data.WalletData +import de.schildbach.wallet.database.entity.BlockchainIdentityConfig +import de.schildbach.wallet.database.entity.BlockchainIdentityData +import de.schildbach.wallet.database.entity.IdentityCreationState +import de.schildbach.wallet.ui.dashpay.PlatformRepo +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import de.schildbach.wallet.ui.payments.ReceiveBalanceTab.CORE +import de.schildbach.wallet.ui.payments.ReceiveBalanceTab.IDENTITY +import de.schildbach.wallet.ui.payments.ReceiveBalanceTab.PLATFORM +import de.schildbach.wallet.ui.payments.ReceiveBalanceTab.SHIELD +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.bitcoinj.core.Context +import org.bitcoinj.params.TestNet3Params +import org.bitcoinj.wallet.Wallet +import org.dash.wallet.common.services.ReceiveAddressUnavailableException +import org.dash.wallet.common.services.analytics.AnalyticsService +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.io.IOException + +@OptIn(ExperimentalCoroutinesApi::class) +class ReceiveViewModelTest { + private companion object { + const val CORE_ADDRESS = "ydW78zVxRgNhANX2qtG4saSCC5ejNQjw2U" + const val SHIELDED_ADDRESS = "tdash1qshieldedaddress" + const val PLATFORM_ADDRESS = "tevo1qplatformaddress" + const val IDENTITY_ID = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" + } + + private val shieldedFlag = MutableStateFlow(false) + private val identity = MutableStateFlow(identityData(hasUsername = false)) + + private var coreAddress: String? = CORE_ADDRESS + private val reads = mutableListOf() + + private val sources = ReceiveAddressSources( + core = ReceiveAddressSource { reads += CORE; coreAddress }, + shielded = ReceiveAddressSource { reads += SHIELD; SHIELDED_ADDRESS }, + platform = ReceiveAddressSource { reads += PLATFORM; PLATFORM_ADDRESS } + ) + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun identityData(hasUsername: Boolean) = BlockchainIdentityData( + creationState = if (hasUsername) IdentityCreationState.DONE else IdentityCreationState.NONE, + creationStateErrorMessage = null, + username = if (hasUsername) "johndoe" else null, + usernameSecondary = null, + userId = if (hasUsername) IDENTITY_ID else null, + restoring = false + ) + + private fun buildViewModel( + supportsPlatform: Boolean = true, + receiveSources: ReceiveAddressSources = sources + ): ReceiveViewModel { + val platformRepo = mockk { + every { observeProfileByUserId(any()) } returns flowOf(null) + } + val identityConfig = mockk { + every { observe() } returns identity + } + val dashPayConfig = mockk { + every { observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) } returns shieldedFlag + } + return ReceiveViewModel( + receiveSources, + platformRepo, + identityConfig, + dashPayConfig, + mockk(relaxed = true), + supportsPlatform + ) + } + + // ── tab list ───────────────────────────────────────────────────────────── + + @Test + fun `tabsFor shows Shield and Platform only with platform support and the flag, Identity only with a username`() { + assertEquals(listOf(CORE), ReceiveViewModel.tabsFor(false, false, false)) + assertEquals(listOf(CORE), ReceiveViewModel.tabsFor(true, false, false)) + assertEquals(listOf(CORE), ReceiveViewModel.tabsFor(false, true, false)) + assertEquals(listOf(CORE, SHIELD, PLATFORM), ReceiveViewModel.tabsFor(true, true, false)) + assertEquals(listOf(CORE, IDENTITY), ReceiveViewModel.tabsFor(false, false, true)) + assertEquals(listOf(CORE, SHIELD, PLATFORM, IDENTITY), ReceiveViewModel.tabsFor(true, true, true)) + } + + @Test + fun `the view model follows the flag and the username`() { + val viewModel = buildViewModel() + assertEquals(listOf(CORE), viewModel.uiState.value.tabs) + + shieldedFlag.value = true + assertEquals(listOf(CORE, SHIELD, PLATFORM), viewModel.uiState.value.tabs) + + identity.value = identityData(hasUsername = true) + assertEquals(listOf(CORE, SHIELD, PLATFORM, IDENTITY), viewModel.uiState.value.tabs) + assertEquals("johndoe", viewModel.uiState.value.username) + } + + @Test + fun `without platform support the flag does not add Shield or Platform`() { + shieldedFlag.value = true + val viewModel = buildViewModel(supportsPlatform = false) + assertEquals(listOf(CORE), viewModel.uiState.value.tabs) + } + + @Test + fun `a failing flag read hides Shield and Platform and keeps retrying`() = runBlocking { + var attempts = 0 + val failingThenTrue = flow { + attempts++ + if (attempts == 1) throw IOException("datastore") + emit(true) + } + val values = ReceiveViewModel.shieldedEnabledFlow(failingThenTrue, retryDelayMs = { 0L }) + .take(2) + .toList() + assertEquals(listOf(false, true), values) + } + + @Test + fun `losing the selected tab falls back to Core and reloads it`() { + shieldedFlag.value = true + val viewModel = buildViewModel() + viewModel.selectTab(SHIELD) + assertEquals(SHIELD, viewModel.uiState.value.selectedTab) + + shieldedFlag.value = false + val state = viewModel.uiState.value + assertEquals(CORE, state.selectedTab) + assertEquals(CORE_ADDRESS, state.address) + } + + // ── switching tabs ─────────────────────────────────────────────────────── + + @Test + fun `switching tabs loads that tab's address with a bare QR payload`() { + shieldedFlag.value = true + identity.value = identityData(hasUsername = true) + val viewModel = buildViewModel() + viewModel.refresh() + assertEquals(CORE_ADDRESS, viewModel.uiState.value.address) + assertTrue(viewModel.uiState.value.qrPayload?.startsWith("dash:$CORE_ADDRESS") == true) + + viewModel.selectTab(SHIELD) + assertEquals(SHIELDED_ADDRESS, viewModel.uiState.value.address) + assertEquals(SHIELDED_ADDRESS, viewModel.uiState.value.qrPayload) + + viewModel.selectTab(PLATFORM) + assertEquals(PLATFORM_ADDRESS, viewModel.uiState.value.address) + assertEquals(PLATFORM_ADDRESS, viewModel.uiState.value.qrPayload) + + viewModel.selectTab(IDENTITY) + assertEquals(IDENTITY_ID, viewModel.uiState.value.address) + assertEquals(IDENTITY_ID, viewModel.uiState.value.qrPayload) + + assertEquals(listOf(CORE, SHIELD, PLATFORM), reads) + } + + @Test + fun `selecting a tab that is not shown does nothing`() { + val viewModel = buildViewModel() + viewModel.selectTab(SHIELD) + assertEquals(CORE, viewModel.uiState.value.selectedTab) + assertFalse(SHIELD in reads) + } + + @Test + fun `a read for a tab the user has left never publishes`() { + shieldedFlag.value = true + val shieldedGate = CompletableDeferred() + val gatedSources = ReceiveAddressSources( + core = ReceiveAddressSource { CORE_ADDRESS }, + shielded = ReceiveAddressSource { shieldedGate.await() }, + platform = ReceiveAddressSource { PLATFORM_ADDRESS } + ) + val viewModel = buildViewModel(receiveSources = gatedSources) + viewModel.selectTab(SHIELD) + viewModel.selectTab(CORE) + assertEquals(CORE_ADDRESS, viewModel.uiState.value.address) + + shieldedGate.complete(SHIELDED_ADDRESS) + assertEquals(CORE, viewModel.uiState.value.selectedTab) + assertEquals(CORE_ADDRESS, viewModel.uiState.value.address) + } + + @Test + fun `a resume during a read in flight does not start a second one`() { + val gate = CompletableDeferred() + var coreReads = 0 + val gatedSources = ReceiveAddressSources( + core = ReceiveAddressSource { coreReads++; gate.await() }, + shielded = ReceiveAddressSource { null }, + platform = ReceiveAddressSource { null } + ) + val viewModel = buildViewModel(receiveSources = gatedSources) + viewModel.refresh() + viewModel.refresh() + assertEquals(1, coreReads) + assertTrue(viewModel.uiState.value.loading) + + gate.complete(CORE_ADDRESS) + assertEquals(CORE_ADDRESS, viewModel.uiState.value.address) + assertFalse(viewModel.uiState.value.loading) + } + + // ── fail closed ────────────────────────────────────────────────────────── + + @Test + fun `an unavailable Core address gives no QR`() { + coreAddress = null + val viewModel = buildViewModel() + viewModel.refresh() + val state = viewModel.uiState.value + assertNull(state.address) + assertNull(state.qrPayload) + assertTrue(state.unavailable) + } + + @Test + fun `a failed revalidation takes down the address that was on show`() { + val viewModel = buildViewModel() + viewModel.refresh() + assertEquals(CORE_ADDRESS, viewModel.uiState.value.address) + + coreAddress = null + viewModel.refresh() + assertNull(viewModel.uiState.value.address) + assertNull(viewModel.uiState.value.qrPayload) + } + + @Test + fun `a source that throws gives no QR`() { + val throwingSources = ReceiveAddressSources( + core = ReceiveAddressSource { throw IllegalStateException("Wallet not yet initialised") }, + shielded = ReceiveAddressSource { null }, + platform = ReceiveAddressSource { null } + ) + val viewModel = buildViewModel(receiveSources = throwingSources) + viewModel.refresh() + assertNull(viewModel.uiState.value.qrPayload) + assertTrue(viewModel.uiState.value.unavailable) + } + + @Test + fun `the Core source returns null when the engine cannot answer, never a dashj address`() = runBlocking { + val dashjWallet = mockk { + every { context } returns Context(TestNet3Params.get()) + } + val walletData = mockk { + every { wallet } returns dashjWallet + every { currentReceiveAddressLive() } throws ReceiveAddressUnavailableException() + } + assertNull(CoreReceiveAddressSource(walletData).address()) + } + + @Test + fun `the Core source returns null before the wallet is loaded`() = runBlocking { + val walletData = mockk { + every { wallet } returns null + } + assertNull(CoreReceiveAddressSource(walletData).address()) + } + + // ── specify amount, username, QR payload ───────────────────────────────── + + @Test + fun `Specify amount is offered only on Core`() { + assertTrue(ReceiveUIState(selectedTab = CORE).showSpecifyAmount) + assertFalse(ReceiveUIState(selectedTab = SHIELD).showSpecifyAmount) + assertFalse(ReceiveUIState(selectedTab = PLATFORM).showSpecifyAmount) + assertFalse(ReceiveUIState(selectedTab = IDENTITY).showSpecifyAmount) + } + + @Test + fun `the username row shows on Core and Identity when there is a username`() { + assertFalse(ReceiveUIState(selectedTab = CORE).showUsername) + assertTrue(ReceiveUIState(selectedTab = CORE, username = "u").showUsername) + assertTrue(ReceiveUIState(selectedTab = IDENTITY, username = "u").showUsername) + assertFalse(ReceiveUIState(selectedTab = SHIELD, username = "u").showUsername) + assertFalse(ReceiveUIState(selectedTab = PLATFORM, username = "u").showUsername) + } + + @Test + fun `the Core QR is a dash URI carrying the username, the others the bare value`() { + assertEquals("dash:$CORE_ADDRESS", ReceiveViewModel.qrPayloadFor(CORE, CORE_ADDRESS, null)) + assertTrue(ReceiveViewModel.qrPayloadFor(CORE, CORE_ADDRESS, "johndoe").contains("johndoe")) + assertEquals(SHIELDED_ADDRESS, ReceiveViewModel.qrPayloadFor(SHIELD, SHIELDED_ADDRESS, "johndoe")) + assertEquals(PLATFORM_ADDRESS, ReceiveViewModel.qrPayloadFor(PLATFORM, PLATFORM_ADDRESS, null)) + assertEquals(IDENTITY_ID, ReceiveViewModel.qrPayloadFor(IDENTITY, IDENTITY_ID, null)) + } +} From f766d814fd0e160429b0b647b2348e43b4c9a86d Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 09:21:09 -0800 Subject: [PATCH 03/13] revert(payments): keep the Receive buttons to the design spec Drop the 8dp side padding and shrink-to-fit text on Share address / Specify amount, and the DashButton options that supported them. The buttons now use the stock TintedGray Medium style. Co-Authored-By: Claude Opus 5.5 --- .../wallet/common/ui/components/DashButton.kt | 46 +------------------ .../wallet/ui/payments/ReceivePage.kt | 6 --- 2 files changed, 2 insertions(+), 50 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt b/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt index 200a2fa1fe..77e02a5227 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/components/DashButton.kt @@ -19,15 +19,9 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector @@ -51,11 +45,6 @@ fun DashButton( stretch: Boolean = true, isEnabled: Boolean = true, isLoading: Boolean = false, - // Overrides [size]'s side padding when set; null keeps the size's own (every existing use). - horizontalPadding: Dp? = null, - // Keep the label on one line and shrink its font until it fits instead of ellipsizing it, - // for buttons that share a narrow row (large font scales). Off by default. - shrinkTextToFit: Boolean = false, onClick: () -> Unit ) { val colors = LocalDashColors.current @@ -120,10 +109,7 @@ fun DashButton( contentColor = contentColor, disabledContainerColor = Color.Transparent ), - contentPadding = PaddingValues( - horizontal = horizontalPadding ?: size.paddingHorizontal, - vertical = size.paddingVertical - ), + contentPadding = PaddingValues(horizontal = size.paddingHorizontal, vertical = size.paddingVertical), elevation = null ) { if (leadingIcon != null) { @@ -145,9 +131,7 @@ fun DashButton( ) Spacer(modifier = Modifier.width(size.iconSpacing)) } - if (text != null && shrinkTextToFit) { - ShrinkToFitText(text, size, contentColor) - } else if (text != null) { + if (text != null) { Text( text, fontSize = size.fontSize, @@ -171,32 +155,6 @@ fun DashButton( } } -/** One-line label whose font steps down (to at most half of [size]'s) until it fits. */ -@Composable -private fun ShrinkToFitText(text: String, size: Size, color: Color) { - var scale by remember(text, size) { mutableFloatStateOf(1f) } - var fits by remember(text, size) { mutableStateOf(false) } - Text( - text, - fontSize = size.fontSize * scale, - lineHeight = size.lineSize * scale, - style = OverlineSemibold, - color = color, - maxLines = 1, - softWrap = false, - overflow = TextOverflow.Clip, - onTextLayout = { result -> - if (result.hasVisualOverflow && scale > 0.5f) { - scale -= 0.05f - } else { - fits = true - } - }, - // Draw only the size that fits, so the steps down never flash on screen. - modifier = Modifier.drawWithContent { if (fits) drawContent() } - ) -} - enum class Style { Plain, Outlined, diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index e46b2efcce..34dd7731f6 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -149,9 +149,6 @@ fun ReceivePage( text = stringResource(R.string.receive_share_address), style = Style.TintedGray, size = Size.Medium, - // Two buttons share the row: Figma 160dp each; keep the full label at large font scales. - horizontalPadding = 8.dp, - shrinkTextToFit = true, isEnabled = address != null, onClick = { address?.let(onShareAddress) } ) @@ -161,9 +158,6 @@ fun ReceivePage( text = stringResource(R.string.receive_specify_amount), style = Style.TintedGray, size = Size.Medium, - // Two buttons share the row: Figma 160dp each; keep the full label at large font scales. - horizontalPadding = 8.dp, - shrinkTextToFit = true, onClick = onSpecifyAmount ) } From b2b1be7735acee94ba6d66ec96d768c88ac14894 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 09:43:46 -0800 Subject: [PATCH 04/13] feat(payments): offer Specify amount on every Advanced Receive tab Shield, Platform and Identity now show Specify amount next to Share address. It opens the existing amount screen; the result is the existing Receive details dialog with a QR of dash:
?amount=, the tab's address label and no username row. Core is unchanged. The non-Core request is built by ReceiveViewModel.amountRequestPayload (same amount formatting as PaymentURI) and shown through a new ReceiveInfoView.setPaymentRequest path, so bech32 addresses and identity IDs never reach PaymentURI / AddressNetwork. receiveFragment gains two optional args (request_address, request_address_label) that default to null; basic mode and Quick Receive never pass them. Co-Authored-By: Claude Opus 5.5 --- .../common/ui/receive/ReceiveInfoView.kt | 47 ++++++++- wallet/res/navigation/nav_home.xml | 19 +++- wallet/res/navigation/nav_quick_receive.xml | 19 +++- .../ui/payments/AdvancedReceiveFragment.kt | 19 +++- .../ui/payments/ReceiveDetailsDialog.kt | 61 ++++++++++-- .../wallet/ui/payments/ReceiveFragment.kt | 16 ++++ .../wallet/ui/payments/ReceivePage.kt | 25 ++--- .../wallet/ui/payments/ReceiveViewModel.kt | 23 ++++- .../ui/payments/ReceiveViewModelTest.kt | 95 ++++++++++++++++++- 9 files changed, 290 insertions(+), 34 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt b/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt index 307520836a..516376a47a 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt @@ -50,6 +50,9 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout private var paymentRequestUri: String = "" private var username: String? = null + /** Set by [setPaymentRequest]: the QR content as given, never built by [PaymentURI]. */ + private var presetPaymentRequest: String? = null + init { binding = ReceiveInfoViewBinding.inflate(LayoutInflater.from(context), this) val attrsArray = context.obtainStyledAttributes(attrs, R.styleable.ReceiveInfoView) @@ -92,6 +95,9 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout } fun setInfo(address: String, amount: Dash?) { + if (presetPaymentRequest != null) { + leavePresetPaymentRequest() + } if (this.address != address) { this.address = address this.amount = amount @@ -109,6 +115,11 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout * already have been paid on it. */ fun clearInfo() { + if (presetPaymentRequest != null) { + leavePresetPaymentRequest() + refresh() + return + } if (address != null || amount != null) { address = null amount = null @@ -116,6 +127,33 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout } } + /** + * Show [address] under [addressLabel] with a QR of [paymentRequest] exactly as given. For + * addresses [PaymentURI] cannot carry (bech32 shielded or Platform addresses, identity IDs): + * the caller builds the request. Copy copies [paymentRequest]; Share shares [address], as + * [setInfo] does. [setInfo] or [clearInfo] go back to the [PaymentURI] request. + */ + fun setPaymentRequest(addressLabel: String, address: String, paymentRequest: String) { + presetPaymentRequest = paymentRequest + this.address = address + this.amount = null + binding.addressLabel.text = addressLabel + refresh() + } + + /** The [setPaymentRequest] QR: shown as given, kept out of [refreshQr]'s [PaymentURI]. */ + private fun showPresetQr(paymentRequest: String) { + paymentRequestUri = paymentRequest + binding.qrPreview.setImageDrawable(Qr.themeAwareDrawable(paymentRequest, resources)) + } + + private fun leavePresetPaymentRequest() { + presetPaymentRequest = null + address = null + amount = null + binding.addressLabel.setText(R.string.dash_address) + } + fun setProfile(username: String?, displayName: String?, avatar: String?, avatarHash: ByteArray?) { this.username = username @@ -160,7 +198,12 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout binding.addressPreviewPane.isVisible = false } - refreshQr() + val presetPaymentRequest = this.presetPaymentRequest + if (presetPaymentRequest != null) { + showPresetQr(presetPaymentRequest) + } else { + refreshQr() + } } private fun refreshQr() { @@ -186,7 +229,7 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout private fun handleCopyAddress(address: String) { val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - if (amount != null && paymentRequestUri.isNotEmpty()) { + if ((amount != null || presetPaymentRequest != null) && paymentRequestUri.isNotEmpty()) { clipboardManager.setPrimaryClip(ClipData.newPlainText("Dash payment request", paymentRequestUri)) } else { clipboardManager.setPrimaryClip(ClipData.newPlainText("Dash address", address)) diff --git a/wallet/res/navigation/nav_home.xml b/wallet/res/navigation/nav_home.xml index f7df1022b9..131d82cad5 100644 --- a/wallet/res/navigation/nav_home.xml +++ b/wallet/res/navigation/nav_home.xml @@ -294,7 +294,24 @@ android:id="@+id/receiveFragment" android:name="de.schildbach.wallet.ui.payments.ReceiveFragment" android:label="Receive" - tools:layout="@layout/fragment_receive"/> + tools:layout="@layout/fragment_receive"> + + + + + + + tools:layout="@layout/fragment_receive"> + + + + + + \ No newline at end of file diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt index 61c13eb36d..f1c732d4ce 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt @@ -99,11 +99,26 @@ class AdvancedReceiveFragment : Fragment() { } } - private fun specifyAmount() { + /** + * Core opens the amount screen as it always has: [ReceiveFragment] reads a fresh address + * once the amount is entered. The other tabs hand it the [address] on show, and their + * request is a bare `dash:` URI ([ReceiveViewModel.amountRequestPayload]). + */ + private fun specifyAmount(tab: ReceiveBalanceTab, address: String?) { val navController = findNavController() // A second tap while the transition runs would find the action missing. if (navController.currentDestination?.id != R.id.advancedPaymentsFragment) return + val directions = if (tab == ReceiveBalanceTab.CORE) { + PaymentsFragmentDirections.paymentsToReceive() + } else { + // The button is disabled without an address; nothing to request otherwise. + if (address == null) return + PaymentsFragmentDirections.paymentsToReceive( + requestAddress = address, + requestAddressLabel = addressLabelFor(tab) + ) + } viewModel.logEvent(AnalyticsConstants.SendReceive.SPECIFY_AMOUNT) - navController.navigate(PaymentsFragmentDirections.paymentsToReceive()) + navController.navigate(directions) } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt index 68d92c4bae..d9a8e641ad 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt @@ -50,6 +50,8 @@ class ReceiveDetailsDialog : OffsetDialogFragment(R.layout.dialog_receive_detail private const val ARG_DASH_AMOUNT = "arg_dash_amount" private const val ARG_FIAT_AMOUNT = "arg_fiat_amount" private const val ARG_ADDRESS = "arg_address" + private const val ARG_REQUEST_ADDRESS = "arg_request_address" + private const val ARG_REQUEST_ADDRESS_LABEL = "arg_request_address_label" @JvmStatic fun createDialog(address: Address, dashAmount: Coin, fiatAmount: Fiat?): OffsetDialogFragment { @@ -61,6 +63,28 @@ class ReceiveDetailsDialog : OffsetDialogFragment(R.layout.dialog_receive_detail dialog.arguments = bundle return dialog } + + /** + * The same dialog for an address [PaymentURI][org.dash.wallet.common.payments.parsers.PaymentURI] + * cannot carry (Advanced Receive's shielded and Platform addresses and identity ID): + * the QR holds [ReceiveViewModel.amountRequestPayload] and the address shows under + * [addressLabel]. There is no username row. + */ + fun createAmountRequestDialog( + addressLabel: String, + address: String, + dashAmount: Coin, + fiatAmount: Fiat? + ): OffsetDialogFragment { + val dialog = ReceiveDetailsDialog() + dialog.arguments = Bundle().apply { + putString(ARG_REQUEST_ADDRESS, address) + putString(ARG_REQUEST_ADDRESS_LABEL, addressLabel) + putSerializable(ARG_DASH_AMOUNT, dashAmount) + putSerializable(ARG_FIAT_AMOUNT, fiatAmount) + } + return dialog + } } override val backgroundStyle = R.style.PrimaryBackground @@ -72,23 +96,42 @@ class ReceiveDetailsDialog : OffsetDialogFragment(R.layout.dialog_receive_detail super.onViewCreated(view, savedInstanceState) requireArguments().apply { + val requestAddress = getString(ARG_REQUEST_ADDRESS) + if (requestAddress != null) { + showAmountRequest(this, requestAddress) + return + } val address = getSerializable(ARG_ADDRESS) as Address val dashAmount = getSerializable(ARG_DASH_AMOUNT) as Coin val fiatAmount = getSerializable(ARG_FIAT_AMOUNT) as Fiat? binding.receiveInfo.setInfo(address.toBase58(), dashAmount?.let { org.dash.wallet.common.money.Dash(it.value) }) - binding.amount.inputValue.text = MonetaryFormat.BTC - .repeatOptionalDecimals(1, Configuration.PREFS_DEFAULT_BTC_PRECISION) - .minDecimals(0).noCode().format(dashAmount) - - if (fiatAmount != null) { - binding.amount.fiatValue.text = fiatAmount.toFormattedString() - } else { - binding.amount.fiatValue.isVisible = false - } + showAmount(dashAmount, fiatAmount) viewModel.dashPayProfile.observe(viewLifecycleOwner) { binding.receiveInfo.setProfile(it?.username, it?.displayName, it?.avatarUrl, it?.avatarHash) } } } + + /** [createAmountRequestDialog]: never through PaymentURI, and no DashPay profile. */ + private fun showAmountRequest(args: Bundle, address: String) { + val label = args.getString(ARG_REQUEST_ADDRESS_LABEL).orEmpty() + val dashAmount = checkNotNull(args.getSerializable(ARG_DASH_AMOUNT) as? Coin) { "no amount" } + val fiatAmount = args.getSerializable(ARG_FIAT_AMOUNT) as? Fiat + val payload = ReceiveViewModel.amountRequestPayload(address, dashAmount.toNeutralCoin()) + binding.receiveInfo.setPaymentRequest(label, address, payload) + showAmount(dashAmount, fiatAmount) + } + + private fun showAmount(dashAmount: Coin, fiatAmount: Fiat?) { + binding.amount.inputValue.text = MonetaryFormat.BTC + .repeatOptionalDecimals(1, Configuration.PREFS_DEFAULT_BTC_PRECISION) + .minDecimals(0).noCode().format(dashAmount) + + if (fiatAmount != null) { + binding.amount.fiatValue.text = fiatAmount.toFormattedString() + } else { + binding.amount.fiatValue.isVisible = false + } + } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt index 9981705d82..4db630a45d 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt @@ -81,9 +81,25 @@ class ReceiveFragment : Fragment(R.layout.fragment_receive) { } enterAmountViewModel.setMaxAmount(org.dash.wallet.common.money.Coin.ZERO) enterAmountViewModel.setMinAmount(org.dash.wallet.common.money.Coin.ZERO) + // Set only by Advanced Receive's Shield/Platform/Identity tabs; every other caller + // leaves it null and gets a fresh Core address below. + val args = ReceiveFragmentArgs.fromBundle(arguments ?: Bundle()) + val requestAddress = args.requestAddress enterAmountViewModel.onContinueEvent.observe(viewLifecycleOwner) { val dashAmount = it.first val fiatAmount = it.second + if (requestAddress != null) { + // Both arguments are set together; the generic label covers a caller that did not. + val label = args.requestAddressLabel.takeIf { label -> label != 0 } + ?: org.dash.wallet.common.R.string.dash_address + ReceiveDetailsDialog.createAmountRequestDialog( + getString(label), + requestAddress, + dashAmount.toDashjCoin(), + fiatAmount?.toDashjFiat() + ).show(requireActivity()) + return@observe + } // OFF THE MAIN THREAD: this observer runs on Main, and dashj's // freshReceiveAddress() forces a synchronous full-wallet save // (measured 1.2s at 215 friend chains) — see freshReceiveAddressOffMain. diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index 34dd7731f6..72e0faddbd 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -77,7 +77,7 @@ fun ReceivePage( onCopyUsername: (String) -> Unit, onCopyAddress: (String) -> Unit, onShareAddress: (String) -> Unit, - onSpecifyAmount: () -> Unit, + onSpecifyAmount: (tab: ReceiveBalanceTab, address: String?) -> Unit, modifier: Modifier = Modifier ) { val colors = LocalDashColors.current @@ -152,21 +152,22 @@ fun ReceivePage( isEnabled = address != null, onClick = { address?.let(onShareAddress) } ) - if (uiState.showSpecifyAmount) { - DashButton( - modifier = Modifier.weight(1f), - text = stringResource(R.string.receive_specify_amount), - style = Style.TintedGray, - size = Size.Medium, - onClick = onSpecifyAmount - ) - } + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.receive_specify_amount), + style = Style.TintedGray, + size = Size.Medium, + isEnabled = uiState.specifyAmountEnabled, + // The tab and address on show, so the request is for what the user saw. + onClick = { onSpecifyAmount(uiState.selectedTab, address) } + ) } } } } -private fun addressLabelFor(tab: ReceiveBalanceTab): Int = when (tab) { +/** The label of [tab]'s address or ID, here and in the Specify amount result. */ +internal fun addressLabelFor(tab: ReceiveBalanceTab): Int = when (tab) { ReceiveBalanceTab.CORE -> R.string.receive_core_address_label ReceiveBalanceTab.SHIELD -> R.string.receive_shielded_address_label ReceiveBalanceTab.PLATFORM -> R.string.receive_platform_address_label @@ -318,7 +319,7 @@ private fun ReceivePagePreview() { onCopyUsername = {}, onCopyAddress = {}, onShareAddress = {}, - onSpecifyAmount = {} + onSpecifyAmount = { _, _ -> } ) } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt index d1aeb525d5..bda51b9aa3 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -43,6 +43,7 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import org.dash.wallet.common.money.Coin import org.dash.wallet.common.payments.parsers.AddressNetwork import org.dash.wallet.common.payments.parsers.PaymentURI import org.dash.wallet.common.services.analytics.AnalyticsService @@ -78,8 +79,13 @@ data class ReceiveUIState( val unavailable: Boolean = false, val username: String? = null ) { - /** Specify amount builds a `dash:` payment request, so only Core offers it. */ - val showSpecifyAmount: Boolean get() = selectedTab == ReceiveBalanceTab.CORE + /** + * Specify amount is on every tab. Core reads a fresh address itself once the amount is + * entered (as it always has), so it is always enabled; the other tabs put [address] in + * the request, so they need one on show. + */ + val specifyAmountEnabled: Boolean + get() = selectedTab == ReceiveBalanceTab.CORE || address != null /** A username identifies a DashPay user, who is paid on Core; the Identity tab is theirs too. */ val showUsername: Boolean @@ -152,6 +158,19 @@ class ReceiveViewModel internal constructor( else -> address } + /** + * The Specify amount request for a tab other than Core: exactly + * `dash:
?amount=`, the amount in DASH formatted as Core's `dash:` URI + * formats it ([Coin.toPlainString], as [PaymentURI.convertToPaymentURI] does). Built + * by hand because [PaymentURI] and [AddressNetwork] accept only base58 L1 addresses, + * not bech32 shielded/Platform addresses or identity IDs. + */ + fun amountRequestPayload(address: String, amount: Coin): String { + require(address.isNotEmpty()) { "no address for the payment request" } + require(amount.signum() >= 0) { "the requested amount must not be negative" } + return "${AddressNetwork.DASH_SCHEME}:$address?amount=${amount.toPlainString()}" + } + /** * The shielded flag as a never-failing flow: a failed read hides the * Shield and Platform tabs and is retried, like the Internal tab diff --git a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt index 20ec100e60..74bf818bdb 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt @@ -44,6 +44,9 @@ import kotlinx.coroutines.test.setMain import org.bitcoinj.core.Context import org.bitcoinj.params.TestNet3Params import org.bitcoinj.wallet.Wallet +import org.dash.wallet.common.money.Coin +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.PaymentURI import org.dash.wallet.common.services.ReceiveAddressUnavailableException import org.dash.wallet.common.services.analytics.AnalyticsService import org.junit.After @@ -311,11 +314,93 @@ class ReceiveViewModelTest { // ── specify amount, username, QR payload ───────────────────────────────── @Test - fun `Specify amount is offered only on Core`() { - assertTrue(ReceiveUIState(selectedTab = CORE).showSpecifyAmount) - assertFalse(ReceiveUIState(selectedTab = SHIELD).showSpecifyAmount) - assertFalse(ReceiveUIState(selectedTab = PLATFORM).showSpecifyAmount) - assertFalse(ReceiveUIState(selectedTab = IDENTITY).showSpecifyAmount) + fun `Specify amount is enabled on every tab with an address, and always on Core`() { + // Core reads its own fresh address after the amount is entered, as it always has. + assertTrue(ReceiveUIState(selectedTab = CORE).specifyAmountEnabled) + assertTrue(ReceiveUIState(selectedTab = CORE, address = CORE_ADDRESS).specifyAmountEnabled) + assertTrue(ReceiveUIState(selectedTab = SHIELD, address = SHIELDED_ADDRESS).specifyAmountEnabled) + assertTrue(ReceiveUIState(selectedTab = PLATFORM, address = PLATFORM_ADDRESS).specifyAmountEnabled) + assertTrue(ReceiveUIState(selectedTab = IDENTITY, address = IDENTITY_ID).specifyAmountEnabled) + // No address on show: nothing to put in the request. + assertFalse(ReceiveUIState(selectedTab = SHIELD).specifyAmountEnabled) + assertFalse(ReceiveUIState(selectedTab = PLATFORM, unavailable = true).specifyAmountEnabled) + assertFalse(ReceiveUIState(selectedTab = IDENTITY, loading = true).specifyAmountEnabled) + } + + @Test + fun `the view model enables Specify amount on each tab once its address is read`() { + shieldedFlag.value = true + identity.value = identityData(hasUsername = true) + val viewModel = buildViewModel() + viewModel.refresh() + assertTrue(viewModel.uiState.value.specifyAmountEnabled) + for (tab in listOf(SHIELD, PLATFORM, IDENTITY)) { + viewModel.selectTab(tab) + assertEquals(tab, viewModel.uiState.value.selectedTab) + assertTrue("Specify amount on $tab", viewModel.uiState.value.specifyAmountEnabled) + } + } + + @Test + fun `a tab whose address read fails disables Specify amount`() { + shieldedFlag.value = true + val failing = ReceiveAddressSources( + core = sources.core, + shielded = ReceiveAddressSource { null }, + platform = sources.platform + ) + val viewModel = buildViewModel(receiveSources = failing) + viewModel.selectTab(SHIELD) + assertTrue(viewModel.uiState.value.unavailable) + assertFalse(viewModel.uiState.value.specifyAmountEnabled) + } + + @Test + fun `the amount request is exactly a dash URI with the amount in DASH`() { + val shielded = "tdash1zq2ksj5u7v5f0pn6lyl4m5k6c3l8wl3x9g0e7v" + assertEquals( + "dash:$shielded?amount=0.5", + ReceiveViewModel.amountRequestPayload(shielded, Coin.valueOf(50_000_000L)) + ) + assertEquals( + "dash:$PLATFORM_ADDRESS?amount=1", + ReceiveViewModel.amountRequestPayload(PLATFORM_ADDRESS, Coin.COIN) + ) + assertEquals( + "dash:$IDENTITY_ID?amount=12.3456789", + ReceiveViewModel.amountRequestPayload(IDENTITY_ID, Coin.valueOf(1_234_567_890L)) + ) + // Small amounts: the smallest unit, no exponent, no trailing zeros. + assertEquals( + "dash:$SHIELDED_ADDRESS?amount=0.00000001", + ReceiveViewModel.amountRequestPayload(SHIELDED_ADDRESS, Coin.SATOSHI) + ) + assertEquals( + "dash:$SHIELDED_ADDRESS?amount=0.0001", + ReceiveViewModel.amountRequestPayload(SHIELDED_ADDRESS, Coin.valueOf(10_000L)) + ) + } + + @Test + fun `the amount request formats the amount as Core's dash URI does`() { + for (duffs in listOf(1L, 10_000L, 50_000_000L, 100_000_000L, 1_234_567_890L, 2_100_000_000_000L)) { + val amount = Coin.valueOf(duffs) + val core = PaymentURI.convertToPaymentURI( + AddressNetwork.DASH_TESTNET, + CORE_ADDRESS, + amount, + null, + null, + null + ) + val request = ReceiveViewModel.amountRequestPayload(CORE_ADDRESS, amount) + assertEquals(core, request) + } + } + + @Test(expected = IllegalArgumentException::class) + fun `the amount request rejects a negative amount`() { + ReceiveViewModel.amountRequestPayload(SHIELDED_ADDRESS, Coin.valueOf(-1L)) } @Test From a1b51965646e3427e75fd8d016b211770ddc8585 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 10:28:30 -0800 Subject: [PATCH 05/13] refactor(payments): simplify the Advanced payments and Receive code No behaviour change. - PaymentsPayFragment checks for the payments_to_addressInput action instead of matching host class names. - PaymentsRoute drops its unused activeTab and becomes a two-value enum. - One shieldedEnabledFlow (with shieldedReadRetryDelayMs) feeds both the screen's tabs and the Receive balance tabs. - ReceiveUIState derives qrPayload and unavailable instead of storing them. - AdvancedPaymentsFragment keeps one selected-tab state; option lists are remembered; the Receive QR is encoded off the main thread. - ReceiveDetailsDialog branches early; SegmentedPicker shares its thumb. Co-Authored-By: Claude Opus 5.5 --- .../ui/segmented_picker/SegmentedPicker.kt | 25 ++-- .../wallet/ui/main/WalletFragment.kt | 2 +- .../ui/payments/AdvancedPaymentsFragment.kt | 109 ++++++++-------- .../ui/payments/AdvancedPaymentsViewModel.kt | 34 +++-- .../wallet/ui/payments/PaymentsPayFragment.kt | 12 +- .../wallet/ui/payments/PaymentsRoute.kt | 37 ++---- .../ui/payments/ReceiveDetailsDialog.kt | 14 ++- .../wallet/ui/payments/ReceivePage.kt | 26 +++- .../wallet/ui/payments/ReceiveViewModel.kt | 118 +++++++----------- .../wallet/ui/payments/PaymentsRouteTest.kt | 22 ---- .../ui/payments/ReceiveViewModelTest.kt | 33 ++++- 11 files changed, 209 insertions(+), 223 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index 54121a83c6..2dde2a17ca 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -195,10 +195,9 @@ fun SegmentedPicker( // Draw the animated selection indicator if (containerSize > 0 && showSelection) { - Surface( - shape = RoundedCornerShape((style.thumbCornerRadius ?: (style.cornerRadius - 2)).dp), + SelectionThumb( + style = style, color = thumbColor, - shadowElevation = style.shadowElevation.dp, modifier = Modifier .then( if (isHorizontal) { @@ -213,7 +212,7 @@ fun SegmentedPicker( .offset(y = animatedPosition) } ) - ) { } + ) } // Draw the options @@ -318,15 +317,14 @@ private fun FitContentSegmentedPicker( ) { Box(modifier = Modifier.fillMaxHeight()) { if (showSelection && selectedBounds != null) { - Surface( - shape = RoundedCornerShape((style.thumbCornerRadius ?: (style.cornerRadius - 2)).dp), + SelectionThumb( + style = style, color = thumbColor, - shadowElevation = style.shadowElevation.dp, modifier = Modifier .offset(x = thumbOffset) .width(thumbWidth) .fillMaxHeight() - ) { } + ) } Row(modifier = Modifier.fillMaxHeight()) { options.forEachIndexed { index, option -> @@ -357,6 +355,17 @@ private fun FitContentSegmentedPicker( } } +/** The selected option's background; [modifier] sizes and places it. */ +@Composable +private fun SelectionThumb(style: SegmentedPickerStyle, color: Color, modifier: Modifier) { + Surface( + shape = RoundedCornerShape((style.thumbCornerRadius ?: (style.cornerRadius - 2)).dp), + color = color, + shadowElevation = style.shadowElevation.dp, + modifier = modifier + ) { } +} + @Composable private fun OptionContent( option: SegmentedOption, diff --git a/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt b/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt index b988ff4a63..f32bcba8a9 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt @@ -391,7 +391,7 @@ class WalletFragment : Fragment(R.layout.home_content) { /** Opens the payments screen the Advanced mode setting picks, on [activeTab]. */ private fun navigateToPayments(activeTab: Int) { - val route = paymentsRoute(viewModel.advancedMode.value, activeTab) + val route = paymentsRoute(viewModel.advancedMode.value) findNavController().navigate( route.destinationId, bundleOf(PaymentsFragment.ARG_ACTIVE_TAB to activeTab), diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt index 77448a0cdb..137a32eae0 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -22,14 +22,13 @@ import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.VisibleForTesting -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ViewCompositionStrategy @@ -42,6 +41,7 @@ import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.viewpager2.adapter.FragmentStateAdapter @@ -71,18 +71,12 @@ import org.dash.wallet.common.ui.viewBinding * navigation (`ShowNavBar` on the destination), over the payments pages. * * Receive is [AdvancedReceiveFragment] (the Compose [ReceivePage]); Internal and Send - * are the same child pages as [PaymentsFragment]'s. + * are the same child pages as [PaymentsFragment]'s. The enter/exit transitions are on + * the NavOptions (see [paymentsRoute]). There is no close control: like the other + * bottom-nav screens it is left through the bottom navigation or Back. * - * All navigation goes through the NavController; the tab set is (re)applied on the - * view's lifecycle from [AdvancedPaymentsViewModel], not once in [onViewCreated]; the - * screen pads itself for the system bars and the IME and never touches status-bar - * colours; and the enter/exit transitions are on the NavOptions (see [paymentsRoute]), - * not set here. There is no close control: like the other bottom-nav screens it is - * left through the bottom navigation or Back. - * - * The pages are hosted by ViewPager2 like [PaymentsFragment]'s: ViewPager2 keeps an - * offscreen page at STARTED and lifts only the selected one to RESUMED, which is when - * [AdvancedReceiveFragment] (re)reads its address. + * ViewPager2 keeps an offscreen page at STARTED and lifts only the selected one to + * RESUMED, which is when [AdvancedReceiveFragment] (re)reads its address. */ @AndroidEntryPoint class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { @@ -101,11 +95,11 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { private val binding by viewBinding(FragmentAdvancedPaymentsBinding::bind) private val viewModel by viewModels() - private var tabIds by mutableStateOf>(emptyList()) - private var selectedPosition by mutableIntStateOf(0) - - /** The logical tab the user is on; kept across view recreation and tab-set changes. */ - private var selectedTabId: Int? = null + /** + * The logical tab the user is on, and the only selection state: the picker and the pager + * positions follow from it ([positionOf]). Kept across view recreation and tab-set changes. + */ + private var selectedTabId by mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -147,7 +141,6 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { binding.pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { val tabId = adapter.tabIds.getOrNull(position) ?: return - selectedPosition = position selectedTabId = tabId if (arguments?.containsKey(ARG_ACTIVE_TAB) != true) { @@ -179,8 +172,6 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { val wanted = selectedTabId ?: initialTabId() val position = positionOf(newTabIds, wanted) adapter.submit(newTabIds) - tabIds = newTabIds - selectedPosition = position selectedTabId = newTabIds[position] binding.pager.setCurrentItem(position, false) } @@ -196,48 +187,46 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { @Composable private fun Header() { val colors = LocalDashColors.current - Column(modifier = Modifier.fillMaxWidth()) { - val ids = tabIds - if (ids.isNotEmpty()) { - val options = ids.map { tabId -> - when (tabId) { - ACTIVE_TAB_RECEIVE -> SegmentedOption( - stringResource(R.string.payments_tab_receive_label), - R.drawable.ic_arrow_down - ) - ACTIVE_TAB_INTERNAL -> SegmentedOption( - stringResource(R.string.shielded_tab_internal), - R.drawable.ic_arrows_internal - ) - else -> SegmentedOption( - stringResource(R.string.payments_tab_pay_label), - R.drawable.ic_arrow_up - ) - } - } - // Figma 7062:49306 (20dp margins, 7062:49303): 70dp, 20dp corners, 4dp inset, 16dp thumb corners, - // icon above the title, no dividers, gray300 @ 20% track. - SegmentedPicker( - options = options, - modifier = Modifier - .padding(20.dp) - .fillMaxWidth() - .height(70.dp), - selectedIndex = selectedPosition, - style = SegmentedPickerStyle( - backgroundColor = colors.gray300.copy(alpha = 0.2f), - cornerRadius = 20f, - containerPadding = 4f, - thumbCornerRadius = 16f, - showDividers = false, - iconAboveTitle = true - ) - ) { _, index -> - selectedPosition = index - binding.pager.currentItem = index + val ids = viewModel.uiState.collectAsStateWithLifecycle().value.tabIds + // Null until showTabs has picked a tab for this tab set. + val selected = selectedTabId + if (ids.isNullOrEmpty() || selected == null) return + + val receiveLabel = stringResource(R.string.payments_tab_receive_label) + val internalLabel = stringResource(R.string.shielded_tab_internal) + val payLabel = stringResource(R.string.payments_tab_pay_label) + val options = remember(ids, receiveLabel, internalLabel, payLabel) { + ids.map { tabId -> + when (tabId) { + ACTIVE_TAB_RECEIVE -> SegmentedOption(receiveLabel, R.drawable.ic_arrow_down) + ACTIVE_TAB_INTERNAL -> SegmentedOption(internalLabel, R.drawable.ic_arrows_internal) + else -> SegmentedOption(payLabel, R.drawable.ic_arrow_up) } } } + // Figma 7062:49306 (20dp margins, 7062:49303): 70dp, 20dp corners, 4dp inset, 16dp thumb corners, + // icon above the title, no dividers, gray300 @ 20% track. + SegmentedPicker( + options = options, + modifier = Modifier + .padding(20.dp) + .fillMaxWidth() + .height(70.dp), + selectedIndex = positionOf(ids, selected), + style = SegmentedPickerStyle( + backgroundColor = colors.gray300.copy(alpha = 0.2f), + cornerRadius = 20f, + containerPadding = 4f, + thumbCornerRadius = 16f, + showDividers = false, + iconAboveTitle = true + ) + ) { _, index -> + val tabId = ids.getOrNull(index) ?: return@SegmentedPicker + selectedTabId = tabId + val pagerTabIds = (binding.pager.adapter as? TabsAdapter)?.tabIds.orEmpty() + binding.pager.currentItem = positionOf(pagerTabIds, tabId) + } } /** diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt index 2d73125485..d11c074d65 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt @@ -21,6 +21,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.schildbach.wallet.Constants +import org.dash.wallet.common.util.readRetryDelayMs import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow @@ -68,22 +69,35 @@ class AdvancedPaymentsViewModel @Inject constructor( } /** - * The tab set for the Advanced payments screen. Same gating as [PaymentsFragment]: the - * "Internal" tab needs `SUPPORTS_PLATFORM` and `USE_KOTLIN_SDK_SHIELDED`. A failed read - * hides it (as [DashPayConfig.get] reading absent does for [PaymentsFragment]) and keeps - * retrying, so the flow never completes on an error. + * The shielded flag as a never-failing flow: a failed read counts as off (as + * [DashPayConfig.get] reading absent does for [PaymentsFragment]), is reported to + * [onError] and is retried, so the flow never completes on an error. Shared by the + * Advanced payments tabs ([advancedPaymentsTabsFlow]) and the Receive balance tabs. */ -internal fun advancedPaymentsTabsFlow( +internal fun shieldedEnabledFlow( shieldedFlag: Flow, - supportsPlatform: Boolean, onError: (Throwable, Long) -> Unit = { _, _ -> }, - retryDelayMs: (Long) -> Long = { attempt -> (attempt.coerceIn(0L, 11L) + 1) * 5_000L } -): Flow> = shieldedFlag - .map { PaymentsFragment.tabIdsFor(supportsPlatform && it == true) } + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +): Flow = shieldedFlag + .map { it == true } .retryWhen { e, attempt -> onError(e, attempt) - emit(PaymentsFragment.tabIdsFor(false)) + emit(false) delay(retryDelayMs(attempt)) true } .distinctUntilChanged() + +/** + * The tab set for the Advanced payments screen. Same gating as [PaymentsFragment]: the + * "Internal" tab needs `SUPPORTS_PLATFORM` and `USE_KOTLIN_SDK_SHIELDED`; a failed read + * hides it (see [shieldedEnabledFlow]). + */ +internal fun advancedPaymentsTabsFlow( + shieldedFlag: Flow, + supportsPlatform: Boolean, + onError: (Throwable, Long) -> Unit = { _, _ -> }, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +): Flow> = shieldedEnabledFlow(shieldedFlag, onError, retryDelayMs) + .map { PaymentsFragment.tabIdsFor(supportsPlatform && it) } + .distinctUntilChanged() diff --git a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt index 5dbdc7d4a2..609fe08d4c 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt @@ -25,7 +25,6 @@ import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope -import androidx.navigation.fragment.FragmentNavigator import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView @@ -108,13 +107,12 @@ class PaymentsPayFragment : Fragment(R.layout.fragment_payments_pay), OnContactI binding.sendBtn.setOnClickListener { analytics.logEvent(AnalyticsConstants.SendReceive.SEND_TO_ADDRESS, mapOf()) - val destination = findNavController().currentDestination as? FragmentNavigator.Destination + val navController = findNavController() - // Either payments screen hosts this page; both declare payments_to_addressInput. - if (destination?.className == PaymentsFragment::class.java.name || - destination?.className == AdvancedPaymentsFragment::class.java.name - ) { - findNavController().navigate(PaymentsFragmentDirections.paymentsToAddressInput()) + // Only from a host that declares the action (either payments screen), so a + // second tap after navigating away does nothing. + if (navController.currentDestination?.getAction(R.id.payments_to_addressInput) != null) { + navController.navigate(PaymentsFragmentDirections.paymentsToAddressInput()) } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt index 86671ea6b2..638dd45d75 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt @@ -24,23 +24,18 @@ import de.schildbach.wallet_test.R /** * Where a "payments" entry point (the bottom-nav payments item, the Home Send - * and Receive shortcuts) goes. - * - * @property destinationId the nav destination: [R.id.advancedPaymentsFragment] - * in Advanced mode, [R.id.paymentsFragment] otherwise. - * @property activeTab the logical tab to open ([PaymentsFragment.ACTIVE_TAB_RECEIVE], - * [PaymentsFragment.ACTIVE_TAB_PAY], ...), or null to let the screen restore - * the most recent one. - * @property enterAnim / [popExitAnim] the transition for this route, set on the - * [NavOptions] rather than in the fragment; null keeps the destination's - * existing behaviour (basic mode animates inside [PaymentsFragment]). + * and Receive shortcuts) goes, and with which transition. The transition is set + * on the [NavOptions] rather than in the fragment; null keeps the destination's + * own behaviour (basic mode animates inside [PaymentsFragment]). */ -data class PaymentsRoute( +enum class PaymentsRoute( @IdRes val destinationId: Int, - val activeTab: Int?, @AnimRes val enterAnim: Int?, @AnimRes val popExitAnim: Int? ) { + BASIC(R.id.paymentsFragment, enterAnim = null, popExitAnim = null), + ADVANCED(R.id.advancedPaymentsFragment, R.anim.slide_in_bottom, R.anim.slide_out_bottom); + /** Adds this route's transition, if any, to [builder]. */ fun applyAnimations(builder: NavOptions.Builder): NavOptions.Builder { enterAnim?.let { builder.setEnterAnim(it) } @@ -56,22 +51,8 @@ data class PaymentsRoute( * the setting has been read, and false while a read is failing, so an unknown * setting always opens the basic screen. */ -fun paymentsRoute(advancedMode: Boolean, activeTab: Int? = null): PaymentsRoute = - if (advancedMode) { - PaymentsRoute( - destinationId = R.id.advancedPaymentsFragment, - activeTab = activeTab, - enterAnim = R.anim.slide_in_bottom, - popExitAnim = R.anim.slide_out_bottom - ) - } else { - PaymentsRoute( - destinationId = R.id.paymentsFragment, - activeTab = activeTab, - enterAnim = null, - popExitAnim = null - ) - } +fun paymentsRoute(advancedMode: Boolean): PaymentsRoute = + if (advancedMode) PaymentsRoute.ADVANCED else PaymentsRoute.BASIC /** * Whether [destinationId] is one of the payments screens, i.e. whether the diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt index d9a8e641ad..2fc114766b 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt @@ -95,12 +95,14 @@ class ReceiveDetailsDialog : OffsetDialogFragment(R.layout.dialog_receive_detail override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - requireArguments().apply { - val requestAddress = getString(ARG_REQUEST_ADDRESS) - if (requestAddress != null) { - showAmountRequest(this, requestAddress) - return - } + val args = requireArguments() + val requestAddress = args.getString(ARG_REQUEST_ADDRESS) + if (requestAddress != null) { + showAmountRequest(args, requestAddress) + return + } + + args.apply { val address = getSerializable(ARG_ADDRESS) as Address val dashAmount = getSerializable(ARG_DASH_AMOUNT) as Coin val fiatAmount = getSerializable(ARG_FIAT_AMOUNT) as Fiat? diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index 72e0faddbd..cc42addd6a 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -17,6 +17,7 @@ package de.schildbach.wallet.ui.payments +import android.graphics.Bitmap import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -36,6 +37,8 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -54,6 +57,8 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import de.schildbach.wallet_test.R +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import org.dash.wallet.common.ui.components.DashButton import org.dash.wallet.common.ui.components.DashWalletTheme import org.dash.wallet.common.ui.components.LocalDashColors @@ -189,7 +194,8 @@ private fun BalancePicker( onSelectTab: (ReceiveBalanceTab) -> Unit ) { val colors = LocalDashColors.current - val options = tabs.map { SegmentedOption(stringResource(tabTitleFor(it))) } + val titles = ReceiveBalanceTab.entries.associateWith { stringResource(tabTitleFor(it)) } + val options = remember(tabs, titles) { tabs.map { SegmentedOption(titles.getValue(it)) } } SegmentedPicker( options = options, modifier = Modifier @@ -228,7 +234,7 @@ private fun QrCode(uiState: ReceiveUIState) { .background(if (payload != null) Color.White else colors.backgroundSecondary), contentAlignment = Alignment.Center ) { - val bitmap = remember(payload) { payload?.let { Qr.qrBitmap(it) } } + val bitmap = rememberQrBitmap(payload) when { bitmap != null -> { val description = stringResource(R.string.receive_qr_code_description) @@ -261,6 +267,21 @@ private fun QrCode(uiState: ReceiveUIState) { } } +/** + * The QR bitmap for [payload], encoded on [Dispatchers.Default]; null until it is ready. The + * state is keyed on [payload], so a new payload never shows the previous one's code. + */ +@Composable +private fun rememberQrBitmap(payload: String?): Bitmap? { + val bitmap = remember(payload) { mutableStateOf(null) } + LaunchedEffect(bitmap) { + if (payload != null) { + bitmap.value = withContext(Dispatchers.Default) { Qr.qrBitmap(payload) } + } + } + return bitmap.value +} + /** Figma 7062:49320 / 7062:49391: label over value, a gray tinted copy button on the right. */ @Composable private fun CopyRow(label: String, value: String, copyDescription: String, onCopy: () -> Unit) { @@ -312,7 +333,6 @@ private fun ReceivePagePreview() { uiState = ReceiveUIState( tabs = ReceiveBalanceTab.entries, address = "yZ3XpruChNgctwFvCzQ5WpFg7RpytQVwkA", - qrPayload = "dash:yZ3XpruChNgctwFvCzQ5WpFg7RpytQVwkA", username = "johndoe" ), onSelectTab = {}, diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt index bda51b9aa3..c2facd8e71 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -29,18 +29,13 @@ import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach -import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.dash.wallet.common.money.Coin @@ -63,22 +58,26 @@ enum class ReceiveBalanceTab { * @property selectedTab the tab whose [address] is on show. * @property address what [selectedTab] advertises, or null when there is nothing safe to show * (still loading, or unavailable — see [unavailable]). - * @property qrPayload the QR content for [address]: a `dash:` URI on Core, the bare address or - * ID elsewhere. - * @property loading a read for [selectedTab] is in flight. [address] may still hold the value - * being revalidated, so a resume does not blank the QR. - * @property unavailable the last read for [selectedTab] could not produce an address. + * @property loading [selectedTab] has no read result on show yet: true until its first read + * completes, so a fresh page shows progress rather than "unavailable". A re-read leaves the + * last result up until it answers: [address] keeps the value being revalidated (a resume + * does not blank the QR), and after a failed read this stays false (still [unavailable]). * @property username the user's username, or null when they have none. */ data class ReceiveUIState( val tabs: List = listOf(ReceiveBalanceTab.CORE), val selectedTab: ReceiveBalanceTab = ReceiveBalanceTab.CORE, val address: String? = null, - val qrPayload: String? = null, - val loading: Boolean = false, - val unavailable: Boolean = false, + val loading: Boolean = true, val username: String? = null ) { + /** The QR content for [address]: a `dash:` URI on Core, the bare address or ID elsewhere. */ + val qrPayload: String? = address?.let { ReceiveViewModel.qrPayloadOrNull(selectedTab, it, username) } + + /** The last read for [selectedTab] could not produce an address. */ + val unavailable: Boolean + get() = !loading && address == null + /** * Specify amount is on every tab. Core reads a fresh address itself once the amount is * entered (as it always has), so it is always enabled; the other tabs put [address] in @@ -171,23 +170,14 @@ class ReceiveViewModel internal constructor( return "${AddressNetwork.DASH_SCHEME}:$address?amount=${amount.toPlainString()}" } - /** - * The shielded flag as a never-failing flow: a failed read hides the - * Shield and Platform tabs and is retried, like the Internal tab - * ([advancedPaymentsTabsFlow]). - */ - internal fun shieldedEnabledFlow( - shieldedFlag: Flow, - retryDelayMs: (Long) -> Long = { attempt -> (attempt.coerceIn(0L, 11L) + 1) * 5_000L } - ): Flow = shieldedFlag - .map { it == true } - .retryWhen { e, attempt -> - log.warn("shielded flag read failed (attempt {})", attempt, e) - emit(false) - delay(retryDelayMs(attempt)) - true + /** [qrPayloadFor], or null (fail closed) when the URI builder rejects [address]. */ + internal fun qrPayloadOrNull(tab: ReceiveBalanceTab, address: String, username: String?): String? = + try { + qrPayloadFor(tab, address, username) + } catch (e: IllegalArgumentException) { + log.warn("cannot build the receive QR payload for {}", tab, e) + null } - .distinctUntilChanged() } private val _uiState = MutableStateFlow(ReceiveUIState()) @@ -203,7 +193,11 @@ class ReceiveViewModel internal constructor( private var loadGeneration = 0 init { - shieldedEnabledFlow(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) + // A failed read hides the Shield and Platform tabs and is retried, like the Internal tab. + shieldedEnabledFlow( + shieldedFlag = dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED), + onError = { e, attempt -> log.warn("shielded flag read failed (attempt {})", attempt, e) } + ) .onEach { shieldedEnabled = it applyTabs() @@ -243,9 +237,7 @@ class ReceiveViewModel internal constructor( fun selectTab(tab: ReceiveBalanceTab) { val state = _uiState.value if (tab == state.selectedTab || tab !in state.tabs) return - _uiState.update { - it.copy(selectedTab = tab, address = null, qrPayload = null, loading = false, unavailable = false) - } + _uiState.update { it.copy(selectedTab = tab, address = null, loading = true) } load(tab, force = true) } @@ -257,35 +249,22 @@ class ReceiveViewModel internal constructor( private fun publishUsername() { val username = if (hasUsername()) profileUsername ?: identity?.activeUsername else null - _uiState.update { state -> - val payload = state.address?.let { qrPayloadOrNull(state.selectedTab, it, username) } - state.copy(username = username, qrPayload = payload) - } + _uiState.update { it.copy(username = username) } } private fun applyTabs() { val tabs = tabsFor(supportsPlatform, shieldedEnabled, hasUsername()) - val state = _uiState.value - if (tabs == state.tabs) { - publishUsername() - return - } - if (state.selectedTab in tabs) { - _uiState.update { it.copy(tabs = tabs) } - publishUsername() - } else { - // The selected balance went away (flag off, username gone): back to Core. - _uiState.update { - it.copy( - tabs = tabs, - selectedTab = ReceiveBalanceTab.CORE, - address = null, - qrPayload = null, - loading = false, - unavailable = false - ) + // The selected balance went away (flag off, username gone): back to Core. + val lostSelection = _uiState.value.selectedTab !in tabs + _uiState.update { + if (lostSelection) { + it.copy(tabs = tabs, selectedTab = ReceiveBalanceTab.CORE, address = null, loading = true) + } else { + it.copy(tabs = tabs) } - publishUsername() + } + publishUsername() + if (lostSelection) { load(ReceiveBalanceTab.CORE, force = true) } } @@ -306,8 +285,9 @@ class ReceiveViewModel internal constructor( loadJob?.cancel() val generation = ++loadGeneration loadingTab = tab - // Keep what is on screen while revalidating it; a failure below takes it down. - _uiState.update { it.copy(loading = true) } + // Keep what is on screen while revalidating it — the address, or the "unavailable" of + // the last failed read — until this read replaces it; a failure below takes it down. + _uiState.update { if (it.unavailable) it else it.copy(loading = true) } loadJob = viewModelScope.launch { val address = try { sourceFor(tab).address() @@ -322,25 +302,11 @@ class ReceiveViewModel internal constructor( if (state.selectedTab != tab) { state } else { - val payload = address?.let { qrPayloadOrNull(tab, it, state.username) } - val shown = address.takeIf { payload != null } - state.copy( - address = shown, - qrPayload = payload, - loading = false, - unavailable = shown == null - ) + // Fail closed: an address the URI builder rejects is not advertised. + val shown = address?.takeIf { qrPayloadOrNull(tab, it, state.username) != null } + state.copy(address = shown, loading = false) } } } } - - private fun qrPayloadOrNull(tab: ReceiveBalanceTab, address: String, username: String?): String? = - try { - qrPayloadFor(tab, address, username) - } catch (e: IllegalArgumentException) { - // Fail closed: an address the URI builder rejects is not advertised. - log.warn("cannot build the receive QR payload for {}", tab, e) - null - } } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt index 19f85cbe53..eedffa91fb 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt @@ -30,17 +30,10 @@ import org.junit.Test import java.io.IOException class PaymentsRouteTest { - private val tabs = listOf( - PaymentsFragment.ACTIVE_TAB_RECEIVE, - PaymentsFragment.ACTIVE_TAB_INTERNAL, - PaymentsFragment.ACTIVE_TAB_PAY - ) - @Test fun `advanced mode off opens the basic screen with no extra transition`() { val route = paymentsRoute(advancedMode = false) assertEquals(R.id.paymentsFragment, route.destinationId) - assertNull(route.activeTab) assertNull(route.enterAnim) assertNull(route.popExitAnim) } @@ -49,25 +42,10 @@ class PaymentsRouteTest { fun `advanced mode on opens the advanced screen with its transition`() { val route = paymentsRoute(advancedMode = true) assertEquals(R.id.advancedPaymentsFragment, route.destinationId) - assertNull(route.activeTab) assertEquals(R.anim.slide_in_bottom, route.enterAnim) assertEquals(R.anim.slide_out_bottom, route.popExitAnim) } - @Test - fun `every tab is passed through unchanged in both modes`() { - for (advanced in listOf(false, true)) { - for (tab in tabs) { - val route = paymentsRoute(advanced, tab) - assertEquals(tab, route.activeTab) - assertEquals( - if (advanced) R.id.advancedPaymentsFragment else R.id.paymentsFragment, - route.destinationId - ) - } - } - } - @Test fun `an unreadable setting routes to the basic screen`() = runBlocking { // What MainViewModel.advancedMode holds while the read fails. diff --git a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt index 74bf818bdb..0a7413d97e 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt @@ -161,7 +161,7 @@ class ReceiveViewModelTest { if (attempts == 1) throw IOException("datastore") emit(true) } - val values = ReceiveViewModel.shieldedEnabledFlow(failingThenTrue, retryDelayMs = { 0L }) + val values = shieldedEnabledFlow(failingThenTrue, retryDelayMs = { 0L }) .take(2) .toList() assertEquals(listOf(false, true), values) @@ -278,6 +278,35 @@ class ReceiveViewModelTest { assertNull(viewModel.uiState.value.qrPayload) } + @Test + fun `a fresh page shows progress, not unavailable`() { + val state = ReceiveUIState() + assertTrue(state.loading) + assertFalse(state.unavailable) + assertNull(state.qrPayload) + } + + @Test + fun `a re-read after a failed read keeps unavailable on show until it answers`() { + val gate = CompletableDeferred() + var coreReads = 0 + val gatedSources = ReceiveAddressSources( + core = ReceiveAddressSource { if (coreReads++ == 0) null else gate.await() }, + shielded = ReceiveAddressSource { null }, + platform = ReceiveAddressSource { null } + ) + val viewModel = buildViewModel(receiveSources = gatedSources) + viewModel.refresh() + assertTrue(viewModel.uiState.value.unavailable) + + viewModel.refresh() + assertTrue(viewModel.uiState.value.unavailable) + + gate.complete(CORE_ADDRESS) + assertFalse(viewModel.uiState.value.unavailable) + assertEquals(CORE_ADDRESS, viewModel.uiState.value.address) + } + @Test fun `a source that throws gives no QR`() { val throwingSources = ReceiveAddressSources( @@ -323,7 +352,7 @@ class ReceiveViewModelTest { assertTrue(ReceiveUIState(selectedTab = IDENTITY, address = IDENTITY_ID).specifyAmountEnabled) // No address on show: nothing to put in the request. assertFalse(ReceiveUIState(selectedTab = SHIELD).specifyAmountEnabled) - assertFalse(ReceiveUIState(selectedTab = PLATFORM, unavailable = true).specifyAmountEnabled) + assertFalse(ReceiveUIState(selectedTab = PLATFORM, loading = false).specifyAmountEnabled) assertFalse(ReceiveUIState(selectedTab = IDENTITY, loading = true).specifyAmountEnabled) } From 9b0de6c56c94ad1b6acbdb31b608f7044061ee2b Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 12:22:26 -0800 Subject: [PATCH 06/13] fix(payments): keep the restored Receive page on rotation; stop logging receive values - AdvancedPaymentsFragment attaches the pager adapter only once its tabs are known, so ViewPager2 restores the saved pages instead of dropping them (a selected Shield/Platform/Identity balance no longer resets to Core after rotation). - ReceiveInfoView no longer writes the address, username or payment request into wallet.log on copy/share; the new Shielded/Platform/ Identity amount-request path goes through those handlers. Co-Authored-By: Claude Opus 5.5 --- .../dash/wallet/common/ui/receive/ReceiveInfoView.kt | 6 +++--- .../wallet/ui/payments/AdvancedPaymentsFragment.kt | 10 +++++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt b/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt index 516376a47a..6ef68f1ea3 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt @@ -236,19 +236,19 @@ class ReceiveInfoView(context: Context, attrs: AttributeSet?) : ConstraintLayout } Toast.makeText(context, R.string.copied, Toast.LENGTH_SHORT).show() - log.info("address copied to clipboard: {}", address) + log.info("address copied to clipboard") } private fun handleCopyUsername(username: String) { val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.setPrimaryClip(ClipData.newPlainText("Dash Username", username)) Toast.makeText(context, R.string.copied, Toast.LENGTH_SHORT).show() - log.info("username copied to clipboard: {}", username) + log.info("username copied to clipboard") } private fun handleShare(paymentRequestUri: String) { val title = resources.getString(R.string.request_coins_share_dialog_title) context.shareText(paymentRequestUri, title) - log.info("payment request shared via intent: {}", paymentRequestUri) + log.info("payment request shared via intent") } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt index 137a32eae0..4ed4f400ad 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -132,8 +132,8 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } } + // Attached by showTabs once the first tab set is in, not here: see there. val adapter = TabsAdapter(this, source = arguments?.getString(ARG_SOURCE) ?: "") - binding.pager.adapter = adapter // Only the top picker changes tabs: a sideways drag belongs to the page's own // content (the Receive balance switch scrolls sideways), never to the pager. binding.pager.isUserInputEnabled = false @@ -172,6 +172,14 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { val wanted = selectedTabId ?: initialTabId() val position = positionOf(newTabIds, wanted) adapter.submit(newTabIds) + // Attach only once populated, as PaymentsFragment does. ViewPager2 hands the adapter + // its saved pages when it is attached (or, if already attached, when the view state is + // restored), and FragmentStateAdapter drops every restored page that containsItem() + // rejects. Attached empty, that is every page: after a rotation the retained Receive + // child and its ViewModel would be recreated and the selected balance reset to Core. + if (binding.pager.adapter == null) { + binding.pager.adapter = adapter + } selectedTabId = newTabIds[position] binding.pager.setCurrentItem(position, false) } From de052a8489646b71c8cfe0cb00180a052cb6e528 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 12:29:01 -0800 Subject: [PATCH 07/13] fix(ui): place the fit-content picker thumb by absolute offset so RTL lines up positionInParent() measures from the physical left, so the thumb must use absoluteOffset rather than the layout-direction-relative offset. Co-Authored-By: Claude Opus 5.5 --- .../dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index 2dde2a17ca..e8153be044 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -321,7 +321,7 @@ private fun FitContentSegmentedPicker( style = style, color = thumbColor, modifier = Modifier - .offset(x = thumbOffset) + .absoluteOffset(x = thumbOffset) .width(thumbWidth) .fillMaxHeight() ) From 1e8cf0f7086166e231b7ca48111c3e95a01276bc Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 5 Nov 2026 20:42:57 -0800 Subject: [PATCH 08/13] fix(ui): match the Receive card to the updated Figma (MO-1123) Figma 7062:49310: - The balance picker spans the card's width. Its 20dp inset is padding inside the scroll, and both ends fade out (new opt-in SegmentedPickerStyle.contentPaddingHorizontal / edgeFadeFraction). - The thumb is Gray300 at 15% (segment/bg), not Gray400. - Unselected tabs are at 35% opacity (new SegmentedPickerStyle.unselectedContentAlpha, default 0.4 unchanged). - The username and address values use Text/Callout, 16/21 (new MyTheme.Typography.Callout). - The copy glyph is 16.5dp. Every other SegmentedPicker caller keeps the defaults, so it is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../wallet/common/ui/components/MyTheme.kt | 9 +++ .../ui/segmented_picker/SegmentedPicker.kt | 66 ++++++++++++++++--- .../wallet/ui/payments/ReceivePage.kt | 22 +++++-- 3 files changed, 82 insertions(+), 15 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/components/MyTheme.kt b/common/src/main/java/org/dash/wallet/common/ui/components/MyTheme.kt index c1a8b37389..d15b3c6e42 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/components/MyTheme.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/components/MyTheme.kt @@ -506,6 +506,15 @@ object MyTheme { fontWeight = FontWeight(400) ) + // Callout - the "Text/Callout" style (e.g. the Receive card's address value, Figma + // 7062:49310): BodyLarge's size with a tighter 21sp line height. + val Callout = TextStyle( + fontSize = 16.sp, + lineHeight = 21.sp, + fontFamily = interRegular, + fontWeight = FontWeight(400) + ) + // Footnote styles - secondary/explanatory text. From the "New/Text" styles that design // system components apply (e.g. SystemMessage's description, node 8378:445); not yet on // the documented typography page (node 5856:804). Same metrics as the deprecated diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index e8153be044..b7b0033526 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -35,7 +35,12 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.graphics.BlendMode +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalDensity @@ -90,7 +95,17 @@ data class SegmentedPickerStyle( // scrolling horizontally when they overflow, instead of splitting the width equally. The // thumb then follows the selected option's measured bounds (e.g. the Receive balance tabs, // Figma 7062:49313). Horizontal mode only; off by default. - val fitOptionsToContent: Boolean = false + val fitOptionsToContent: Boolean = false, + // Alpha of an unselected option's title and icon tint, relative to textPrimary. + val unselectedContentAlpha: Float = 0.4f, + // fitOptionsToContent only: horizontal inset inside the scrolling row, so options scroll + // right up to the picker's edges while resting inset from them (e.g. the Receive balance + // tabs, Figma 7062:49313, px-[20px]). Zero by default. + val contentPaddingHorizontal: Float = 0f, + // fitOptionsToContent only: fraction of the row's width over which each end fades from + // transparent to opaque (a horizontal alpha mask, symmetric so direction-neutral). Zero, + // the default, draws no fade. + val edgeFadeFraction: Float = 0f ) @Composable @@ -234,7 +249,8 @@ fun SegmentedPicker( modifier = Modifier.weight(1f), paddingHorizontal = style.optionPaddingHorizontal.dp, paddingVertical = style.optionPaddingVertical.dp, - iconAboveTitle = style.iconAboveTitle + iconAboveTitle = style.iconAboveTitle, + unselectedContentAlpha = style.unselectedContentAlpha ) } } @@ -257,7 +273,8 @@ fun SegmentedPicker( isHorizontal = false, paddingHorizontal = style.optionPaddingHorizontal.dp, paddingVertical = style.optionPaddingVertical.dp, - iconAboveTitle = style.iconAboveTitle + iconAboveTitle = style.iconAboveTitle, + unselectedContentAlpha = style.unselectedContentAlpha ) } } @@ -268,7 +285,8 @@ fun SegmentedPicker( /** * [SegmentedPicker] with [SegmentedPickerStyle.fitOptionsToContent]: options keep their own * width, start-aligned, and scroll horizontally when they do not fit. The thumb is drawn under - * the selected option's measured bounds. + * the selected option's measured bounds. [SegmentedPickerStyle.contentPaddingHorizontal] insets + * the scrolling content, and [SegmentedPickerStyle.edgeFadeFraction] fades the row's ends. */ @Composable private fun FitContentSegmentedPicker( @@ -308,14 +326,42 @@ private fun FitContentSegmentedPicker( label = "fitThumbWidth" ) + val edgeFade = style.edgeFadeFraction Box( modifier = modifier + .then( + if (edgeFade > 0f) { + Modifier + // Offscreen so DstIn masks only this row, not what is behind it. + .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } + .drawWithContent { + drawContent() + drawRect( + brush = Brush.horizontalGradient( + 0f to Color.Transparent, + edgeFade to Color.Black, + 1f - edgeFade to Color.Black, + 1f to Color.Transparent + ), + blendMode = BlendMode.DstIn + ) + } + } else { + Modifier + } + ) .clip(RoundedCornerShape(style.cornerRadius.dp)) .background(backgroundColor) .padding(style.containerPadding.dp) .horizontalScroll(rememberScrollState()) ) { - Box(modifier = Modifier.fillMaxHeight()) { + // The inset sits inside the scroll, around both the thumb and the row, so the measured + // option offsets and the thumb's absoluteOffset share one origin. + Box( + modifier = Modifier + .fillMaxHeight() + .padding(horizontal = style.contentPaddingHorizontal.dp) + ) { if (showSelection && selectedBounds != null) { SelectionThumb( style = style, @@ -347,7 +393,8 @@ private fun FitContentSegmentedPicker( }, paddingHorizontal = style.optionPaddingHorizontal.dp, paddingVertical = style.optionPaddingVertical.dp, - iconAboveTitle = style.iconAboveTitle + iconAboveTitle = style.iconAboveTitle, + unselectedContentAlpha = style.unselectedContentAlpha ) } } @@ -376,7 +423,8 @@ private fun OptionContent( isHorizontal: Boolean = true, paddingHorizontal: Dp = 0.dp, paddingVertical: Dp = 0.dp, - iconAboveTitle: Boolean = false + iconAboveTitle: Boolean = false, + unselectedContentAlpha: Float = 0.4f ) { Box( modifier = modifier @@ -393,7 +441,7 @@ private fun OptionContent( Icon( painter = painterResource(id = it), contentDescription = null, - tint = if (isSelected) Color.Unspecified else colors.textPrimary.copy(alpha = 0.4f), + tint = if (isSelected) Color.Unspecified else colors.textPrimary.copy(alpha = unselectedContentAlpha), modifier = iconModifier ) } @@ -401,7 +449,7 @@ private fun OptionContent( val title: @Composable () -> Unit = { Text( text = option.title, - color = if (isSelected) colors.textPrimary else colors.textPrimary.copy(alpha = 0.4f), + color = if (isSelected) colors.textPrimary else colors.textPrimary.copy(alpha = unselectedContentAlpha), style = textStyle, textAlign = TextAlign.Center ) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index cc42addd6a..24e3f40ebf 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -186,7 +186,11 @@ private fun tabTitleFor(tab: ReceiveBalanceTab): Int = when (tab) { ReceiveBalanceTab.IDENTITY -> R.string.receive_balance_identity } -/** Figma 7062:49313: text-only segments sized to their labels, the selected one on a gray pill. */ +/** + * Figma 7062:49313: text-only segments sized to their labels, the selected one on a gray pill. + * The row spans the card's full width: the 20dp side inset is padding inside the scroll, and the + * ends fade out so segments scroll to the card edge. + */ @Composable private fun BalancePicker( tabs: List, @@ -199,13 +203,14 @@ private fun BalancePicker( SegmentedPicker( options = options, modifier = Modifier - .padding(horizontal = 20.dp, vertical = 20.dp) + .padding(vertical = 20.dp) .fillMaxWidth() .height(40.dp), selectedIndex = tabs.indexOf(selectedTab).coerceAtLeast(0), style = SegmentedPickerStyle( backgroundColor = Color.Transparent, - thumbColor = colors.gray400.copy(alpha = 0.15f), + // segment/bg: Gray300 at 15%. + thumbColor = colors.gray300.copy(alpha = 0.15f), cornerRadius = 12f, thumbCornerRadius = 12f, containerPadding = 0f, @@ -213,7 +218,11 @@ private fun BalancePicker( showDividers = false, textStyle = MyTheme.Typography.BodyMediumSemibold, optionPaddingHorizontal = 20f, - fitOptionsToContent = true + fitOptionsToContent = true, + unselectedContentAlpha = 0.35f, + contentPaddingHorizontal = 20f, + // Figma 7062:49310 mask: alpha 0 at 0%, opaque from 4.792% to 95.297%, 0 at 100%. + edgeFadeFraction = 0.04792f ) ) { _, index -> tabs.getOrNull(index)?.let(onSelectTab) @@ -296,7 +305,7 @@ private fun CopyRow(label: String, value: String, copyDescription: String, onCop verticalArrangement = Arrangement.spacedBy(2.dp) ) { Text(text = label, style = MyTheme.Typography.Footnote, color = colors.textSecondary) - Text(text = value, style = MyTheme.Typography.BodyLarge, color = colors.textPrimary) + Text(text = value, style = MyTheme.Typography.Callout, color = colors.textPrimary) } CopyButton(description = copyDescription, onClick = onCopy) } @@ -319,7 +328,8 @@ private fun CopyButton(description: String, onClick: () -> Unit) { painter = painterResource(org.dash.wallet.common.R.drawable.ic_copy), contentDescription = null, tint = colors.textPrimary, - modifier = Modifier.size(18.dp) + // Figma: a 15dp glyph in a 20dp slot with a 5% outset. + modifier = Modifier.size(16.5.dp) ) } } From 316d189a8479ffcafaaa43a465a1e2637c8782d2 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 9 Nov 2026 15:46:05 -0800 Subject: [PATCH 09/13] fix(ui): draw Compose QR codes without bitmap filtering Qr.qrBitmap() encodes at one pixel per module (about 33-57 px), and a Compose Image scales it to 176-200dp with the default bilinear FilterQuality.Low, which blurs the module edges. Use FilterQuality.None, as the View path already does (Qr.themeAwareDrawable sets isFilterBitmap = false), on the Receive, Shielded receive and xpub QR codes. Co-Authored-By: Claude Opus 5.5 --- .../wallet/ui/compose_views/ExtendedPublicKeyDialog.kt | 2 ++ wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt | 2 ++ .../de/schildbach/wallet/ui/shielded/ShieldedReceiveScreen.kt | 2 ++ 3 files changed, 6 insertions(+) diff --git a/wallet/src/de/schildbach/wallet/ui/compose_views/ExtendedPublicKeyDialog.kt b/wallet/src/de/schildbach/wallet/ui/compose_views/ExtendedPublicKeyDialog.kt index 73f75939e1..b032c4e4af 100644 --- a/wallet/src/de/schildbach/wallet/ui/compose_views/ExtendedPublicKeyDialog.kt +++ b/wallet/src/de/schildbach/wallet/ui/compose_views/ExtendedPublicKeyDialog.kt @@ -15,6 +15,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign @@ -72,6 +73,7 @@ private fun ExtendedPublicKeyContent( bitmap = bitmap.asImageBitmap(), contentDescription = null, colorFilter = ColorFilter.tint(colors.textPrimary, BlendMode.SrcIn), + filterQuality = FilterQuality.None, modifier = Modifier .padding(vertical = 30.dp) .size(180.dp) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index 24e3f40ebf..722592e57b 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -47,6 +47,7 @@ import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource @@ -251,6 +252,7 @@ private fun QrCode(uiState: ReceiveUIState) { bitmap = bitmap.asImageBitmap(), contentDescription = description, colorFilter = ColorFilter.tint(Color.Black, BlendMode.SrcIn), + filterQuality = FilterQuality.None, modifier = Modifier.size(200.dp) ) Image( diff --git a/wallet/src/de/schildbach/wallet/ui/shielded/ShieldedReceiveScreen.kt b/wallet/src/de/schildbach/wallet/ui/shielded/ShieldedReceiveScreen.kt index ba86b3d3b9..59673b550e 100644 --- a/wallet/src/de/schildbach/wallet/ui/shielded/ShieldedReceiveScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/shielded/ShieldedReceiveScreen.kt @@ -45,6 +45,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource @@ -195,6 +196,7 @@ private fun ReceiveCard( bitmap = bitmap.asImageBitmap(), contentDescription = null, colorFilter = ColorFilter.tint(Color.Black, BlendMode.SrcIn), + filterQuality = FilterQuality.None, modifier = Modifier.size(176.dp) ) } From 66694e14ab658fb33eb3a35b1c5c44b33c39bd26 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 11:26:35 -0800 Subject: [PATCH 10/13] refactor(payments): cut per-update work on the Receive page and picker - ReceiveUIState builds its QR payload lazily, once per state, and load() validates through that same cached value. - ReceivePage remembers its picker options and the QR ImageBitmap. - FitContentSegmentedPicker reads the animated thumb offset and width in layout, caches the edge-fade brush, and records option bounds onPlaced, so animation and scroll frames no longer recompose. Drawn output is unchanged. - shieldedEnabledFlow uses the shared retryReadErrors helper. Co-Authored-By: Claude Opus 5.5 --- .../ui/segmented_picker/SegmentedPicker.kt | 44 +++++++++++++------ .../ui/payments/AdvancedPaymentsViewModel.kt | 15 +++---- .../wallet/ui/payments/ReceivePage.kt | 16 +++++-- .../wallet/ui/payments/ReceiveViewModel.kt | 18 +++++--- 4 files changed, 60 insertions(+), 33 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index b7b0033526..891e574430 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -35,13 +35,15 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection @@ -51,6 +53,7 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import org.dash.wallet.common.R @@ -334,17 +337,17 @@ private fun FitContentSegmentedPicker( Modifier // Offscreen so DstIn masks only this row, not what is behind it. .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } - .drawWithContent { - drawContent() - drawRect( - brush = Brush.horizontalGradient( - 0f to Color.Transparent, - edgeFade to Color.Black, - 1f - edgeFade to Color.Black, - 1f to Color.Transparent - ), - blendMode = BlendMode.DstIn + .drawWithCache { + val mask = Brush.horizontalGradient( + 0f to Color.Transparent, + edgeFade to Color.Black, + 1f - edgeFade to Color.Black, + 1f to Color.Transparent ) + onDrawWithContent { + drawContent() + drawRect(brush = mask, blendMode = BlendMode.DstIn) + } } } else { Modifier @@ -366,9 +369,20 @@ private fun FitContentSegmentedPicker( SelectionThumb( style = style, color = thumbColor, + // The animated values are read in the placement and measure lambdas, not in + // composition, so an animation frame relayouts the thumb without recomposing. + // Same rounding as absoluteOffset(x =) and width(): roundToPx, clamped to the + // incoming constraints. modifier = Modifier - .absoluteOffset(x = thumbOffset) - .width(thumbWidth) + .absoluteOffset { IntOffset(thumbOffset.roundToPx(), 0) } + .layout { measurable, constraints -> + val width = thumbWidth.roundToPx().coerceAtLeast(0) + .coerceIn(constraints.minWidth, constraints.maxWidth) + val placeable = measurable.measure( + constraints.copy(minWidth = width, maxWidth = width) + ) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + } .fillMaxHeight() ) } @@ -385,7 +399,9 @@ private fun FitContentSegmentedPicker( }, modifier = Modifier .fillMaxHeight() - .onGloballyPositioned { coordinates -> + // onPlaced, not onGloballyPositioned: the offset is in the Row, so + // it need not re-run on every scroll frame. + .onPlaced { coordinates -> val entry = coordinates.positionInParent().x.toInt() to coordinates.size.width if (index < bounds.size && bounds[index] != entry) { bounds[index] = entry diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt index d11c074d65..eb33b9b6ee 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt @@ -21,18 +21,17 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.schildbach.wallet.Constants -import org.dash.wallet.common.util.readRetryDelayMs import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import org.dash.wallet.common.util.readRetryDelayMs +import org.dash.wallet.common.util.retryReadErrors import org.slf4j.LoggerFactory import javax.inject.Inject @@ -71,7 +70,8 @@ class AdvancedPaymentsViewModel @Inject constructor( /** * The shielded flag as a never-failing flow: a failed read counts as off (as * [DashPayConfig.get] reading absent does for [PaymentsFragment]), is reported to - * [onError] and is retried, so the flow never completes on an error. Shared by the + * [onError] and is retried, so the flow never completes on an [Exception] (see + * [retryReadErrors]: a cancellation or an [Error] still propagates). Shared by the * Advanced payments tabs ([advancedPaymentsTabsFlow]) and the Receive balance tabs. */ internal fun shieldedEnabledFlow( @@ -80,12 +80,7 @@ internal fun shieldedEnabledFlow( retryDelayMs: (Long) -> Long = ::readRetryDelayMs ): Flow = shieldedFlag .map { it == true } - .retryWhen { e, attempt -> - onError(e, attempt) - emit(false) - delay(retryDelayMs(attempt)) - true - } + .retryReadErrors(false, retryDelayMs, onError) .distinctUntilChanged() /** diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index 722592e57b..d4e92aa911 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -49,6 +49,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -199,8 +201,13 @@ private fun BalancePicker( onSelectTab: (ReceiveBalanceTab) -> Unit ) { val colors = LocalDashColors.current - val titles = ReceiveBalanceTab.entries.associateWith { stringResource(tabTitleFor(it)) } - val options = remember(tabs, titles) { tabs.map { SegmentedOption(titles.getValue(it)) } } + // Resolved as stringResource does (it reads LocalConfiguration so a locale change + // recomposes), but only when the tabs or the configuration change. + val configuration = LocalConfiguration.current + val resources = LocalContext.current.resources + val options = remember(tabs, configuration, resources) { + tabs.map { SegmentedOption(resources.getString(tabTitleFor(it))) } + } SegmentedPicker( options = options, modifier = Modifier @@ -245,11 +252,12 @@ private fun QrCode(uiState: ReceiveUIState) { contentAlignment = Alignment.Center ) { val bitmap = rememberQrBitmap(payload) + val imageBitmap = remember(bitmap) { bitmap?.asImageBitmap() } when { - bitmap != null -> { + imageBitmap != null -> { val description = stringResource(R.string.receive_qr_code_description) Image( - bitmap = bitmap.asImageBitmap(), + bitmap = imageBitmap, contentDescription = description, colorFilter = ColorFilter.tint(Color.Black, BlendMode.SrcIn), filterQuality = FilterQuality.None, diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt index c2facd8e71..bcdc4c09a4 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -71,8 +71,15 @@ data class ReceiveUIState( val loading: Boolean = true, val username: String? = null ) { - /** The QR content for [address]: a `dash:` URI on Core, the bare address or ID elsewhere. */ - val qrPayload: String? = address?.let { ReceiveViewModel.qrPayloadOrNull(selectedTab, it, username) } + /** + * The QR content for [address]: a `dash:` URI on Core, the bare address or ID elsewhere. + * Built on first read and cached for this instance, not in the constructor, so the many + * `copy`s that only change other fields never build the URI unless someone reads it. Not + * part of equals/hashCode: it is derived from [selectedTab], [address] and [username]. + */ + val qrPayload: String? by lazy(LazyThreadSafetyMode.PUBLICATION) { + address?.let { ReceiveViewModel.qrPayloadOrNull(selectedTab, it, username) } + } /** The last read for [selectedTab] could not produce an address. */ val unavailable: Boolean @@ -302,9 +309,10 @@ class ReceiveViewModel internal constructor( if (state.selectedTab != tab) { state } else { - // Fail closed: an address the URI builder rejects is not advertised. - val shown = address?.takeIf { qrPayloadOrNull(tab, it, state.username) != null } - state.copy(address = shown, loading = false) + // Fail closed: an address the URI builder rejects is not advertised. The + // check reads the published state's own (cached) payload: built once. + val next = state.copy(address = address, loading = false) + if (address != null && next.qrPayload == null) next.copy(address = null) else next } } } From 4ee59705cae974f528b3db6e759b748b19086c9a Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 16:27:25 -0800 Subject: [PATCH 11/13] fix(payments): let Receive scroll clear of the bottom bar; RTL picker thumb - ReceivePage: the screen's bottom navigation is drawn over the page, so the scroll content ends a bar's height lower and the last buttons can scroll clear of it. The visible gaps are unchanged. - FitContentSegmentedPicker: anchor the thumb at the physical left before its absolute offset. With the default TopStart, RTL first placed it at the right edge and then added the physical offset, so it landed off the selected option. Co-Authored-By: Claude Opus 5.5 --- .../wallet/common/ui/segmented_picker/SegmentedPicker.kt | 8 +++++++- .../src/de/schildbach/wallet/ui/payments/ReceivePage.kt | 6 +++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index 891e574430..49ee1a8379 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -32,6 +32,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* +import androidx.compose.ui.AbsoluteAlignment import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -359,7 +360,11 @@ private fun FitContentSegmentedPicker( .horizontalScroll(rememberScrollState()) ) { // The inset sits inside the scroll, around both the thumb and the row, so the measured - // option offsets and the thumb's absoluteOffset share one origin. + // option offsets and the thumb's absoluteOffset share one origin. positionInParent() is + // the physical x in the Row, and this Box is as wide as the Row (the scroll gives it no + // minimum width), so the thumb is anchored at the physical left (TopLeft): the default + // TopStart would, in RTL, put it at the right edge and the offset would then be added + // on top. Checked in LTR and RTL that the thumb lands on the selected option. Box( modifier = Modifier .fillMaxHeight() @@ -374,6 +379,7 @@ private fun FitContentSegmentedPicker( // Same rounding as absoluteOffset(x =) and width(): roundToPx, clamped to the // incoming constraints. modifier = Modifier + .align(AbsoluteAlignment.TopLeft) .absoluteOffset { IntOffset(thumbOffset.roundToPx(), 0) } .layout { measurable, constraints -> val width = thumbWidth.roundToPx().coerceAtLeast(0) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt index d4e92aa911..910f33fef6 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -51,6 +51,7 @@ import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -89,11 +90,14 @@ fun ReceivePage( modifier: Modifier = Modifier ) { val colors = LocalDashColors.current + // The screen's bottom navigation (ShowNavBar) is drawn over the page, so the scroll ends a + // bar's height lower: the last buttons scroll clear of it and keep the design's 20dp gap. + val navBarClearance = dimensionResource(R.dimen.bottom_nav_bar_height) Column( modifier = modifier .fillMaxSize() .verticalScroll(rememberScrollState()) - .padding(start = 20.dp, end = 20.dp, bottom = 20.dp) + .padding(start = 20.dp, end = 20.dp, bottom = 20.dp + navBarClearance) ) { Column( modifier = Modifier From fd6ee672aa5a45a1c2d1c30bed1715f159e771cf Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 19:18:55 -0800 Subject: [PATCH 12/13] fix(payments): resolve amount-request addresses from the wallet; review fixes - ReceiveFragment no longer takes an address as a navigation argument. MainActivity is exported and forwards any caller's destination and arguments, so another app could open Receive with its own address in the amount request. The argument now names only a balance (request_balance); AmountRequestAddressResolver reads the address from the same wallet sources Advanced Receive shows and fails closed on an unknown balance or a missing address. - Platform Receive shows only an unused Platform address (unusedPlatformAddressOrNull) and null otherwise; the used-address fallback stays for the self-unshield path only. - The non-Core amount request is built with PaymentURI.convertToPaymentURI and the wallet's AddressNetwork instead of a hand-built string. - SegmentedPicker fixed-width mode: drop the manual RTL mirror. The thumb is start-aligned and Modifier.offset is direction-aware, so mirroring the position as well put the thumb over the mirrored option (measured with 2 and 3 options in LTR and RTL). Co-Authored-By: Claude Opus 5.5 --- .../ui/segmented_picker/SegmentedPicker.kt | 15 +-- wallet/res/navigation/nav_home.xml | 15 +-- wallet/res/navigation/nav_quick_receive.xml | 15 +-- .../platform/sdk/ShieldedBalanceService.kt | 12 +- .../sdk/ShieldedBalanceServiceImpl.kt | 22 +++- .../ui/payments/AdvancedReceiveFragment.kt | 10 +- .../ui/payments/ReceiveAddressSources.kt | 68 ++++++++++ .../ui/payments/ReceiveDetailsDialog.kt | 8 +- .../wallet/ui/payments/ReceiveFragment.kt | 85 +++++++------ .../wallet/ui/payments/ReceiveViewModel.kt | 17 +-- .../sdk/ShieldedBalanceServiceTest.kt | 35 +++++- .../AmountRequestAddressResolverTest.kt | 119 ++++++++++++++++++ 12 files changed, 329 insertions(+), 92 deletions(-) create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/AmountRequestAddressResolverTest.kt diff --git a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt index 49ee1a8379..614500b7d0 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt @@ -47,7 +47,6 @@ import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle @@ -55,7 +54,6 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import org.dash.wallet.common.R import org.dash.wallet.common.ui.components.DashWalletTheme @@ -136,7 +134,6 @@ fun SegmentedPicker( } val density = LocalDensity.current - val layoutDirection = LocalLayoutDirection.current // Resolve theme-aware defaults so the picker tracks light/dark; explicit style colors win. val colors = LocalDashColors.current @@ -166,14 +163,10 @@ fun SegmentedPicker( val optionSizePx = if (containerSize > 0) containerSize * itemSize else 0f val positionPx = optionSizePx * internalSelectedIndex - // Calculate animation position - val positionDp = with(density) { positionPx.toDp() } - val targetPosition = if (isHorizontal && layoutDirection == LayoutDirection.Rtl) { - // For RTL horizontal mode, calculate position from the right side - with(density) { (containerWidth - optionSizePx - positionPx).toDp() } - } else { - positionDp - } + // The thumb's offset from the start edge. The thumb is start-aligned and Modifier.offset is + // direction-aware, so in RTL both already measure from the right, where option 0 sits; + // mirroring the position here as well would put the thumb over the mirrored option. + val targetPosition = with(density) { positionPx.toDp() } val animatedPosition by animateDpAsState( targetValue = targetPosition, diff --git a/wallet/res/navigation/nav_home.xml b/wallet/res/navigation/nav_home.xml index 0eab7901cb..01c6294356 100644 --- a/wallet/res/navigation/nav_home.xml +++ b/wallet/res/navigation/nav_home.xml @@ -297,20 +297,17 @@ tools:layout="@layout/fragment_receive"> - - - - \ No newline at end of file diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt index b0a653152a..44764ff82d 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -333,11 +333,13 @@ interface ShieldedBalanceService { suspend fun shieldedReceiveAddress(): String? /** - * The wallet's own Platform (DIP-17) receive address as stored by the SDK - * — the lowest unused index, else the lowest index of any state, the same - * row [unshieldToCredits] pays itself to — or null when the flag is off, - * the runtime is not ready, or the SDK's address store has no row for the - * wallet yet. Never throws (except cancellation). + * The wallet's Platform (DIP-17) receive address to show to payers: the + * lowest-index UNUSED address the SDK has stored — or null when the flag + * is off, the runtime is not ready, or the store has no unused row for the + * wallet (every row used, or none yet). Never a used address, so payments + * cannot be linked through it; unlike the self-unshield target, which falls + * back to a used row. Null is retryable: Receive shows "unavailable" and + * reads again on its next resume. Never throws (except cancellation). */ suspend fun platformReceiveAddress(): String? diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt index df57cadf56..b26cb415b4 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -583,6 +583,13 @@ internal fun classifyCoinJoinFunding( // ── Source seam ─────────────────────────────────────────────────────── +/** + * The lowest-[index] row of [rows] that is not [isUsed], or null when every row is used (or + * there are none). No fallback to a used row: see [ShieldedSource.unusedPlatformAddressOrNull]. + */ +internal fun > lowestUnusedOrNull(rows: List, isUsed: (T) -> Boolean, index: (T) -> K): T? = + rows.filter { !isUsed(it) }.minByOrNull(index) + /** * Seam over the Kotlin SDK's shielded surface * ([org.dashfoundation.dashsdk.wallet.PlatformWalletManager]'s shielded @@ -685,6 +692,14 @@ interface ShieldedSource { */ suspend fun ownPlatformAddressOrNull(walletId: ByteArray): String? + /** + * The wallet's lowest-index UNUSED DIP-17 Platform address (bech32m), or null when the SDK's + * address store has no unused row for the wallet. Unlike [ownPlatformAddressOrNull] it never + * falls back to a used address: this one is shown to payers, and reusing an address would + * link their payments. + */ + suspend fun unusedPlatformAddressOrNull(walletId: ByteArray): String? + /** Type 15: shield credits into the wallet's own pool. Blocks for the proof. */ suspend fun shield(walletId: ByteArray, amountCredits: Long) @@ -842,6 +857,11 @@ internal class DashSdkShieldedSource( return row?.address } + override suspend fun unusedPlatformAddressOrNull(walletId: ByteArray): String? { + val rows = database().platformAddressDao().observeByWallet(walletId).first() + return lowestUnusedOrNull(rows, isUsed = { it.isUsed }, index = { it.addressIndex })?.address + } + override suspend fun shield(walletId: ByteArray, amountCredits: Long) = manager().shieldedShield(walletId = walletId, amount = amountCredits) @@ -2054,7 +2074,7 @@ class ShieldedBalanceServiceImpl internal constructor( if (!ensureShieldedReady()) return null val walletId = readyWalletIdHex.value?.let(::walletIdFromHex) ?: return null return try { - source.ownPlatformAddressOrNull(walletId) + source.unusedPlatformAddressOrNull(walletId) } catch (t: Throwable) { if (t is CancellationException) throw t log.warn("failed to read the platform receive address", t) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt index f1c732d4ce..4f20fee881 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt @@ -101,8 +101,9 @@ class AdvancedReceiveFragment : Fragment() { /** * Core opens the amount screen as it always has: [ReceiveFragment] reads a fresh address - * once the amount is entered. The other tabs hand it the [address] on show, and their - * request is a bare `dash:` URI ([ReceiveViewModel.amountRequestPayload]). + * once the amount is entered. The other tabs pass only the balance; [ReceiveFragment] reads + * that balance's address from the wallet ([AmountRequestAddressResolver]), never from its + * arguments, and the request is a bare `dash:` URI ([ReceiveViewModel.amountRequestPayload]). */ private fun specifyAmount(tab: ReceiveBalanceTab, address: String?) { val navController = findNavController() @@ -113,10 +114,7 @@ class AdvancedReceiveFragment : Fragment() { } else { // The button is disabled without an address; nothing to request otherwise. if (address == null) return - PaymentsFragmentDirections.paymentsToReceive( - requestAddress = address, - requestAddressLabel = addressLabelFor(tab) - ) + PaymentsFragmentDirections.paymentsToReceive(requestBalance = tab.name) } viewModel.logEvent(AnalyticsConstants.SendReceive.SPECIFY_AMOUNT) navController.navigate(directions) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt index e3f9b539ed..b7ae7f18ec 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt @@ -18,7 +18,9 @@ package de.schildbach.wallet.ui.payments import de.schildbach.wallet.data.WalletData +import de.schildbach.wallet.database.entity.BlockchainIdentityConfig import de.schildbach.wallet.service.platform.sdk.ShieldedBalanceService +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.bitcoinj.core.Context @@ -73,3 +75,69 @@ class ReceiveAddressSources( platform = ReceiveAddressSource { shieldedBalanceService.platformReceiveAddress() } ) } + +/** What [ReceiveFragment]'s Specify amount puts in its request; see [AmountRequestAddressResolver]. */ +sealed interface AmountRequestTarget { + /** Core: [ReceiveFragment] reads a fresh Core address itself, as it always has. */ + data object Core : AmountRequestTarget + + /** [address] was read from [tab]'s wallet source just now. */ + data class Address(val tab: ReceiveBalanceTab, val address: String) : AmountRequestTarget + + /** An unknown balance, or its source has nothing safe to show: no request at all. */ + data object Unavailable : AmountRequestTarget +} + +/** + * Resolves the balance [ReceiveFragment] was opened for to the address its request carries. + * + * [ReceiveFragment] is reachable from other apps: MainActivity is exported and navigates to any + * destination an intent names, with that intent's arguments. So its argument names only a + * balance (a [ReceiveBalanceTab] name), never an address: the address is always read here, + * from the same wallet sources Advanced Receive shows. Fail closed: an unknown balance, or a + * source that has no address or fails, yields [AmountRequestTarget.Unavailable], never Core's + * address for another balance. + */ +class AmountRequestAddressResolver( + private val sources: ReceiveAddressSources, + private val identity: ReceiveAddressSource +) { + @Inject + constructor(sources: ReceiveAddressSources, identityConfig: BlockchainIdentityConfig) : this( + sources, + // As ReceiveViewModel's Identity tab: the identity ID, only once it has a username. + ReceiveAddressSource { identityConfig.load()?.takeIf { it.hasUsername }?.userId } + ) + + private companion object { + private val log = LoggerFactory.getLogger(AmountRequestAddressResolver::class.java) + } + + /** [balance] is the navigation argument: null (every caller but Advanced Receive) is Core. */ + suspend fun resolve(balance: String?): AmountRequestTarget { + if (balance == null) return AmountRequestTarget.Core + val tab = ReceiveBalanceTab.entries.firstOrNull { it.name == balance } + if (tab == null) { + // Not logged: the value came from outside and may be anything, an address included. + log.warn("unknown balance requested for an amount request; showing none") + return AmountRequestTarget.Unavailable + } + val source = when (tab) { + ReceiveBalanceTab.CORE -> return AmountRequestTarget.Core + ReceiveBalanceTab.SHIELD -> sources.shielded + ReceiveBalanceTab.PLATFORM -> sources.platform + ReceiveBalanceTab.IDENTITY -> identity + } + val address = try { + source.address() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("receive address read failed for {}; showing no request", tab, e) + null + } + return address?.takeIf { it.isNotEmpty() } + ?.let { AmountRequestTarget.Address(tab, it) } + ?: AmountRequestTarget.Unavailable + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt index 2fc114766b..517380c849 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveDetailsDialog.kt @@ -65,10 +65,10 @@ class ReceiveDetailsDialog : OffsetDialogFragment(R.layout.dialog_receive_detail } /** - * The same dialog for an address [PaymentURI][org.dash.wallet.common.payments.parsers.PaymentURI] - * cannot carry (Advanced Receive's shielded and Platform addresses and identity ID): - * the QR holds [ReceiveViewModel.amountRequestPayload] and the address shows under - * [addressLabel]. There is no username row. + * The same dialog for an address that is not a base58 Core address (Advanced Receive's + * shielded and Platform addresses and identity ID): the QR holds + * [ReceiveViewModel.amountRequestPayload] and the address shows under [addressLabel]. + * There is no username row. */ fun createAmountRequestDialog( addressLabel: String, diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt index 4db630a45d..4adf38cc1e 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveFragment.kt @@ -29,6 +29,7 @@ import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentReceiveBinding +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import org.bitcoinj.core.Coin import de.schildbach.wallet.data.WalletData @@ -55,6 +56,7 @@ class ReceiveFragment : Fragment(R.layout.fragment_receive) { private val enterAmountViewModel by activityViewModels() private val binding by viewBinding(FragmentReceiveBinding::bind) @Inject lateinit var walletData: WalletData + @Inject lateinit var amountRequestAddressResolver: AmountRequestAddressResolver override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) @@ -81,51 +83,62 @@ class ReceiveFragment : Fragment(R.layout.fragment_receive) { } enterAmountViewModel.setMaxAmount(org.dash.wallet.common.money.Coin.ZERO) enterAmountViewModel.setMinAmount(org.dash.wallet.common.money.Coin.ZERO) - // Set only by Advanced Receive's Shield/Platform/Identity tabs; every other caller - // leaves it null and gets a fresh Core address below. - val args = ReceiveFragmentArgs.fromBundle(arguments ?: Bundle()) - val requestAddress = args.requestAddress + // A balance name, set only by Advanced Receive's Shield/Platform/Identity tabs; every + // other caller leaves it null and gets a fresh Core address below. This destination is + // reachable from other apps, so the argument never carries an address: the resolver + // reads it from the wallet (and shows no request for an unknown balance). + val requestBalance = ReceiveFragmentArgs.fromBundle(arguments ?: Bundle()).requestBalance enterAmountViewModel.onContinueEvent.observe(viewLifecycleOwner) { val dashAmount = it.first val fiatAmount = it.second - if (requestAddress != null) { - // Both arguments are set together; the generic label covers a caller that did not. - val label = args.requestAddressLabel.takeIf { label -> label != 0 } - ?: org.dash.wallet.common.R.string.dash_address - ReceiveDetailsDialog.createAmountRequestDialog( - getString(label), - requestAddress, - dashAmount.toDashjCoin(), - fiatAmount?.toDashjFiat() - ).show(requireActivity()) - return@observe - } - // OFF THE MAIN THREAD: this observer runs on Main, and dashj's - // freshReceiveAddress() forces a synchronous full-wallet save - // (measured 1.2s at 215 friend chains) — see freshReceiveAddressOffMain. viewLifecycleOwner.lifecycleScope.launch { - try { - val address = walletData.freshReceiveAddressOffMain() - val dialogFragment = ReceiveDetailsDialog.createDialog( - address, dashAmount.toDashjCoin(), fiatAmount?.toDashjFiat() - ) - dialogFragment.show(requireActivity()) - } catch (ex: ReceiveAddressUnavailableException) { - // No safe address to put in the request — see - // PaymentsReceiveFragment. Better no invoice than one the - // chain has already paid. - // - // Guarded: the read parks uncancellably, so this arm can run - // after the VIEW scope was cancelled, which on this screen - // means the user navigated on with the fragment still on the - // back stack — attached, so only the cancellation half of the - // guard suppresses the toast. - toastIfStillAttached(org.dash.wallet.common.R.string.loading_error) + when (val target = amountRequestAddressResolver.resolve(requestBalance)) { + AmountRequestTarget.Core -> showCoreRequest(dashAmount, fiatAmount) + is AmountRequestTarget.Address -> { + // The read may return after the view scope was cancelled. + ensureActive() + ReceiveDetailsDialog.createAmountRequestDialog( + getString(addressLabelFor(target.tab)), + target.address, + dashAmount.toDashjCoin(), + fiatAmount?.toDashjFiat() + ).show(requireActivity()) + } + // Nothing from the wallet to put in the request: no request. + AmountRequestTarget.Unavailable -> + toastIfStillAttached(org.dash.wallet.common.R.string.loading_error) } } } } + private suspend fun showCoreRequest( + dashAmount: org.dash.wallet.common.money.Coin, + fiatAmount: org.dash.wallet.common.money.Fiat? + ) { + // OFF THE MAIN THREAD: the caller runs on Main, and dashj's + // freshReceiveAddress() forces a synchronous full-wallet save + // (measured 1.2s at 215 friend chains) — see freshReceiveAddressOffMain. + try { + val address = walletData.freshReceiveAddressOffMain() + val dialogFragment = ReceiveDetailsDialog.createDialog( + address, dashAmount.toDashjCoin(), fiatAmount?.toDashjFiat() + ) + dialogFragment.show(requireActivity()) + } catch (ex: ReceiveAddressUnavailableException) { + // No safe address to put in the request — see + // PaymentsReceiveFragment. Better no invoice than one the + // chain has already paid. + // + // Guarded: the read parks uncancellably, so this arm can run + // after the VIEW scope was cancelled, which on this screen + // means the user navigated on with the fragment still on the + // back stack — attached, so only the cancellation half of the + // guard suppresses the toast. + toastIfStillAttached(org.dash.wallet.common.R.string.loading_error) + } + } + override fun onDestroy() { enterAmountViewModel.resetCurrency() super.onDestroy() diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt index bcdc4c09a4..275ea69627 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -147,8 +147,8 @@ class ReceiveViewModel internal constructor( /** * The QR content for [address] on [tab]. Core keeps today's `dash:` URI (with the * username, as [org.dash.wallet.common.ui.receive.ReceiveInfoView] does); the other - * tabs are not base58 L1 addresses, which [PaymentURI] cannot carry, so they encode - * the bare value. + * tabs are not base58 L1 addresses ([AddressNetwork.fromDashAddress] rejects them), so + * they encode the bare value. */ @VisibleForTesting fun qrPayloadFor(tab: ReceiveBalanceTab, address: String, username: String?): String = @@ -164,17 +164,20 @@ class ReceiveViewModel internal constructor( else -> address } + /** The wallet's network, for its `dash:` URI scheme: from its id, never from an address. */ + private val walletNetwork: AddressNetwork by lazy { AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id) } + /** * The Specify amount request for a tab other than Core: exactly - * `dash:
?amount=`, the amount in DASH formatted as Core's `dash:` URI - * formats it ([Coin.toPlainString], as [PaymentURI.convertToPaymentURI] does). Built - * by hand because [PaymentURI] and [AddressNetwork] accept only base58 L1 addresses, - * not bech32 shielded/Platform addresses or identity IDs. + * `dash:
?amount=`, built by [PaymentURI.convertToPaymentURI] as Core's + * request is. That builder appends [address] as given, so it carries bech32 + * shielded/Platform addresses and identity IDs too; the network comes from the wallet, + * not from [AddressNetwork.fromDashAddress], which accepts only base58 L1 addresses. */ fun amountRequestPayload(address: String, amount: Coin): String { require(address.isNotEmpty()) { "no address for the payment request" } require(amount.signum() >= 0) { "the requested amount must not be negative" } - return "${AddressNetwork.DASH_SCHEME}:$address?amount=${amount.toPlainString()}" + return PaymentURI.convertToPaymentURI(walletNetwork, address, amount, null, null) } /** [qrPayloadFor], or null (fail closed) when the URI builder rejects [address]. */ diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt index 632fe88987..2423e4efc5 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -118,6 +118,7 @@ class ShieldedBalanceServiceTest { var defaultAddress: ByteArray? = ByteArray(43) { 7 } var platformAddress: () -> String? = { "tdash1ownplatformaddress" } + var unusedPlatformAddress: () -> String? = { "tdash1unusedplatformaddress" } val notesFlow = MutableStateFlow>(emptyList()) val activityFlow = MutableStateFlow>(emptyList()) @@ -273,6 +274,8 @@ class ShieldedBalanceServiceTest { override suspend fun ownPlatformAddressOrNull(walletId: ByteArray): String? = platformAddress() + override suspend fun unusedPlatformAddressOrNull(walletId: ByteArray): String? = unusedPlatformAddress() + override suspend fun shield(walletId: ByteArray, amountCredits: Long) { broadcastCalls++ lastAmountCredits = amountCredits @@ -1464,9 +1467,33 @@ class ShieldedBalanceServiceTest { } @Test - fun platformReceiveAddress_isTheSourcesOwnPlatformAddress() = runBlocking { - val source = readySource().apply { platformAddress = { "tdash1qown" } } - assertEquals("tdash1qown", service(source).platformReceiveAddress()) + fun platformReceiveAddress_isTheSourcesUnusedPlatformAddress() = runBlocking { + val source = readySource().apply { + platformAddress = { "tdash1qownused" } + unusedPlatformAddress = { "tdash1qunused" } + } + assertEquals("tdash1qunused", service(source).platformReceiveAddress()) + } + + @Test + fun platformReceiveAddress_nullWhenNoUnusedAddress_neverTheUsedFallback() = runBlocking { + // The self-unshield lookup still has a (used) address; Receive must not show it. + val source = readySource().apply { + platformAddress = { "tdash1qownused" } + unusedPlatformAddress = { null } + } + assertNull(service(source).platformReceiveAddress()) + } + + @Test + fun lowestUnusedOrNull_allUsed_isNull_oneUnused_isThatRow() { + data class Row(val index: Int, val used: Boolean) + fun pick(rows: List) = lowestUnusedOrNull(rows, isUsed = { it.used }, index = { it.index }) + + assertNull(pick(emptyList())) + assertNull(pick(listOf(Row(0, true), Row(1, true), Row(2, true)))) + assertEquals(Row(1, false), pick(listOf(Row(0, true), Row(1, false), Row(2, true)))) + assertEquals(Row(2, false), pick(listOf(Row(5, false), Row(0, true), Row(2, false)))) } @Test @@ -1479,7 +1506,7 @@ class ShieldedBalanceServiceTest { @Test fun platformReceiveAddress_lookupFailure_isNullNotThrown() = runBlocking { val source = readySource().apply { - platformAddress = { throw DashSdkError.InternalError("room read failed") } + unusedPlatformAddress = { throw DashSdkError.InternalError("room read failed") } } assertNull(service(source).platformReceiveAddress()) } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/AmountRequestAddressResolverTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/AmountRequestAddressResolverTest.kt new file mode 100644 index 0000000000..a85ea410df --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/AmountRequestAddressResolverTest.kt @@ -0,0 +1,119 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments + +import android.app.Application +import android.os.Bundle +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.IOException + +/** + * [ReceiveFragment] is reachable from other apps with arguments they choose, so whatever its + * argument holds, the request it shows carries only an address read from the wallet. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class, sdk = [29], manifest = Config.NONE) +class AmountRequestAddressResolverTest { + private companion object { + const val SHIELDED_ADDRESS = "tdash1qshieldedaddress" + const val PLATFORM_ADDRESS = "tevo1qplatformaddress" + const val IDENTITY_ID = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" + + /** An address another app would like the user to show as their own. */ + const val FOREIGN_ADDRESS = "yjSvwyLB5X4dqQqVMPMu6UdrFpYZ3u9v5U" + } + + private val reads = mutableListOf() + private var shielded: suspend () -> String? = { SHIELDED_ADDRESS } + private var platform: suspend () -> String? = { PLATFORM_ADDRESS } + private var identity: suspend () -> String? = { IDENTITY_ID } + + private val resolver = AmountRequestAddressResolver( + ReceiveAddressSources( + core = ReceiveAddressSource { reads += "core"; error("Core is read by ReceiveFragment, not here") }, + shielded = ReceiveAddressSource { reads += "shielded"; shielded() }, + platform = ReceiveAddressSource { reads += "platform"; platform() } + ), + identity = ReceiveAddressSource { reads += "identity"; identity() } + ) + + private fun resolve(balance: String?) = runBlocking { resolver.resolve(balance) } + + @Test + fun `no balance is the Core flow`() { + assertEquals(AmountRequestTarget.Core, resolve(null)) + assertEquals(AmountRequestTarget.Core, resolve(ReceiveBalanceTab.CORE.name)) + assertTrue(reads.isEmpty()) + } + + @Test + fun `the old address arguments from another app are ignored`() { + val external = Bundle().apply { + putString("request_address", FOREIGN_ADDRESS) + putInt("request_address_label", 1) + } + val balance = ReceiveFragmentArgs.fromBundle(external).requestBalance + assertNull(balance) + // So the request is Core's, whose address ReceiveFragment reads from the wallet. + assertEquals(AmountRequestTarget.Core, resolve(balance)) + } + + @Test + fun `each balance's address comes from its wallet source`() { + assertEquals( + AmountRequestTarget.Address(ReceiveBalanceTab.SHIELD, SHIELDED_ADDRESS), + resolve(ReceiveBalanceTab.SHIELD.name) + ) + assertEquals( + AmountRequestTarget.Address(ReceiveBalanceTab.PLATFORM, PLATFORM_ADDRESS), + resolve(ReceiveBalanceTab.PLATFORM.name) + ) + assertEquals( + AmountRequestTarget.Address(ReceiveBalanceTab.IDENTITY, IDENTITY_ID), + resolve(ReceiveBalanceTab.IDENTITY.name) + ) + assertEquals(listOf("shielded", "platform", "identity"), reads) + } + + @Test + fun `an external value that is not a balance shows no request and reads nothing`() { + // The old argument carried an address; one passed as the balance is not one. + for (bogus in listOf(FOREIGN_ADDRESS, "dash:$FOREIGN_ADDRESS?amount=1", "shield", "Shield", " SHIELD", "", "4")) { + assertEquals(bogus, AmountRequestTarget.Unavailable, resolve(bogus)) + } + assertTrue(reads.isEmpty()) + } + + @Test + fun `a balance whose source has nothing shows no request, never Core's address`() { + shielded = { null } + platform = { "" } + identity = { throw IOException("identity read failed") } + assertEquals(AmountRequestTarget.Unavailable, resolve(ReceiveBalanceTab.SHIELD.name)) + assertEquals(AmountRequestTarget.Unavailable, resolve(ReceiveBalanceTab.PLATFORM.name)) + assertEquals(AmountRequestTarget.Unavailable, resolve(ReceiveBalanceTab.IDENTITY.name)) + assertTrue("core" !in reads) + } +} From 263f160e2182e90b55a0ddee38aa1805775b5ef6 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 20:49:13 -0800 Subject: [PATCH 13/13] fix(payments): bring the Identity tab back after a failed identity read BlockchainIdentityConfig.observe() turns an IOException into "no identity" and then completes, so one transient read failure hid Receive's Identity tab until the screen was recreated. Receive now reads BlockchainIdentityConfig.observePreservingErrors() (on BaseConfig's new dataPreservingErrors, the single source for data and the *PreservingErrors reads) through retryReadErrors: while the read fails the tab and username are withheld, and they return on the same ViewModel once a retry succeeds. observe() is unchanged for its other callers. Co-Authored-By: Claude Opus 5.5 --- .../org/dash/wallet/common/data/BaseConfig.kt | 12 ++- .../database/entity/BlockchainIdentityData.kt | 10 ++- .../wallet/ui/payments/ReceiveViewModel.kt | 36 +++++++-- .../ui/payments/ReceiveViewModelTest.kt | 80 ++++++++++++++++++- 4 files changed, 128 insertions(+), 10 deletions(-) diff --git a/common/src/main/java/org/dash/wallet/common/data/BaseConfig.kt b/common/src/main/java/org/dash/wallet/common/data/BaseConfig.kt index b22deafb7d..a995519089 100644 --- a/common/src/main/java/org/dash/wallet/common/data/BaseConfig.kt +++ b/common/src/main/java/org/dash/wallet/common/data/BaseConfig.kt @@ -105,7 +105,15 @@ abstract class BaseConfig( produceMigrations = { migrations } ) - protected val data = context.dataStore.data + /** + * The store's preferences WITHOUT [data]'s IOException rescue: an unreadable + * store arrives as the THROW it was, not as [emptyPreferences]. The one source + * for [data] and the `*PreservingErrors` reads; collect it (with a retry such as + * `retryReadErrors`) where "could not read" must not pass for "never written". + */ + protected val dataPreservingErrors: Flow = context.dataStore.data + + protected val data = dataPreservingErrors .catch { exception -> if (exception is IOException) { emit(emptyPreferences()) @@ -146,7 +154,7 @@ abstract class BaseConfig( * IOException, for the caller to fail closed on. */ open fun observePreservingErrors(key: Preferences.Key): Flow { - return context.dataStore.data.map { preferences -> preferences[key] } + return dataPreservingErrors.map { preferences -> preferences[key] } } open suspend fun get(key: Preferences.Key): T? { diff --git a/wallet/src/de/schildbach/wallet/database/entity/BlockchainIdentityData.kt b/wallet/src/de/schildbach/wallet/database/entity/BlockchainIdentityData.kt index 1f2487a3df..52236d804f 100644 --- a/wallet/src/de/schildbach/wallet/database/entity/BlockchainIdentityData.kt +++ b/wallet/src/de/schildbach/wallet/database/entity/BlockchainIdentityData.kt @@ -310,7 +310,7 @@ open class BlockchainIdentityConfig @Inject constructor( } /** Unlike ordinary preference reads, absence here must never be inferred from an I/O fallback. */ - fun observeIdentityPresence(): Flow = context.dataStore.data.map { prefs -> + fun observeIdentityPresence(): Flow = dataPreservingErrors.map { prefs -> IdentityCreationState.valueOf(prefs[CREATION_STATE] ?: "NONE") != IdentityCreationState.NONE || prefs.asMap().keys.any { it != CREATION_STATE } } @@ -373,6 +373,14 @@ open class BlockchainIdentityConfig @Inject constructor( return identityData } + /** + * [observe] WITHOUT [data]'s IOException rescue (see [BaseConfig.observePreservingErrors]): + * an unreadable store THROWS instead of reading as "no identity". [observe] completes + * after such a read; collect this with a retry (`retryReadErrors`) for a subscription + * that must survive a transient failure and fail closed while it lasts. + */ + fun observePreservingErrors(): Flow = dataPreservingErrors.map(::identityDataFrom) + suspend fun loadBase() : BlockchainIdentityBaseData { return identityBaseData.first() } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt index 275ea69627..de61af0cd9 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -29,12 +29,15 @@ import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -42,6 +45,8 @@ import org.dash.wallet.common.money.Coin import org.dash.wallet.common.payments.parsers.AddressNetwork import org.dash.wallet.common.payments.parsers.PaymentURI import org.dash.wallet.common.services.analytics.AnalyticsService +import org.dash.wallet.common.util.readRetryDelayMs +import org.dash.wallet.common.util.retryReadErrors import org.slf4j.LoggerFactory import javax.inject.Inject @@ -115,7 +120,8 @@ class ReceiveViewModel internal constructor( identityConfig: BlockchainIdentityConfig, dashPayConfig: DashPayConfig, private val analytics: AnalyticsService, - private val supportsPlatform: Boolean + private val supportsPlatform: Boolean, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs ) : ViewModel() { @Inject @@ -130,6 +136,24 @@ class ReceiveViewModel internal constructor( companion object { private val log = LoggerFactory.getLogger(ReceiveViewModel::class.java) + /** + * The identity, or null while it cannot be read: [BlockchainIdentityConfig.observe] + * turns a failed read into "no identity" and then completes, so one transient failure + * would hide the Identity tab for good. This keeps the read alive with + * [retryReadErrors] and emits null (no identity, no username) while it fails. + */ + internal fun identityFlow( + identityConfig: BlockchainIdentityConfig, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs + ): Flow = identityConfig.observePreservingErrors() + .map { it } + .retryReadErrors(null, retryDelayMs) { e, attempt -> + // never the identity itself: only that the read failed + log.warn("identity read failed (attempt {}); withholding the Identity tab", attempt, e) + } + // repeated failures each emit null: one is enough + .distinctUntilChanged() + /** The balance tabs to show, in display order. */ @VisibleForTesting fun tabsFor(supportsPlatform: Boolean, shieldedEnabled: Boolean, hasUsername: Boolean): List = @@ -214,18 +238,20 @@ class ReceiveViewModel internal constructor( } .launchIn(viewModelScope) - // Same wiring as PaymentsViewModel's profile observer. - identityConfig.observe() + // Same wiring as PaymentsViewModel's profile observer, but fail closed and retried: a + // failed identity read withholds the Identity tab and the username (null below) until a + // later read succeeds, instead of reading as "no identity" for the rest of this screen. + identityFlow(identityConfig, retryDelayMs) .onEach { data -> val previousId = identity?.userId identity = data applyTabs() - if (_uiState.value.selectedTab == ReceiveBalanceTab.IDENTITY && previousId != data.userId) { + if (_uiState.value.selectedTab == ReceiveBalanceTab.IDENTITY && previousId != data?.userId) { load(ReceiveBalanceTab.IDENTITY, force = true) } } .flatMapLatest { data -> - val userId = data.userId + val userId = data?.userId if (userId != null && data.hasUsername) { platformRepo.observeProfileByUserId(userId) } else { diff --git a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt index 0a7413d97e..aa629708c2 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt @@ -32,7 +32,9 @@ import io.mockk.mockk import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.take @@ -70,6 +72,10 @@ class ReceiveViewModelTest { private val shieldedFlag = MutableStateFlow(false) private val identity = MutableStateFlow(identityData(hasUsername = false)) + /** What the view model's identity read collects; [identity] unless a test fails it. */ + private var identitySource: Flow = identity + private val mainDispatcher = UnconfinedTestDispatcher() + private var coreAddress: String? = CORE_ADDRESS private val reads = mutableListOf() @@ -81,7 +87,7 @@ class ReceiveViewModelTest { @Before fun setUp() { - Dispatchers.setMain(UnconfinedTestDispatcher()) + Dispatchers.setMain(mainDispatcher) } @After @@ -106,7 +112,7 @@ class ReceiveViewModelTest { every { observeProfileByUserId(any()) } returns flowOf(null) } val identityConfig = mockk { - every { observe() } returns identity + every { observePreservingErrors() } returns identitySource } val dashPayConfig = mockk { every { observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) } returns shieldedFlag @@ -180,6 +186,76 @@ class ReceiveViewModelTest { assertEquals(CORE_ADDRESS, state.address) } + @Test + fun `a failed identity read withholds the Identity tab until a retry reads it`() { + identity.value = identityData(hasUsername = true) + var attempts = 0 + identitySource = flow { + attempts++ + if (attempts <= 2) throw IOException("datastore") + emitAll(identity) + } + val viewModel = buildViewModel(supportsPlatform = false) + viewModel.refresh() + + // failing: no Identity tab, no username, and Core is not reloaded by the fallback + assertEquals(1, attempts) + assertEquals(listOf(CORE), viewModel.uiState.value.tabs) + assertNull(viewModel.uiState.value.username) + val coreReads = reads.count { it == CORE } + + mainDispatcher.scheduler.advanceTimeBy(5_001) + assertEquals(2, attempts) + assertEquals(listOf(CORE), viewModel.uiState.value.tabs) + assertNull(viewModel.uiState.value.username) + assertEquals(coreReads, reads.count { it == CORE }) + + // the read recovers on the same view model + mainDispatcher.scheduler.advanceTimeBy(10_001) + assertEquals(3, attempts) + assertEquals(listOf(CORE, IDENTITY), viewModel.uiState.value.tabs) + assertEquals("johndoe", viewModel.uiState.value.username) + assertEquals(CORE, viewModel.uiState.value.selectedTab) + assertEquals(coreReads, reads.count { it == CORE }) + } + + @Test + fun `a failed identity read while Identity is selected falls back to Core, which stays after recovery`() { + identity.value = identityData(hasUsername = true) + val fail = CompletableDeferred() + var attempts = 0 + identitySource = flow { + attempts++ + if (attempts == 1) { + emit(identity.value) + fail.await() + throw IOException("datastore") + } + emitAll(identity) + } + val viewModel = buildViewModel(supportsPlatform = false) + viewModel.selectTab(IDENTITY) + assertEquals(IDENTITY, viewModel.uiState.value.selectedTab) + assertEquals(IDENTITY_ID, viewModel.uiState.value.address) + + fail.complete(Unit) + var state = viewModel.uiState.value + assertEquals(listOf(CORE), state.tabs) + assertEquals(CORE, state.selectedTab) + assertEquals(CORE_ADDRESS, state.address) + assertNull(state.username) + val coreReads = reads.count { it == CORE } + + mainDispatcher.scheduler.advanceTimeBy(5_001) + state = viewModel.uiState.value + assertEquals(2, attempts) + assertEquals(listOf(CORE, IDENTITY), state.tabs) + assertEquals(CORE, state.selectedTab) + assertEquals(CORE_ADDRESS, state.address) + assertEquals("johndoe", state.username) + assertEquals(coreReads, reads.count { it == CORE }) + } + // ── switching tabs ─────────────────────────────────────────────────────── @Test