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/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/receive/ReceiveInfoView.kt b/common/src/main/java/org/dash/wallet/common/ui/receive/ReceiveInfoView.kt index 307520836a..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 @@ -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,26 +229,26 @@ 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)) } 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/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..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 @@ -23,27 +23,37 @@ 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 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 +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 import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource 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.LayoutDirection +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import org.dash.wallet.common.R import org.dash.wallet.common.ui.components.DashWalletTheme @@ -73,7 +83,31 @@ 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, + // 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, + // 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 @@ -88,6 +122,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) } @@ -96,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 @@ -110,7 +147,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 @@ -126,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, @@ -152,7 +185,7 @@ fun SegmentedPicker( } ) // Draw dividers between options - if (isHorizontal) { + if (isHorizontal && style.showDividers) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly @@ -174,10 +207,9 @@ fun SegmentedPicker( // Draw the animated selection indicator if (containerSize > 0 && showSelection) { - Surface( - shape = RoundedCornerShape((style.cornerRadius - 2).dp), + SelectionThumb( + style = style, color = thumbColor, - shadowElevation = style.shadowElevation.dp, modifier = Modifier .then( if (isHorizontal) { @@ -192,7 +224,7 @@ fun SegmentedPicker( .offset(y = animatedPosition) } ) - ) { } + ) } // Draw the options @@ -213,7 +245,9 @@ fun SegmentedPicker( }, modifier = Modifier.weight(1f), paddingHorizontal = style.optionPaddingHorizontal.dp, - paddingVertical = style.optionPaddingVertical.dp + paddingVertical = style.optionPaddingVertical.dp, + iconAboveTitle = style.iconAboveTitle, + unselectedContentAlpha = style.unselectedContentAlpha ) } } @@ -235,7 +269,147 @@ fun SegmentedPicker( modifier = Modifier.weight(1f), isHorizontal = false, paddingHorizontal = style.optionPaddingHorizontal.dp, - paddingVertical = style.optionPaddingVertical.dp + paddingVertical = style.optionPaddingVertical.dp, + iconAboveTitle = style.iconAboveTitle, + unselectedContentAlpha = style.unselectedContentAlpha + ) + } + } + } + } +} + +/** + * [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. [SegmentedPickerStyle.contentPaddingHorizontal] insets + * the scrolling content, and [SegmentedPickerStyle.edgeFadeFraction] fades the row's ends. + */ +@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" + ) + + 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 } + .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 + } + ) + .clip(RoundedCornerShape(style.cornerRadius.dp)) + .background(backgroundColor) + .padding(style.containerPadding.dp) + .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. 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() + .padding(horizontal = style.contentPaddingHorizontal.dp) + ) { + if (showSelection && selectedBounds != null) { + 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 + .align(AbsoluteAlignment.TopLeft) + .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() + ) + } + 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() + // 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 + } + }, + paddingHorizontal = style.optionPaddingHorizontal.dp, + paddingVertical = style.optionPaddingVertical.dp, + iconAboveTitle = style.iconAboveTitle, + unselectedContentAlpha = style.unselectedContentAlpha ) } } @@ -243,6 +417,17 @@ fun SegmentedPicker( } } +/** 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, @@ -252,7 +437,9 @@ private fun OptionContent( modifier: Modifier = Modifier, isHorizontal: Boolean = true, paddingHorizontal: Dp = 0.dp, - paddingVertical: Dp = 0.dp + paddingVertical: Dp = 0.dp, + iconAboveTitle: Boolean = false, + unselectedContentAlpha: Float = 0.4f ) { Box( modifier = modifier @@ -263,30 +450,48 @@ 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) + tint = if (isSelected) Color.Unspecified else colors.textPrimary.copy(alpha = unselectedContentAlpha), + modifier = iconModifier ) } - + } + 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 ) } + 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 df85a56218..01c6294356 100644 --- a/wallet/res/navigation/nav_home.xml +++ b/wallet/res/navigation/nav_home.xml @@ -162,6 +162,52 @@ app:popExitAnim="@anim/slide_out_left" /> + + + + + + + + + + + + + + + + + tools:layout="@layout/fragment_receive"> + + + + + tools:layout="@layout/fragment_receive"> + + + + \ No newline at end of file diff --git a/wallet/res/values/strings.xml b/wallet/res/values/strings.xml index 864c7fc0c1..41126b501d 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -505,5 +505,20 @@ Current Identity Balance: %1$s unavailable This request was paid before, but that payment was never confirmed. Confirming sends the same payment again, so you cannot be charged twice. + + 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 Revoke access 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/service/platform/sdk/ShieldedBalanceService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt index 99b509bd8b..44764ff82d 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,17 @@ interface ShieldedBalanceService { */ suspend fun shieldedReceiveAddress(): String? + /** + * 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? + /** * 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..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) @@ -2050,6 +2070,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.unusedPlatformAddressOrNull(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/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/main/MainActivityExt.kt b/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt index 020c00f093..047eb111a4 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt @@ -55,6 +55,8 @@ import com.google.android.material.bottomnavigation.BottomNavigationView import de.schildbach.wallet.WalletBalanceWidgetProvider import de.schildbach.wallet.ui.LockScreenActivity import de.schildbach.wallet.ui.more.MoreFragment +import de.schildbach.wallet.ui.payments.isPaymentsDestination +import de.schildbach.wallet.ui.payments.paymentsRoute import de.schildbach.wallet_test.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -114,10 +116,13 @@ object MainActivityExt { } R.id.paymentsFragment -> { 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 d6b1156765..7aee8e4273 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/MainViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/MainViewModel.kt @@ -262,6 +262,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 8872a454d9..033267872e 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt @@ -56,6 +56,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.transactions.TaxCategoryExplainerDialogFragment @@ -377,6 +378,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) + 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 -> { @@ -404,29 +418,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..4ed4f400ad --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -0,0 +1,271 @@ +/* + * 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.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.mutableStateOf +import androidx.compose.runtime.remember +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.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +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.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 / 7062:49303): a + * Receive / Internal / Send picker right under the status bar, above the bottom + * 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. 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. + * + * 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) { + + 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() + + /** + * 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) + 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() + } + } + + // Attached by showTabs once the first tab set is in, not here: see there. + val adapter = TabsAdapter(this, source = arguments?.getString(ARG_SOURCE) ?: "") + // 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) { + val tabId = adapter.tabIds.getOrNull(position) ?: return + 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) + // 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) + } + + 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) + } + + @Composable + private fun Header() { + val colors = LocalDashColors.current + 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) + } + } + + /** + * 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 -> AdvancedReceiveFragment.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..eb33b9b6ee --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt @@ -0,0 +1,98 @@ +/* + * 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.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.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 + +/** + * @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 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 [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( + shieldedFlag: Flow, + onError: (Throwable, Long) -> Unit = { _, _ -> }, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +): Flow = shieldedFlag + .map { it == true } + .retryReadErrors(false, retryDelayMs, onError) + .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/AdvancedReceiveFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt new file mode 100644 index 0000000000..4f20fee881 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedReceiveFragment.kt @@ -0,0 +1,122 @@ +/* + * 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() + } + } + } + + /** + * Core opens the amount screen as it always has: [ReceiveFragment] reads a fresh address + * 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() + // 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(requestBalance = tab.name) + } + viewModel.logEvent(AnalyticsConstants.SendReceive.SPECIFY_AMOUNT) + navController.navigate(directions) + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt index b2831ff0e4..177dff390b 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,10 +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() - if (destination?.className == PaymentsFragment::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 new file mode 100644 index 0000000000..638dd45d75 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsRoute.kt @@ -0,0 +1,62 @@ +/* + * 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, 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]). + */ +enum class PaymentsRoute( + @IdRes val destinationId: 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) } + 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): PaymentsRoute = + if (advancedMode) PaymentsRoute.ADVANCED else PaymentsRoute.BASIC + +/** + * 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/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt new file mode 100644 index 0000000000..b7ae7f18ec --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveAddressSources.kt @@ -0,0 +1,143 @@ +/* + * 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.service.platform.sdk.ShieldedBalanceService +import kotlinx.coroutines.CancellationException +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() } + ) +} + +/** 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 68d92c4bae..517380c849 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 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, + 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 @@ -71,24 +95,45 @@ class ReceiveDetailsDialog : OffsetDialogFragment(R.layout.dialog_receive_detail override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - requireArguments().apply { + 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? 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..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,35 +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) + // 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 - // 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/ReceivePage.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt new file mode 100644 index 0000000000..910f33fef6 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceivePage.kt @@ -0,0 +1,370 @@ +/* + * 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.graphics.Bitmap +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.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +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.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 +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 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 +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: (tab: ReceiveBalanceTab, address: String?) -> Unit, + 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 + navBarClearance) + ) { + 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, + isEnabled = address != null, + onClick = { address?.let(onShareAddress) } + ) + 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) } + ) + } + } + } +} + +/** 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 + 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. + * 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, + selectedTab: ReceiveBalanceTab, + onSelectTab: (ReceiveBalanceTab) -> Unit +) { + val colors = LocalDashColors.current + // 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 + .padding(vertical = 20.dp) + .fillMaxWidth() + .height(40.dp), + selectedIndex = tabs.indexOf(selectedTab).coerceAtLeast(0), + style = SegmentedPickerStyle( + backgroundColor = Color.Transparent, + // segment/bg: Gray300 at 15%. + thumbColor = colors.gray300.copy(alpha = 0.15f), + cornerRadius = 12f, + thumbCornerRadius = 12f, + containerPadding = 0f, + shadowElevation = 0, + showDividers = false, + textStyle = MyTheme.Typography.BodyMediumSemibold, + optionPaddingHorizontal = 20f, + 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) + } +} + +/** 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 = rememberQrBitmap(payload) + val imageBitmap = remember(bitmap) { bitmap?.asImageBitmap() } + when { + imageBitmap != null -> { + val description = stringResource(R.string.receive_qr_code_description) + Image( + bitmap = imageBitmap, + contentDescription = description, + colorFilter = ColorFilter.tint(Color.Black, BlendMode.SrcIn), + filterQuality = FilterQuality.None, + 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) + ) + } + } +} + +/** + * 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) { + 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.Callout, 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, + // Figma: a 15dp glyph in a 20dp slot with a 5% outset. + modifier = Modifier.size(16.5.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", + 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..de61af0cd9 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -0,0 +1,349 @@ +/* + * 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.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 +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 + +/** 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 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 loading: Boolean = true, + val username: String? = null +) { + /** + * 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 + 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 + * 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 + 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, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +) : 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 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 = + 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 ([AddressNetwork.fromDashAddress] rejects them), 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 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=`, 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 PaymentURI.convertToPaymentURI(walletNetwork, address, amount, null, null) + } + + /** [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 + } + } + + 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 { + // 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() + } + .launchIn(viewModelScope) + + // 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) { + 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, loading = true) } + 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 { it.copy(username = username) } + } + + private fun applyTabs() { + val tabs = tabsFor(supportsPlatform, shieldedEnabled, hasUsername()) + // 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() + if (lostSelection) { + 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 — 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() + } 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 { + // 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 + } + } + } + } +} 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) ) } 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..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 @@ -1463,6 +1466,51 @@ class ShieldedBalanceServiceTest { assertNull(service(source).shieldedReceiveAddress()) } + @Test + 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 + 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 { + unusedPlatformAddress = { 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/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/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) + } +} 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..eedffa91fb --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsRouteTest.kt @@ -0,0 +1,71 @@ +/* + * 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 { + @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.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) + assertEquals(R.anim.slide_in_bottom, route.enterAnim) + assertEquals(R.anim.slide_out_bottom, route.popExitAnim) + } + + @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/ui/payments/ReceiveViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt new file mode 100644 index 0000000000..aa629708c2 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/ReceiveViewModelTest.kt @@ -0,0 +1,528 @@ +/* + * 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.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 +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.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 +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)) + + /** 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() + + 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(mainDispatcher) + } + + @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 { observePreservingErrors() } returns identitySource + } + 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 = 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) + } + + @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 + 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 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( + 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 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, loading = false).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 + 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)) + } +} diff --git a/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt b/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt index d9c4f4e28e..cefd62ac02 100644 --- a/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt @@ -203,6 +203,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() { @@ -552,6 +553,54 @@ 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, + 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,