From e475d571ec9d68faf06e455f3dfe66d2e4341f1b Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sat, 7 Nov 2026 00:11:25 -0800 Subject: [PATCH 01/17] feat(payments): Internal transfers between own balances in Advanced mode (MO-1125) The Advanced payments Internal tab is now an internal-transfer screen (Figma DashPay iOS 3333:10699): pick From and To among Core, Shielded, Platform and Identity, enter an amount (DASH or fiat, Max), and confirm through the same confirm/sending/result UI as External Send. No address is entered: the transfer pays the wallet's own destination for the To balance; transfers to Core use an unadvertised internal-chain address. Supported now: Core->Shielded (self-shield), Core->Identity, Shielded->Core/Platform/Identity, Platform->Shielded (self-shield), Platform->Identity, Identity->Core/Platform. Core->Platform, Platform->Core and Identity->Shielded show as not available yet (no app wrapper / SDK support). History entry (AC14) is deferred. - InternalTransferModels/Service/ServiceImpl: pair matrix, own destination resolution (fail closed), wallet-id pinning, routes. - InternalTransferExecutor: application-scoped with its own durable in-flight marker, sibling of ExternalSendExecutor. - Shared confirm components moved out of ExternalSendScreen. - Internal tab always shown in Advanced mode; basic mode unchanged. Co-Authored-By: Claude Opus 5.5 --- wallet/res/drawable/ic_swap_up_down.xml | 35 ++ wallet/res/values/strings.xml | 11 + .../schildbach/wallet/di/PlatformSdkModule.kt | 7 + .../platform/sdk/ExternalSendModels.kt | 8 + .../platform/sdk/ExternalSendService.kt | 18 + .../platform/sdk/ExternalSendServiceImpl.kt | 58 +- .../platform/sdk/InternalTransferModels.kt | 130 +++++ .../platform/sdk/InternalTransferService.kt | 72 +++ .../sdk/InternalTransferServiceImpl.kt | 403 ++++++++++++++ .../platform/sdk/ShieldedBalanceService.kt | 18 + .../sdk/ShieldedBalanceServiceImpl.kt | 22 +- .../wallet/ui/dashpay/utils/DashPayConfig.kt | 7 + .../ui/payments/AdvancedPaymentsFragment.kt | 12 +- .../ui/payments/AdvancedPaymentsViewModel.kt | 56 +- .../internal/InternalTransferExecutor.kt | 225 ++++++++ .../internal/InternalTransferFragment.kt | 99 ++++ .../internal/InternalTransferScreen.kt | 502 ++++++++++++++++++ .../internal/InternalTransferViewModel.kt | 497 +++++++++++++++++ .../ui/payments/send/ExternalSendExecutor.kt | 19 +- .../ui/payments/send/ExternalSendScreen.kt | 346 ++---------- .../ui/payments/send/SendConfirmComponents.kt | 381 +++++++++++++ .../sdk/InternalTransferModelsTest.kt | 110 ++++ .../sdk/InternalTransferServiceImplTest.kt | 351 ++++++++++++ .../ui/payments/AdvancedPaymentsTabsTest.kt | 66 +-- .../internal/InternalTransferViewModelTest.kt | 378 +++++++++++++ .../send/ExternalSendViewModelTest.kt | 2 + 26 files changed, 3391 insertions(+), 442 deletions(-) create mode 100644 wallet/res/drawable/ic_swap_up_down.xml create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/SendConfirmComponents.kt create mode 100644 wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt create mode 100644 wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt diff --git a/wallet/res/drawable/ic_swap_up_down.xml b/wallet/res/drawable/ic_swap_up_down.xml new file mode 100644 index 0000000000..98a264d5e3 --- /dev/null +++ b/wallet/res/drawable/ic_swap_up_down.xml @@ -0,0 +1,35 @@ + + + + + + diff --git a/wallet/res/values/strings.xml b/wallet/res/values/strings.xml index 8d7db1bf60..c6f04dc5ae 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -591,5 +591,16 @@ Your payment may have gone through. Do not send it again; your balances will update after the next sync. Payment not completed The payment could not be completed. The funds will arrive in your Shielded balance instead; the recipient was not paid. + + Transfer from + Transfer to + Change the balance to transfer from + Change the balance to transfer to + Swap the From and To balances + Not available yet + Insufficient balance + Withdrawals from your Identity balance to Core are not instant and take some time + Transfer in progress + Your funds left your Core balance and will arrive in your Shielded balance automatically. Do not transfer them again. This address is not available right now diff --git a/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt b/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt index 0c987457f4..4b09ee474b 100644 --- a/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt +++ b/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt @@ -29,6 +29,8 @@ import de.schildbach.wallet.service.platform.sdk.DashSdkService import de.schildbach.wallet.service.platform.sdk.DashSdkServiceImpl import de.schildbach.wallet.service.platform.sdk.ExternalSendService import de.schildbach.wallet.service.platform.sdk.ExternalSendServiceImpl +import de.schildbach.wallet.service.platform.sdk.InternalTransferService +import de.schildbach.wallet.service.platform.sdk.InternalTransferServiceImpl import de.schildbach.wallet.service.platform.sdk.PlatformMnemonicProvider import de.schildbach.wallet.service.platform.sdk.SdkMessageSigner import de.schildbach.wallet.service.platform.sdk.SecurityGuardMnemonicProvider @@ -83,6 +85,11 @@ abstract class PlatformSdkModule { @Binds abstract fun bindExternalSendService(service: ExternalSendServiceImpl): ExternalSendService + /** Advanced-mode Internal Transfers (MO-1125): own-balance moves over the External Send routes. */ + @Singleton + @Binds + abstract fun bindInternalTransferService(service: InternalTransferServiceImpl): InternalTransferService + /** * The SDK message-signing seam behind * [de.schildbach.wallet.security.SecurityFunctions.signMessage] (the diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 84713e9388..ce90b4d64b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -316,6 +316,14 @@ private fun detectCoreDashUri(input: String, network: AddressNetwork): Destinati } } +/** The kind of balance [destination] is paid into. */ +fun balanceKindOf(destination: SendDestination): SendBalance = when (destination) { + is SendDestination.Core -> SendBalance.CORE + is SendDestination.Shielded -> SendBalance.SHIELDED + is SendDestination.Platform -> SendBalance.PLATFORM + is SendDestination.Identity -> SendBalance.IDENTITY +} + /** Whether a pair can be sent, and if not, why (the UI maps each to its own copy). */ enum class SendSupport { SUPPORTED, diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt index 0cef4b83e0..b1122b533c 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -83,6 +83,14 @@ sealed class ExternalSendResult { * user's OWN shielded balance instead; the recipient is not paid. Terminal; no retry. */ object InterruptedFundsReturnToShielded : ExternalSendResult() + + /** + * Internal transfer Core → own Shielded only ([InternalTransferService]): the L1 asset lock + * went out and the wallet's pending-shield sweep finishes the shield to the user's own + * shielded balance ([ShieldFromWalletOutcome.SHIELD_PENDING_RETRY]). Funds are not lost + * and nothing must be sent again. Terminal; no retry. + */ + object CompletesAutomatically : ExternalSendResult() } /** @@ -124,6 +132,16 @@ interface ExternalSendService { /** Fee for this exact send, or null when it cannot be known before the send (never fabricated). */ suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? + /** + * [estimateFee] for a destination of the balance kind [destinationKind]: every estimate + * depends only on the pair, never on the address, so the internal transfer + * ([InternalTransferService]) can show it before its own destination is resolved. + */ + suspend fun estimateFeeForPair(source: SendBalance, destinationKind: SendBalance, amount: Dash): FeeEstimate? + + /** [maxSendable] for a destination of the balance kind [destinationKind] (see [estimateFeeForPair]). */ + suspend fun maxSendableForPair(source: SendBalance, destinationKind: SendBalance): Dash? + /** * The Max amount, or null when unknown: for Core → Core the whole spendable balance, * GROSS of the drain fee (the drain delivers it minus the fee); for every other pair the diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 8b67a4514e..eb84fed05d 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -281,6 +281,15 @@ internal fun Flow.retryReadErrors( } } +/** + * The user's registered identity id from the identity record ([id] and its creation [state]), + * null when there is none yet; an unknown creation state throws (unknown, not "none"). + */ +internal fun ownRegisteredIdentity(id: String?, state: String?): String? { + val creation = IdentityCreationState.valueOf(state ?: IdentityCreationState.NONE.name) + return id?.takeIf { it.isNotBlank() && creation >= IdentityCreationState.IDENTITY_REGISTERED } +} + private val retryLog = LoggerFactory.getLogger("de.schildbach.wallet.service.platform.sdk.ExternalSendRetry") /** @@ -513,11 +522,7 @@ internal class DashSdkExternalSendSource( ) { id, state -> Result.success(ownIdentity(id, state)) } .retryReadErrors("identity record", Result.failure(IllegalStateException("identity record unreadable"))) - /** A registered identity; an unknown creation state throws (unknown, not "none"). */ - private fun ownIdentity(id: String?, state: String?): String? { - val creation = IdentityCreationState.valueOf(state ?: IdentityCreationState.NONE.name) - return id?.takeIf { it.isNotBlank() && creation >= IdentityCreationState.IDENTITY_REGISTERED } - } + private fun ownIdentity(id: String?, state: String?): String? = ownRegisteredIdentity(id, state) override suspend fun managedIdentityIds(walletIdHex: String): List = wallet(walletIdHex).inMemoryIdentityStates().filter { !it.watched }.map { it.identityId } @@ -927,8 +932,15 @@ class ExternalSendServiceImpl internal constructor( } override suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? = + estimateFeeForPair(source, balanceKindOf(destination), amount) + + override suspend fun estimateFeeForPair( + source: SendBalance, + destinationKind: SendBalance, + amount: Dash + ): FeeEstimate? = try { - withContext(ioDispatcher) { estimateFeeInner(source, destination) } + withContext(ioDispatcher) { estimateFeeInner(source, destinationKind) } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -955,17 +967,17 @@ class ExternalSendServiceImpl internal constructor( * fee of the asset unlock comes out of the amount on top; Platform/Identity → Shielded * add the shielded compute fee to the metered one.) */ - private suspend fun estimateFeeInner(source: SendBalance, destination: SendDestination): FeeEstimate? = + private suspend fun estimateFeeInner(source: SendBalance, destination: SendBalance): FeeEstimate? = when (source) { SendBalance.CORE -> when (destination) { - is SendDestination.Core -> FeeEstimate(Dash(coreSendFeeReserveDuffs()), exact = false) - is SendDestination.Shielded -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { + SendBalance.CORE -> FeeEstimate(Dash(coreSendFeeReserveDuffs()), exact = false) + SendBalance.SHIELDED -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { FeeEstimate(Dash(shieldPoolFeeDuffs(it)), exact = false) } - is SendDestination.Platform -> this.source.spendableUtxoCount()?.let { + SendBalance.PLATFORM -> this.source.spendableUtxoCount()?.let { FeeEstimate(Dash(coreToPlatformFeeDuffs(it)), exact = false) } - is SendDestination.Identity -> null + SendBalance.IDENTITY -> null } SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destination))?.let { FeeEstimate(Dash(ceilCreditsToDuffs(it)), exact = false) @@ -986,13 +998,17 @@ class ExternalSendServiceImpl internal constructor( * retries once with the exact deficit the note selection reports. * - Everything else: null (no pre-send fee figure). */ - override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = try { + override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = + maxSendableForPair(source, balanceKindOf(destination)) + + override suspend fun maxSendableForPair(source: SendBalance, destinationKind: SendBalance): Dash? = try { + val destination = destinationKind when (source) { SendBalance.CORE -> when (destination) { - is SendDestination.Core -> withContext(ioDispatcher) { coreToCoreMaxDuffs() }?.let(::Dash) - is SendDestination.Shielded -> withContext(ioDispatcher) { coreToShieldedMaxDuffs() }?.let(::Dash) - is SendDestination.Platform -> withContext(ioDispatcher) { coreToPlatformMaxDuffsOrNull() }?.let(::Dash) - is SendDestination.Identity -> null + SendBalance.CORE -> withContext(ioDispatcher) { coreToCoreMaxDuffs() }?.let(::Dash) + SendBalance.SHIELDED -> withContext(ioDispatcher) { coreToShieldedMaxDuffs() }?.let(::Dash) + SendBalance.PLATFORM -> withContext(ioDispatcher) { coreToPlatformMaxDuffsOrNull() }?.let(::Dash) + SendBalance.IDENTITY -> null } SendBalance.SHIELDED -> { val balance = this.source.observeShieldedBalance().first() @@ -1785,11 +1801,11 @@ class ExternalSendServiceImpl internal constructor( is SendDestination.Identity -> "Identity" } - private fun shieldedKindFor(destination: SendDestination): ShieldedFeeKind = when (destination) { - is SendDestination.Core -> ShieldedFeeKind.WITHDRAWAL - is SendDestination.Shielded -> ShieldedFeeKind.TRANSFER - is SendDestination.Platform -> ShieldedFeeKind.UNSHIELD - is SendDestination.Identity -> ShieldedFeeKind.IDENTITY_TOP_UP + private fun shieldedKindFor(destination: SendBalance): ShieldedFeeKind = when (destination) { + SendBalance.CORE -> ShieldedFeeKind.WITHDRAWAL + SendBalance.SHIELDED -> ShieldedFeeKind.TRANSFER + SendBalance.PLATFORM -> ShieldedFeeKind.UNSHIELD + SendBalance.IDENTITY -> ShieldedFeeKind.IDENTITY_TOP_UP } } } diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt new file mode 100644 index 0000000000..baeda4baae --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt @@ -0,0 +1,130 @@ +/* + * 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.service.platform.sdk + +// Pure, host-testable model of the Advanced-mode "Internal Transfers" (MO-1125): moving +// funds between the user's OWN balances. No native, no Android, no I/O. + +/** Whether a From → To pair of own balances can be transferred, and if not, why. */ +enum class InternalTransferSupport { + SUPPORTED, + + /** From and To are the same balance: never allowed. */ + SAME_BALANCE, + + /** The SDK (or the wallet) cannot do this pair yet: shown disabled, "not available yet". */ + NOT_SUPPORTED_YET, + + /** One side is the Shielded balance and the shielded feature is off (or unreadable). */ + SHIELDED_OFF, + + /** One side is the Identity balance and the user has no identity (or it is unknown). */ + NO_IDENTITY +} + +/** + * The one pair matrix of the internal transfer, enforced by the UI AND by + * [InternalTransferService.transfer]: + * + * | From \ To | Core | Shielded | Platform | Identity | + * |---|---|---|---|---| + * | Core | — | yes | no (1) | yes | + * | Shielded | yes | — | yes | yes | + * | Platform | no (2) | yes | — | yes | + * | Identity | yes | no (3) | yes | — | + * + * 1. The Platform-address funding from an asset lock is not wired for this flow yet. + * 2. The SDK's Platform-address withdrawal only withdraws the full balance. + * 3. `shieldedShieldFromIdentity` (Type 21) is not bound in the wallet yet. + * + * [shieldedEnabled] and [hasIdentity] are the error-preserving reads: unknown is false. + */ +fun internalTransferSupport( + from: SendBalance, + to: SendBalance, + shieldedEnabled: Boolean, + hasIdentity: Boolean +): InternalTransferSupport { + if (from == to) return InternalTransferSupport.SAME_BALANCE + if (!internalTransferPairSupported(from, to)) return InternalTransferSupport.NOT_SUPPORTED_YET + if ((from == SendBalance.SHIELDED || to == SendBalance.SHIELDED) && !shieldedEnabled) { + return InternalTransferSupport.SHIELDED_OFF + } + if ((from == SendBalance.IDENTITY || to == SendBalance.IDENTITY) && !hasIdentity) { + return InternalTransferSupport.NO_IDENTITY + } + return InternalTransferSupport.SUPPORTED +} + +/** The bare matrix of [internalTransferSupport]: whether the wallet can move [from] → [to] at all. */ +fun internalTransferPairSupported(from: SendBalance, to: SendBalance): Boolean = when (from) { + SendBalance.CORE -> to == SendBalance.SHIELDED || to == SendBalance.IDENTITY + SendBalance.SHIELDED -> to != SendBalance.SHIELDED + SendBalance.PLATFORM -> to == SendBalance.SHIELDED || to == SendBalance.IDENTITY + SendBalance.IDENTITY -> to == SendBalance.CORE || to == SendBalance.PLATFORM +} + +/** + * The balances the From / To pickers list, in order. Identity only for a user known to have + * an identity ([hasIdentity] true); unknown hides it. Shielded is always listed: when the + * feature is off it shows disabled. + */ +fun internalTransferBalances(hasIdentity: Boolean?): List = + SendBalance.entries.filter { it != SendBalance.IDENTITY || hasIdentity == true } + +/** An ordered pair of own balances; [from] != [to] always. [toString] carries no amounts or ids. */ +data class InternalTransferPair(val from: SendBalance, val to: SendBalance) { + init { + require(from != to) { "an internal transfer needs two different balances" } + } + + /** The swap button (AC3): From and To exchange. */ + fun swapped(): InternalTransferPair = InternalTransferPair(to, from) + + /** Pick [balance] as From; picking the current To swaps the two (AC4). */ + fun withFrom(balance: SendBalance): InternalTransferPair = when (balance) { + from -> this + to -> swapped() + else -> copy(from = balance) + } + + /** Pick [balance] as To; picking the current From swaps the two (AC4). */ + fun withTo(balance: SendBalance): InternalTransferPair = when (balance) { + to -> this + from -> swapped() + else -> copy(to = balance) + } +} + +/** + * The pair the Internal tab opens with: From Core; To Shielded when the shielded feature is + * on, otherwise Identity when the user has one, otherwise Platform. + */ +fun defaultInternalTransferPair(shieldedEnabled: Boolean, hasIdentity: Boolean): InternalTransferPair = + InternalTransferPair( + SendBalance.CORE, + when { + shieldedEnabled -> SendBalance.SHIELDED + hasIdentity -> SendBalance.IDENTITY + else -> SendBalance.PLATFORM + } + ) + +/** Whether a transfer [from] → [to] involves a ~30 s shielded proof. */ +fun internalTransferHasShieldedLeg(from: SendBalance, to: SendBalance): Boolean = + from == SendBalance.SHIELDED || to == SendBalance.SHIELDED diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt new file mode 100644 index 0000000000..80637f1a0c --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt @@ -0,0 +1,72 @@ +/* + * 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.service.platform.sdk + +import kotlinx.coroutines.flow.Flow +import org.dash.wallet.common.money.Dash + +/** + * Advanced-mode "Internal Transfers" (MO-1125): move funds between the user's OWN balances + * ([SendBalance]) under the pair matrix [internalTransferSupport]. There is no address entry: + * the destination is always the wallet's own address for the To balance, resolved by this + * service at send time and failing closed. Basic mode does not use this. + * + * Results reuse [ExternalSendResult] / [NotSentReason]. Nothing amount-, address- or + * identity-derived is logged. + */ +interface InternalTransferService { + /** [ExternalSendService.observeBalance]: live spendable balance of [balance]; null = unknown. */ + fun observeBalance(balance: SendBalance): Flow + + /** [ExternalSendService.observeHasIdentity]; null = could not tell (the UI hides Identity). */ + fun observeHasIdentity(): Flow + + /** + * `USE_KOTLIN_SDK_SHIELDED`, error-preserving: an unreadable flag emits false (off) and + * keeps observing. Never completes on a transient error. + */ + fun observeShieldedEnabled(): Flow + + /** [ExternalSendService.currentWalletIdOrNull]: captured, without suspending, at confirmation. */ + fun currentWalletIdOrNull(): String? + + /** The fee of a [from] → [to] transfer, null when it cannot be known before the send (never fabricated). */ + suspend fun estimateFee(from: SendBalance, to: SendBalance, amount: Dash): FeeEstimate? + + /** The Max of a [from] → [to] transfer (the balance minus the fee paid on top), null when unknown. */ + suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? + + /** + * Move [amount] from [from] to the wallet's own [to] balance. The caller has ALREADY + * authenticated and passes exactly what the user confirmed, including + * [expectedWalletIdHex] ([currentWalletIdOrNull] at confirmation). The implementation + * enforces [internalTransferSupport] itself, refuses unless that wallet is the bound one + * (re-checked right before the write), and resolves the own destination after that check; + * an unavailable destination is [NotSentReason.GENERIC] with nothing submitted. A Core + * destination is NEVER the advertised receive address. + * + * Shielded legs block for a ~30s proof: run this on an application-scoped owner. + */ + suspend fun transfer( + from: SendBalance, + to: SendBalance, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt new file mode 100644 index 0000000000..7d68af637b --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -0,0 +1,403 @@ +/* + * 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.service.platform.sdk + +import de.schildbach.wallet.data.WalletData +import de.schildbach.wallet.database.entity.BlockchainIdentityConfig +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import de.schildbach.wallet.ui.shielded.shieldedMaxFeeAdjustment +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.util.readRetryDelayMs +import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicBoolean +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Seam over everything [InternalTransferServiceImpl] touches besides [ExternalSendService], so + * the gating / own-destination / wallet-pinning orchestration is host-JVM unit-testable. + */ +internal interface InternalTransferSource { + /** [SdkL1SendService.cutoverCommittedOrThrow]: throws when unreadable. */ + suspend fun cutoverCommittedOrThrow(): Boolean + + /** `USE_KOTLIN_SDK_SHIELDED`, error-preserving: throws when unreadable. */ + suspend fun shieldedEnabledOrThrow(): Boolean + + /** `USE_KOTLIN_SDK_SHIELDED` as it changes; a read error is thrown into the flow. */ + fun observeShieldedFlag(): Flow + + /** The SDK wallet bound now (null when none, or not exactly one, is loaded). */ + suspend fun boundWalletIdOrNull(): String? + + /** The user's registered identity (base58), null when there is none; throws when unreadable. */ + suspend fun ownIdentityIdOrThrow(): String? + + /** + * The wallet's own UNADVERTISED Core address (`WalletData.unadvertisedDestinationLive`, the + * SDK engine's internal chain post-cutover), base58. Throws when none can be obtained; never + * the advertised receive address. Blocking: call off the main thread. + */ + fun unadvertisedCoreAddress(): String + + /** [ShieldedBalanceService.platformReceiveAddress]: the wallet's own Platform address, or null. */ + suspend fun ownPlatformAddress(): String? + + suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? + + suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult + suspend fun shieldFromCredits(amount: Dash, walletIdHex: String): SdkWriteResult + suspend fun unshieldToCredits(amount: Dash, walletIdHex: String): SdkWriteResult +} + +/** Production [InternalTransferSource]. */ +internal class DashSdkInternalTransferSource( + private val sdkService: DashSdkService, + private val sdkL1SendService: SdkL1SendService, + private val shieldedBalanceService: ShieldedBalanceService, + private val dashPayConfig: DashPayConfig, + private val identityConfig: BlockchainIdentityConfig, + private val walletData: WalletData +) : InternalTransferSource { + + override suspend fun cutoverCommittedOrThrow(): Boolean = sdkL1SendService.cutoverCommittedOrThrow() + + override suspend fun shieldedEnabledOrThrow(): Boolean = + dashPayConfig.getPreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) == true + + override fun observeShieldedFlag(): Flow = + flow { emitAll(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) } + + override suspend fun boundWalletIdOrNull(): String? { + sdkService.ensureStarted() + val manager = checkNotNull(sdkService.walletManagerOrNull()) { "SDK wallet manager missing after ensureStarted()" } + return manager.wallets.value.keys.singleOrNull() + } + + override suspend fun ownIdentityIdOrThrow(): String? = ownRegisteredIdentity( + identityConfig.getPreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), + identityConfig.getPreservingErrors(BlockchainIdentityConfig.CREATION_STATE) + ) + + override fun unadvertisedCoreAddress(): String = walletData.unadvertisedDestinationLive().toBase58() + + override suspend fun ownPlatformAddress(): String? = shieldedBalanceService.platformReceiveAddress() + + override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = + shieldedBalanceService.estimateShieldedFeeCredits(kind) + + override suspend fun shieldFromWallet(amount: Dash, walletIdHex: String) = + shieldedBalanceService.shieldFromWalletPinned(amount, walletIdHex) + + override suspend fun shieldFromCredits(amount: Dash, walletIdHex: String) = + shieldedBalanceService.shieldFromCreditsPinned(amount, walletIdHex) + + override suspend fun unshieldToCredits(amount: Dash, walletIdHex: String) = + shieldedBalanceService.unshieldToCreditsPinned(amount, walletIdHex) +} + +/** + * Default [InternalTransferService]. Orchestration only: every money move is either an + * [ExternalSendService.send] to the resolved OWN destination (that route's gating, pinning and + * classification apply unchanged) or one of [ShieldedBalanceService]'s pinned self routes. + * + * Routes (the 9 supported pairs of [internalTransferSupport]): + * - Core → Shielded: [ShieldedBalanceService.shieldFromWalletPinned] of `amount + pool fee` + * ([shieldPoolFeeDuffs]), so the own shielded balance receives the confirmed amount (the + * External Send's Core → Shielded convention). A lock that went out with the shield still + * pending is [ExternalSendResult.CompletesAutomatically]. + * - Core → Identity, Shielded → Identity, Platform → Identity: [ExternalSendService.send] to + * the user's own identity id. + * - Shielded → Core, Identity → Core: [ExternalSendService.send] to the UNADVERTISED Core + * address ([InternalTransferSource.unadvertisedCoreAddress]); unavailable = Not sent. + * - Shielded → Platform: [ShieldedBalanceService.unshieldToCreditsPinned] (own Platform address), + * with the shielded Max fee retry. + * - Platform → Shielded: [ShieldedBalanceService.shieldFromCreditsPinned]. + * - Identity → Platform: [ExternalSendService.send] to the wallet's own Platform address + * ([ShieldedBalanceService.platformReceiveAddress]); unavailable = Not sent. + * + * Funds safety, in order, for every [transfer]: single-flight; positive amount; the pair matrix; + * cutover committed and (for a shielded leg) the shielded flag, error-preserving; the wallet + * captured at confirmation is the bound one; the own destination is resolved (fail closed); + * the wallet is re-checked right before the write, which is pinned to it. Broadcast → Sent, + * NotBroadcast → Not sent, Ambiguous or anything unclassified → may have gone through. + */ +@Singleton +class InternalTransferServiceImpl internal constructor( + private val externalSendService: ExternalSendService, + private val source: InternalTransferSource, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val retryDelayMs: (Long) -> Long = ::readRetryDelayMs +) : InternalTransferService { + + @Inject + constructor( + externalSendService: ExternalSendService, + sdkService: DashSdkService, + sdkL1SendService: SdkL1SendService, + shieldedBalanceService: ShieldedBalanceService, + dashPayConfig: DashPayConfig, + identityConfig: BlockchainIdentityConfig, + walletData: WalletData + ) : this( + externalSendService, + DashSdkInternalTransferSource( + sdkService, sdkL1SendService, shieldedBalanceService, dashPayConfig, identityConfig, walletData + ) + ) + + private val inFlight = AtomicBoolean(false) + + // ── Reads ───────────────────────────────────────────────────────── + + override fun observeBalance(balance: SendBalance): Flow = externalSendService.observeBalance(balance) + + override fun observeHasIdentity(): Flow = externalSendService.observeHasIdentity() + + override fun observeShieldedEnabled(): Flow = + source.observeShieldedFlag() + .map { it == true } + .retryReadErrors("shielded flag", false, retryDelayMs) + .distinctUntilChanged() + + override fun currentWalletIdOrNull(): String? = externalSendService.currentWalletIdOrNull() + + /** + * Every supported pair's figure depends only on the pair, so the External Send's per-pair + * estimate applies ([ExternalSendService.estimateFeeForPair]): Core → Shielded the shield + * pool fee (on top), Shielded → * the flat single-note pool fee; Core → Identity, + * Platform → * and Identity → * are metered by Rust at execution, so null. + */ + override suspend fun estimateFee(from: SendBalance, to: SendBalance, amount: Dash): FeeEstimate? = + if (internalTransferPairSupported(from, to)) externalSendService.estimateFeeForPair(from, to, amount) else null + + /** [ExternalSendService.maxSendableForPair] for a supported pair (null for metered pairs). */ + override suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? = + if (internalTransferPairSupported(from, to)) externalSendService.maxSendableForPair(from, to) else null + + // ── Transfer ────────────────────────────────────────────────────── + + override suspend fun transfer( + from: SendBalance, + to: SendBalance, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + if (!inFlight.compareAndSet(false, true)) { + log.warn("internal transfer refused: another internal transfer is in progress") + return ExternalSendResult.NotSent(NotSentReason.IN_PROGRESS) + } + return try { + withContext(ioDispatcher) { transferInner(from, to, amount, isMax, expectedWalletIdHex) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Every pre-submission step returns its own NotSent; an exception escaping here came + // from a write path and may have submitted. + log.error("internal transfer {} → {} failed unclassified; outcome unknown", from, to, e) + ExternalSendResult.MayHaveGoneThrough + } finally { + inFlight.set(false) + } + } + + private suspend fun transferInner( + from: SendBalance, + to: SendBalance, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + val pair = "$from → $to" + if (!amount.isPositive) return notSent(pair, NotSentReason.GENERIC, "non-positive amount") + if (from == to || !internalTransferPairSupported(from, to)) { + return notSent(pair, NotSentReason.NOT_SUPPORTED, "pair not supported") + } + + // Engine ownership / flags, error-preserving. + val committed = readOrNull("cutover state") { source.cutoverCommittedOrThrow() } + ?: return notSent(pair, NotSentReason.GENERIC, "cutover state unreadable") + if (!committed) return notSent(pair, NotSentReason.NOT_SUPPORTED, "cutover not committed") + val shieldedEnabled = if (internalTransferHasShieldedLeg(from, to)) { + readOrNull("shielded flag") { source.shieldedEnabledOrThrow() } + ?: return notSent(pair, NotSentReason.GENERIC, "shielded flag unreadable") + } else { + false + } + val ownIdentityId: String? = if (from == SendBalance.IDENTITY || to == SendBalance.IDENTITY) { + val own = readOrNull("own identity") { Result.success(source.ownIdentityIdOrThrow()) } + ?: return notSent(pair, NotSentReason.GENERIC, "identity record unreadable") + own.getOrNull() + } else { + null + } + val support = internalTransferSupport(from, to, shieldedEnabled, hasIdentity = ownIdentityId != null) + if (support != InternalTransferSupport.SUPPORTED) { + return notSent(pair, NotSentReason.NOT_SUPPORTED, "pair not supported ($support)") + } + + // The wallet the user confirmed with must be the one bound now. + val walletIdHex = expectedWalletIdHex + ?: return notSent(pair, NotSentReason.GENERIC, "no SDK wallet captured at confirmation") + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + + return when (to) { + SendBalance.CORE -> { + // Never the advertised receive address (checklist 4.15): no fallback. + val address = try { + source.unadvertisedCoreAddress() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("internal transfer {}: no unadvertised Core address; not sent", pair, e) + return ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + delegate(pair, walletIdHex, from, SendDestination.Core(address), amount, isMax) + } + SendBalance.IDENTITY -> { + val id = ownIdentityId ?: return notSent(pair, NotSentReason.GENERIC, "no own identity") + delegate(pair, walletIdHex, from, SendDestination.Identity(id), amount, isMax) + } + SendBalance.PLATFORM -> when (from) { + SendBalance.SHIELDED -> unshieldToOwnPlatform(pair, walletIdHex, amount, isMax) + else -> { + val address = readOrNull("own platform address") { source.ownPlatformAddress() } + ?: return notSent(pair, NotSentReason.GENERIC, "own platform address unavailable") + delegate(pair, walletIdHex, from, SendDestination.Platform(address), amount, isMax) + } + } + SendBalance.SHIELDED -> when (from) { + SendBalance.CORE -> shieldFromOwnCore(pair, walletIdHex, amount) + else -> { + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + mapWrite(pair, source.shieldFromCredits(amount, walletIdHex)) + } + } + } + } + + /** An existing External Send route to the resolved own [destination], after a wallet re-check. */ + private suspend fun delegate( + pair: String, + walletIdHex: String, + from: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean + ): ExternalSendResult { + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + return externalSendService.send(from, destination, amount, isMax, walletIdHex) + } + + /** Self-shield of `amount + pool fee`: the own shielded balance receives [amount]. */ + private suspend fun shieldFromOwnCore(pair: String, walletIdHex: String, amount: Dash): ExternalSendResult { + val feeCredits = readOrNull("shield pool fee") { source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER) } + ?: return notSent(pair, NotSentReason.GENERIC, "shield pool fee unknown") + val lock = try { + Dash(Math.addExact(amount.duffs, shieldPoolFeeDuffs(feeCredits))) + } catch (e: ArithmeticException) { + return notSent(pair, NotSentReason.GENERIC, "amount out of range") + } + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + return when (val result = source.shieldFromWallet(lock, walletIdHex)) { + is SdkWriteResult.Broadcast -> when (result.value) { + ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) + ShieldFromWalletOutcome.SHIELD_PENDING_RETRY -> { + log.warn("internal transfer {}: lock out, shield pending — the sweep completes it", pair) + ExternalSendResult.CompletesAutomatically + } + } + else -> mapWrite(pair, result) + } + } + + /** Unshield to the own Platform address; a Max retries once with the reported fee deficit. */ + private suspend fun unshieldToOwnPlatform( + pair: String, + walletIdHex: String, + amount: Dash, + isMax: Boolean + ): ExternalSendResult { + suspend fun attempt(value: Dash): SdkWriteResult { + if (!stillBound(pair, walletIdHex)) return SdkWriteResult.NotBroadcast("the bound wallet changed") + return source.unshieldToCredits(value, walletIdHex) + } + var result = attempt(amount) + val first = result + if (isMax && first is SdkWriteResult.NotBroadcast) { + val adjustment = shieldedMaxFeeAdjustment(amount, first) + if (adjustment != null) { + log.info("internal transfer {}: max spend short by the pool fee; retrying once", pair) + result = attempt(adjustment.adjustedAmount) + } + } + return mapWrite(pair, result) + } + + private fun mapWrite(pair: String, result: SdkWriteResult<*>): ExternalSendResult = when (result) { + is SdkWriteResult.Broadcast -> { + log.info("internal transfer {}: sent", pair) + ExternalSendResult.Sent(null) + } + is SdkWriteResult.NotBroadcast -> { + val reason = notSentReasonFor(result) + log.warn("internal transfer {}: not sent ({})", pair, reason, result.cause) + ExternalSendResult.NotSent(reason) + } + is SdkWriteResult.Ambiguous -> { + log.error("internal transfer {}: outcome unconfirmed — may have gone through; do NOT retry", pair, result.cause) + ExternalSendResult.MayHaveGoneThrough + } + } + + /** Re-read the bound SDK wallet: it must still be [walletIdHex]. */ + private suspend fun stillBound(pair: String, walletIdHex: String): Boolean { + val now = readOrNull("bound wallet") { source.boundWalletIdOrNull() } + val same = now != null && now.equals(walletIdHex, ignoreCase = true) + if (!same) log.warn("internal transfer {}: the bound SDK wallet changed before submission; not sent", pair) + return same + } + + private suspend fun readOrNull(what: String, read: suspend () -> T?): T? = try { + read() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("internal transfer: {} unreadable", what, e) + null + } + + private fun notSent(pair: String, reason: NotSentReason, why: String): ExternalSendResult.NotSent { + log.info("internal transfer {}: not sent ({}: {})", pair, reason, why) + return ExternalSendResult.NotSent(reason) + } + + private companion object { + private val log = LoggerFactory.getLogger(InternalTransferServiceImpl::class.java) + } +} 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 6884c4652d..a54db7a64f 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -629,6 +629,24 @@ interface ShieldedBalanceService { expectedWalletIdHex: String ): SdkWriteResult + // ── Pinned self transfers (Advanced mode "Internal Transfers") ───── + // + // The self-only writes above, pinned to the SDK wallet [expectedWalletIdHex] the + // caller captured before its first suspension: a runtime bound to another wallet is a + // [SdkWriteResult.NotBroadcast] before anything is submitted. Same contracts otherwise. + + /** [shieldFromWallet] (self-shield, own default Orchard address), pinned to [expectedWalletIdHex]. */ + suspend fun shieldFromWalletPinned( + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** [shieldFromCredits] (Type 15, own default Orchard address), pinned to [expectedWalletIdHex]. */ + suspend fun shieldFromCreditsPinned(amount: Dash, expectedWalletIdHex: String): SdkWriteResult + + /** [unshieldToCredits] (Type 17, own Platform address), pinned to [expectedWalletIdHex]. */ + suspend fun unshieldToCreditsPinned(amount: Dash, expectedWalletIdHex: String): SdkWriteResult + /** * The consensus-pinned flat pool fee, in credits, of a single-note (2-action) * transition of [kind]; a spend selecting more notes pays more, so this is an 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 04e0e3da44..b0c4023118 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -2139,7 +2139,13 @@ class ShieldedBalanceServiceImpl internal constructor( } override suspend fun shieldFromCredits(amount: Dash): SdkWriteResult = - runShieldedWrite("shieldFromCredits", amount) { walletId, credits -> + shieldFromCreditsInternal(amount, expectedWalletIdHex = null) + + override suspend fun shieldFromCreditsPinned(amount: Dash, expectedWalletIdHex: String): SdkWriteResult = + shieldFromCreditsInternal(amount, expectedWalletIdHex) + + private suspend fun shieldFromCreditsInternal(amount: Dash, expectedWalletIdHex: String?): SdkWriteResult = + runShieldedWrite("shieldFromCredits", amount, expectedWalletIdHex) { walletId, credits -> source.shield(walletId, credits) } @@ -2184,6 +2190,12 @@ class ShieldedBalanceServiceImpl internal constructor( override suspend fun shieldFromWallet(amount: Dash): SdkWriteResult = shieldFromWalletInternal(amount, fundingPath = null) + override suspend fun shieldFromWalletPinned( + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult = + shieldFromWalletInternal(amount, fundingPath = null, expectedWalletIdHex = expectedWalletIdHex) + /** Tracked locks with [PendingWalletShieldLock.platformConsumed] applied; unreadable → none (fail closed). */ private suspend fun trackedShieldLocks(walletId: ByteArray): List { val locks = source.walletShieldLocks(walletId) @@ -2812,7 +2824,13 @@ class ShieldedBalanceServiceImpl internal constructor( } override suspend fun unshieldToCredits(amount: Dash): SdkWriteResult = - runShieldedWrite("unshieldToCredits", amount) { walletId, credits -> + unshieldToCreditsInternal(amount, expectedWalletIdHex = null) + + override suspend fun unshieldToCreditsPinned(amount: Dash, expectedWalletIdHex: String): SdkWriteResult = + unshieldToCreditsInternal(amount, expectedWalletIdHex) + + private suspend fun unshieldToCreditsInternal(amount: Dash, expectedWalletIdHex: String?): SdkWriteResult = + runShieldedWrite("unshieldToCredits", amount, expectedWalletIdHex) { walletId, credits -> val target = try { source.ownPlatformAddressOrNull(walletId) } catch (t: Throwable) { diff --git a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt index f68df92e72..3de32bc97f 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt @@ -310,6 +310,13 @@ open class DashPayConfig @Inject constructor( */ val EXTERNAL_PLATFORM_FUNDING_PENDING = stringPreferencesKey("external_platform_funding_pending") + /** + * [EXTERNAL_SEND_IN_FLIGHT] for the Advanced-mode internal transfer between the user's own + * balances ([de.schildbach.wallet.ui.payments.internal.InternalTransferExecutor]). A bare + * flag: no amount, address or id. + */ + val INTERNAL_TRANSFER_IN_FLIGHT = booleanPreferencesKey("internal_transfer_in_flight") + /** * `startedAtMillis` of the in-flight marker whose "could not confirm" * guidance the user closed. While it matches the current marker the diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt index cdb05545af..0c49274859 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -51,6 +51,7 @@ import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_IN 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.ui.payments.internal.InternalTransferFragment import de.schildbach.wallet.ui.payments.send.AdvancedSendFragment import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentAdvancedPaymentsBinding @@ -72,7 +73,8 @@ import org.dash.wallet.common.ui.viewBinding * navigation (`ShowNavBar` on the destination), over the payments pages. * * Receive is [AdvancedReceiveFragment] (the Compose [ReceivePage]), Send is - * [AdvancedSendFragment] (MO-1121); Internal is the same child page as [PaymentsFragment]'s. The enter/exit transitions are on + * [AdvancedSendFragment] (MO-1121) and Internal is [InternalTransferFragment] (MO-1125), shown + * whatever the shielded flag (see [advancedPaymentsTabIds]). 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. * @@ -238,11 +240,7 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } } - /** - * 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. - */ + /** Pages keyed by logical tab id (stable ids), so a tab-set change keeps the pages that remain. */ private class TabsAdapter( fragment: Fragment, private val source: String @@ -265,7 +263,7 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { override fun createFragment(position: Int): Fragment = when (tabIds[position]) { ACTIVE_TAB_RECEIVE -> AdvancedReceiveFragment.newInstance() - ACTIVE_TAB_INTERNAL -> PaymentsInternalFragment.newInstance() + ACTIVE_TAB_INTERNAL -> InternalTransferFragment.newInstance() else -> AdvancedSendFragment.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 index d11c074d65..caffe39695 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt @@ -18,7 +18,6 @@ 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 org.dash.wallet.common.util.readRetryDelayMs @@ -31,48 +30,37 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.retryWhen -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import org.slf4j.LoggerFactory import javax.inject.Inject /** - * @property tabIds the logical tab ids in display order (see [PaymentsFragment.tabIdsFor]), - * or null until the shielded flag has been read: the screen builds no pages until then. + * @property tabIds the logical tab ids in display order (see [advancedPaymentsTabIds]); null only + * before the first state is set (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) - } +class AdvancedPaymentsViewModel internal constructor(supportsPlatform: Boolean) : ViewModel() { + @Inject + constructor() : this(Constants.SUPPORTS_PLATFORM) - private val _uiState = MutableStateFlow(AdvancedPaymentsUIState()) + private val _uiState = MutableStateFlow(AdvancedPaymentsUIState(tabIds = advancedPaymentsTabIds(supportsPlatform))) val uiState: StateFlow = _uiState.asStateFlow() - - init { - viewModelScope.launch { - advancedPaymentsTabsFlow( - shieldedFlag = dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED), - supportsPlatform = Constants.SUPPORTS_PLATFORM, - onError = { e, attempt -> log.warn("shielded flag read failed (attempt {})", attempt, e) } - ).collect { tabIds -> - _uiState.update { it.copy(tabIds = tabIds) } - } - } - } } +/** + * The tab set for the Advanced payments screen (MO-1125): the "Internal" tab is always shown + * where Platform is supported, whatever the shielded flag — with the flag off, the Internal + * transfer shows Shielded disabled. Basic mode ([PaymentsFragment]) keeps its own gating. + */ +internal fun advancedPaymentsTabIds(supportsPlatform: Boolean): List = PaymentsFragment.tabIdsFor(supportsPlatform) + /** * The shielded flag as a never-failing flow: a failed read counts as off (as * [DashPayConfig.get] reading absent does for [PaymentsFragment]), is reported to - * [onError] and is retried, so the flow never completes on an error. Shared by the - * Advanced payments tabs ([advancedPaymentsTabsFlow]) and the Receive balance tabs. + * [onError] and is retried, so the flow never completes on an error. Used by the Receive + * balance tabs. */ internal fun shieldedEnabledFlow( shieldedFlag: Flow, @@ -87,17 +75,3 @@ internal fun shieldedEnabledFlow( true } .distinctUntilChanged() - -/** - * The tab set for the Advanced payments screen. Same gating as [PaymentsFragment]: the - * "Internal" tab needs `SUPPORTS_PLATFORM` and `USE_KOTLIN_SDK_SHIELDED`; a failed read - * hides it (see [shieldedEnabledFlow]). - */ -internal fun advancedPaymentsTabsFlow( - shieldedFlag: Flow, - supportsPlatform: Boolean, - onError: (Throwable, Long) -> Unit = { _, _ -> }, - retryDelayMs: (Long) -> Long = ::readRetryDelayMs -): Flow> = shieldedEnabledFlow(shieldedFlag, onError, retryDelayMs) - .map { PaymentsFragment.tabIdsFor(supportsPlatform && it) } - .distinctUntilChanged() diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt new file mode 100644 index 0000000000..bb67bd513d --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt @@ -0,0 +1,225 @@ +/* + * 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.internal + +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.InternalTransferService +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import de.schildbach.wallet.ui.payments.send.DashPayConfigInFlightMarker +import de.schildbach.wallet.ui.payments.send.ExternalSendInFlightMarker +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.dash.wallet.common.money.Dash +import org.slf4j.LoggerFactory +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Exactly what the user confirmed: captured BEFORE authentication and passed to + * [InternalTransferService.transfer] unchanged. There is no destination: the service resolves + * the wallet's own address for [to] at send time. [toString] is redacted. + */ +data class InternalTransferRequest( + val from: SendBalance, + val to: SendBalance, + val amount: Dash, + val isMax: Boolean, + val expectedWalletIdHex: String? +) { + override fun toString(): String = "InternalTransferRequest($from → $to, , isMax=$isMax)" +} + +/** The one internal transfer the app runs at a time, as [InternalTransferExecutor] reports it. */ +sealed class InternalTransferExecution { + /** The in-flight marker of a previous process is still being read; nothing can be sent yet. */ + object Restoring : InternalTransferExecution() + + object Idle : InternalTransferExecution() + + data class Sending(val request: InternalTransferRequest) : InternalTransferExecution() + + /** Terminal until the screen [InternalTransferExecutor.acknowledge]s it. */ + data class Finished(val request: InternalTransferRequest, val result: ExternalSendResult) : + InternalTransferExecution() + + /** A previous process died with a transfer possibly submitted, or the marker is unreadable. */ + object InterruptedByRestart : InternalTransferExecution() + + /** An outcome was acknowledged and its marker is being cleared (see the External Send executor). */ + object Acknowledging : InternalTransferExecution() +} + +/** + * App-lifetime owner of the Advanced-mode internal transfer (MO-1125): the same contract as + * [de.schildbach.wallet.ui.payments.send.ExternalSendExecutor] — application scope (a shielded + * leg's ~30 s proof survives the screen), one transfer per confirmation, a durable in-flight + * marker ([DashPayConfig.INTERNAL_TRANSFER_IN_FLIGHT]) written before the request reaches the + * service and cleared right away only on Not sent, otherwise on acknowledgement — over + * [InternalTransferService] and its own request type. + * + * A sibling rather than a generalized External Send executor: that executor's state type is + * public API of the External Send screen and its tests, and sharing one instance would let one + * flow's screen show (and acknowledge) the other's outcome. + */ +@Singleton +class InternalTransferExecutor internal constructor( + private val service: InternalTransferService, + private val marker: ExternalSendInFlightMarker, + private val applicationScope: CoroutineScope +) { + @Inject + constructor( + service: InternalTransferService, + dashPayConfig: DashPayConfig, + applicationScope: CoroutineScope + ) : this( + service, + DashPayConfigInFlightMarker(dashPayConfig, DashPayConfig.INTERNAL_TRANSFER_IN_FLIGHT), + applicationScope + ) + + companion object { + private val log = LoggerFactory.getLogger(InternalTransferExecutor::class.java) + } + + private val _state = MutableStateFlow(InternalTransferExecution.Restoring) + val state: StateFlow = _state.asStateFlow() + + init { + applicationScope.launch { + val interrupted = try { + marker.isSet() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("internal transfer in-flight marker unreadable; assuming a transfer may have gone through", e) + true + } + if (interrupted) log.warn("internal transfer: a previous process may have left a transfer in flight") + _state.update { + if (it is InternalTransferExecution.Restoring) { + if (interrupted) InternalTransferExecution.InterruptedByRestart else InternalTransferExecution.Idle + } else { + it + } + } + } + } + + /** Start [request]; refused (false) unless Idle. A terminal result is never silently replaced. */ + fun submit(request: InternalTransferRequest): Boolean { + var accepted = false + _state.update { current -> + if (current is InternalTransferExecution.Idle) { + accepted = true + InternalTransferExecution.Sending(request) + } else { + accepted = false + current + } + } + if (!accepted) { + log.warn("internal transfer refused: a previous transfer is still running or unacknowledged") + return false + } + applicationScope.launch { + var result: ExternalSendResult = ExternalSendResult.MayHaveGoneThrough + var marked = false + try { + try { + marker.set() + marked = true + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Nothing handed to the service: provably nothing spent. + log.warn("internal transfer: could not record the in-flight marker; not sent", e) + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + if (marked) { + result = service.transfer( + request.from, + request.to, + request.amount, + request.isMax, + request.expectedWalletIdHex + ) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.error("internal transfer threw; outcome unknown", e) + } finally { + log.info("internal transfer {} → {} finished: {}", request.from, request.to, kindOf(result)) + // Cleared BEFORE the outcome is published, and only on Not sent. + if (marked && result is ExternalSendResult.NotSent) { + withContext(NonCancellable) { clearMarker() } + } + _state.value = InternalTransferExecution.Finished(request, result) + } + } + return true + } + + /** The screen showed the outcome (see `ExternalSendExecutor.acknowledge`). */ + fun acknowledge() { + val current = _state.value + val needsClear = when (current) { + is InternalTransferExecution.Finished -> current.result !is ExternalSendResult.NotSent + InternalTransferExecution.InterruptedByRestart -> true + else -> return + } + if (!needsClear) { + _state.compareAndSet(current, InternalTransferExecution.Idle) + return + } + if (!_state.compareAndSet(current, InternalTransferExecution.Acknowledging)) return + applicationScope.launch { + clearMarker() + _state.compareAndSet(InternalTransferExecution.Acknowledging, InternalTransferExecution.Idle) + } + } + + private suspend fun clearMarker() { + try { + marker.clear() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Left set: the next process warns once more (conservative). + log.warn("internal transfer: could not clear the in-flight marker", e) + } + } + + private fun kindOf(result: ExternalSendResult): String = when (result) { + is ExternalSendResult.Sent -> "Sent" + is ExternalSendResult.NotSent -> "NotSent(${result.reason})" + ExternalSendResult.MayHaveGoneThrough -> "MayHaveGoneThrough" + ExternalSendResult.InterruptedFundsReturnToShielded -> "InterruptedFundsReturnToShielded" + ExternalSendResult.CompletesAutomatically -> "CompletesAutomatically" + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt new file mode 100644 index 0000000000..6c0112b8f9 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt @@ -0,0 +1,99 @@ +/* + * 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.internal + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.compose.BackHandler +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.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.launch +import org.dash.wallet.common.services.AuthenticationManager +import org.dash.wallet.common.ui.components.DashWalletTheme +import javax.inject.Inject + +/** + * The Internal page of [de.schildbach.wallet.ui.payments.AdvancedPaymentsFragment] (MO-1125): + * transfers between the user's own balances. Basic mode keeps + * [de.schildbach.wallet.ui.payments.PaymentsInternalFragment]. + * + * Confirm captures the exact request, then asks for PIN/biometric (the External Send's auth + * path), then hands it to the app-scoped [InternalTransferExecutor]: leaving the screen does not + * cancel the transfer. Back closes an open sheet; otherwise it belongs to the host. + */ +@AndroidEntryPoint +class InternalTransferFragment : Fragment() { + + companion object { + fun newInstance() = InternalTransferFragment() + } + + private val viewModel by viewModels() + + @Inject + lateinit var authManager: AuthenticationManager + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = + ComposeView(requireContext()).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { + DashWalletTheme { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + BackHandler(enabled = uiState.picker != null || uiState.confirm != null) { viewModel.onBack() } + InternalTransferScreen( + uiState = uiState, + actions = InternalTransferActions( + onKeyInput = viewModel::onKeyInput, + onCurrencySelected = viewModel::onCurrencySelected, + onMaxClick = viewModel::onMaxClick, + onShowPicker = viewModel::onShowPicker, + onDismissPicker = viewModel::onDismissPicker, + onBalancePicked = viewModel::onBalancePicked, + onSwap = viewModel::onSwap, + onContinue = viewModel::onContinue, + onDismissConfirm = viewModel::onDismissConfirm, + onConfirm = ::authenticateAndTransfer, + onHideSending = viewModel::onHideSending, + onResultClosed = viewModel::onResultAcknowledged + ) + ) + } + } + } + + /** + * Capture what the confirm sheet shows BEFORE authenticating, then transfer exactly that. + * A failed or cancelled authentication transfers nothing. + */ + private fun authenticateAndTransfer() { + val request = viewModel.confirmedRequest() ?: return + viewLifecycleOwner.lifecycleScope.launch { + val activity = activity ?: return@launch + if (authManager.authenticate(activity) == null) return@launch + viewModel.submit(request) + } + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt new file mode 100644 index 0000000000..316bbbcb25 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -0,0 +1,502 @@ +/* + * 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.internal + +import androidx.annotation.DrawableRes +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.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.Layout +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.selected +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.Constraints +import androidx.compose.ui.unit.dp +import de.schildbach.wallet.service.platform.sdk.InternalTransferSupport +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.ui.payments.send.ExternalSendStatus +import de.schildbach.wallet.ui.payments.send.ResultDialog +import de.schildbach.wallet.ui.payments.send.SendConfirmSheet +import de.schildbach.wallet.ui.payments.send.SendingOverlay +import de.schildbach.wallet.ui.payments.send.SheetOverlay +import de.schildbach.wallet.ui.payments.send.balanceNameFor +import de.schildbach.wallet.ui.payments.send.iconFor +import de.schildbach.wallet.ui.payments.send.titleFor +import de.schildbach.wallet.ui.shielded.toDisplay +import de.schildbach.wallet.ui.shielded.toDisplayString +import de.schildbach.wallet.ui.shielded.toFiatAt +import de.schildbach.wallet_test.R +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.ui.components.DASH_CURRENCY_CODE +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.ui.components.LocalDashColors +import org.dash.wallet.common.ui.components.Menu +import org.dash.wallet.common.ui.components.MyImages +import org.dash.wallet.common.ui.components.MyTheme +import org.dash.wallet.common.ui.components.TopNavBase +import org.dash.wallet.common.ui.enter_amount.AmountEntryPage +import org.dash.wallet.common.ui.enter_amount.AmountEntryPrimaryButton + +/** The callbacks of [InternalTransferScreen], one per user action. */ +class InternalTransferActions( + val onKeyInput: (String) -> Unit, + val onCurrencySelected: (dashMode: Boolean) -> Unit, + val onMaxClick: () -> Unit, + val onShowPicker: (InternalTransferPicker) -> Unit, + val onDismissPicker: () -> Unit, + val onBalancePicked: (SendBalance) -> Unit, + val onSwap: () -> Unit, + val onContinue: () -> Unit, + val onDismissConfirm: () -> Unit, + val onConfirm: () -> Unit, + val onHideSending: () -> Unit, + val onResultClosed: () -> Unit +) + +/** Disabled picker rows, as the shared `ActionItem` dims them. */ +private const val DISABLED_ROW_ALPHA = 0.4f + +/** + * The Internal tab of the Advanced payments screen (MO-1125, Figma 3342:12176) under the + * Receive / Internal / Send picker the host draws: the amount, the From / To cards with the swap + * button, the keypad and Continue; the "Transfer from / to" picker (3342:12177); and the shared + * confirm sheet, sending overlay and outcome dialog of the External Send. + */ +@Composable +fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTransferActions) { + val colors = LocalDashColors.current + Box( + modifier = Modifier + .fillMaxSize() + .background(colors.backgroundPrimary) + ) { + AmountPage(uiState, actions) + + val picker = uiState.picker + if (picker != null && uiState.formEditable) { + PickerSheet(uiState, picker, actions) + } + + val confirm = uiState.confirm + if (confirm != null && uiState.status == ExternalSendStatus.Idle) { + val request = confirm.request + SendConfirmSheet( + amount = request.amount, + rate = uiState.rate, + fiatCode = uiState.fiatCode, + fromValue = stringResource(balanceNameFor(request.from)), + toValue = stringResource(balanceNameFor(request.to)), + fee = confirm.fee, + feeLoading = confirm.feeLoading, + total = confirm.total, + feeIncluded = false, + notes = internalConfirmNotes(request.from, request.to), + onDismiss = actions.onDismissConfirm, + onConfirm = actions.onConfirm + ) + } + + when (val status = uiState.status) { + // A shielded leg's ~30 s proof can be left: Close hides the overlay (the form stays + // disabled) and the outcome shows when it arrives. + is ExternalSendStatus.Sending -> if (!uiState.sendingHidden) { + SendingOverlay(status.shieldedLeg, actions.onHideSending) + } + is ExternalSendStatus.Done -> ResultDialog(status.result, status.afterRestart, actions.onResultClosed) + ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} + } + } +} + +/** + * The confirm notes (AC11/AC13, reusing the External Send's): out of Shielded the transfer is not + * instant and its amount becomes public; Identity → Core is a withdrawal that takes some time. + */ +internal fun internalConfirmNotes(from: SendBalance, to: SendBalance): List = buildList { + if (from == SendBalance.SHIELDED && to != SendBalance.SHIELDED) { + add(R.string.external_send_shielded_not_instant) + add( + when (to) { + SendBalance.CORE -> R.string.external_send_shielded_public_to_core + SendBalance.PLATFORM -> R.string.external_send_shielded_public_to_platform + else -> R.string.external_send_shielded_public_to_identity + } + ) + } + if (from == SendBalance.IDENTITY && to == SendBalance.CORE) { + add(R.string.internal_transfer_withdrawal_not_instant) + } +} + +@Composable +private fun AmountPage(uiState: InternalTransferUIState, actions: InternalTransferActions) { + val fiatCode = uiState.fiatCode + val codes = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE) + AmountEntryPage( + amount = uiState.amountText, + currencyCodes = codes, + selectedCurrencyIndex = if (uiState.dashMode || fiatCode == null) 0 else 1, + onKeyInput = actions.onKeyInput, + // Figma 3342:12176: the content column starts 10dp under the tab picker. + modifier = Modifier + .fillMaxSize() + .padding(top = 10.dp), + secondaryAmount = uiState.secondaryAmountText, + showPrimaryChevron = false, + keypadEnabled = uiState.formEditable, + onCurrencySelected = if (fiatCode != null && uiState.rate != null) { + { index -> actions.onCurrencySelected(index == 0) } + } else { + null + }, + // Max is offered only when the service knows the max sendable (balance minus fee). + onMaxClick = if (uiState.maxSendable != null) actions.onMaxClick else null, + belowAmount = { + // Figma: 10dp between the amount block and the cards group. + Spacer(modifier = Modifier.height(10.dp)) + FromToCards(uiState, actions) + PairStatus(uiState) + }, + primaryButton = { + AmountEntryPrimaryButton( + text = stringResource(R.string.button_continue), + enabled = uiState.canContinue, + onClick = actions.onContinue + ) + } + ) +} + +/** + * Figma 3342:12176 cards group: From over To with a 5dp gap, and the swap button (btn-s + * 3325:4692) centred on that gap. + */ +@Composable +private fun FromToCards(uiState: InternalTransferUIState, actions: InternalTransferActions) { + val colors = LocalDashColors.current + val editable = uiState.formEditable + val changeFrom = stringResource(R.string.internal_transfer_change_from) + val changeTo = stringResource(R.string.internal_transfer_change_to) + val swap = stringResource(R.string.internal_transfer_swap) + Layout( + modifier = Modifier.fillMaxWidth(), + content = { + Card { + DirectionRow( + icon = iconFor(uiState.from), + label = stringResource(R.string.external_send_from), + title = stringResource(titleFor(uiState.from)), + modifier = Modifier + .clickable(enabled = editable, role = Role.Button) { + actions.onShowPicker(InternalTransferPicker.FROM) + } + .semantics { contentDescription = changeFrom }, + trailing = { FromBalance(uiState) } + ) + } + Card { + DirectionRow( + icon = iconFor(uiState.to), + label = stringResource(R.string.external_send_to), + title = stringResource(titleFor(uiState.to)), + modifier = Modifier + .clickable(enabled = editable, role = Role.Button) { + actions.onShowPicker(InternalTransferPicker.TO) + } + .semantics { contentDescription = changeTo }, + trailing = { Chevron() } + ) + } + // btn-s: a 30dp white button, 10dp corners, ringed by a 5dp stroke in the page colour. + Box( + modifier = Modifier + .size(40.dp) + .clip(RoundedCornerShape(15.dp)) + .background(colors.backgroundPrimary) + .clickable(enabled = editable, role = Role.Button, onClick = actions.onSwap) + .semantics { contentDescription = swap }, + contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .size(30.dp) + .background(colors.backgroundSecondary, RoundedCornerShape(10.dp)), + contentAlignment = Alignment.Center + ) { + Icon( + painter = painterResource(R.drawable.ic_swap_up_down), + contentDescription = null, + tint = colors.dashBlue, + modifier = Modifier.size(16.dp) + ) + } + } + } + ) { measurables, constraints -> + val width = constraints.maxWidth + val gap = 5.dp.roundToPx() + val cardConstraints = Constraints(minWidth = width, maxWidth = width) + val fromCard = measurables[0].measure(cardConstraints) + val toCard = measurables[1].measure(cardConstraints) + val button = measurables[2].measure(Constraints()) + layout(width, fromCard.height + gap + toCard.height) { + fromCard.place(0, 0) + toCard.place(0, fromCard.height + gap) + button.place((width - button.width) / 2, fromCard.height + gap / 2 - button.height / 2) + } + } +} + +/** The From balance: amount with the Dash logo over its fiat value, right-aligned, then a chevron. */ +@Composable +private fun FromBalance(uiState: InternalTransferUIState) { + val colors = LocalDashColors.current + val balance = uiState.balance + Row(verticalAlignment = Alignment.CenterVertically) { + Column(horizontalAlignment = Alignment.End) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text( + text = balance?.toDisplayString() ?: stringResource(R.string.external_send_value_unknown), + style = MyTheme.Typography.SubheadMedium, + color = colors.textPrimary + ) + if (balance != null) { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_dash_d_black), + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.height(14.dp) + ) + } + } + balance?.toFiatAt(uiState.rate)?.let { fiat -> + Text(text = fiat.toDisplay(), style = MyTheme.Typography.Footnote, color = colors.textSecondary) + } + } + Spacer(modifier = Modifier.size(10.dp)) + Chevron() + } +} + +@Composable +private fun Chevron() { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_menu_row_arrow), + contentDescription = null, + tint = LocalDashColors.current.gray300.copy(alpha = 0.9f), + modifier = Modifier.size(14.dp) + ) +} + +/** A Figma "Menu" card: secondary background, 20dp corners, 6dp padding. */ +@Composable +private fun Card(content: @Composable ColumnScope.() -> Unit) { + Column( + modifier = Modifier + .fillMaxWidth() + .background(LocalDashColors.current.backgroundSecondary, RoundedCornerShape(20.dp)) + .padding(6.dp), + content = content + ) +} + +/** Figma "Action item": 10dp padding and gap, 30dp icon, label over title (0 6dp), trailing content. */ +@Composable +private fun DirectionRow( + @DrawableRes icon: Int, + label: String, + title: String, + modifier: Modifier = Modifier, + trailing: @Composable () -> Unit +) { + val colors = LocalDashColors.current + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .then(modifier) + .padding(10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Image(painter = painterResource(icon), contentDescription = null, modifier = Modifier.size(30.dp)) + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = 6.dp) + ) { + Text(text = label, style = MyTheme.Typography.Footnote, color = colors.textSecondary) + Text(text = title, style = MyTheme.Typography.SubheadMedium, color = colors.textPrimary) + } + trailing() + } +} + +/** Under the cards: "Insufficient balance" (AC7), or why the pair cannot be transferred. */ +@Composable +private fun PairStatus(uiState: InternalTransferUIState) { + val colors = LocalDashColors.current + when { + uiState.support != InternalTransferSupport.SUPPORTED && uiState.shieldedEnabled != null -> + StatusText(stringResource(R.string.internal_transfer_unavailable), colors.textSecondary) + uiState.insufficientBalance -> + StatusText(stringResource(R.string.internal_transfer_insufficient_balance), colors.red) + } +} + +@Composable +private fun StatusText(text: String, color: Color) { + Text( + text = text, + style = MyTheme.Typography.BodySmall, + color = color, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(top = 10.dp) + ) +} + +/** Figma 3342:12177 "Transfer from" / "Transfer to": one row per balance, the selected one blue with a check. */ +@Composable +private fun PickerSheet(uiState: InternalTransferUIState, picker: InternalTransferPicker, actions: InternalTransferActions) { + val selected = if (picker == InternalTransferPicker.FROM) uiState.from else uiState.to + SheetOverlay(onDismiss = actions.onDismissPicker) { + TopNavBase( + leadingPart = false, + trailingIcon = MyImages.NavBarClose, + trailingContentDescription = stringResource(R.string.external_send_close), + onTrailingClick = actions.onDismissPicker, + title = stringResource( + if (picker == InternalTransferPicker.FROM) { + R.string.internal_transfer_transfer_from + } else { + R.string.internal_transfer_transfer_to + } + ) + ) + Spacer(modifier = Modifier.height(10.dp)) + Menu { + uiState.balances.forEach { balance -> + PickerRow( + balance = balance, + selected = balance == selected, + enabled = uiState.pickable(picker, balance), + onClick = { actions.onBalancePicked(balance) } + ) + } + } + Spacer(modifier = Modifier.height(20.dp)) + } +} + +/** An `ActionItem`-sized row whose title turns dashBlue, with a trailing check, when [selected]. */ +@Composable +private fun PickerRow(balance: SendBalance, selected: Boolean, enabled: Boolean, onClick: () -> Unit) { + val colors = LocalDashColors.current + Row( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 50.dp) + .then(if (enabled) Modifier else Modifier.alpha(DISABLED_ROW_ALPHA)) + .clip(RoundedCornerShape(16.dp)) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick) + .semantics { this.selected = selected } + .padding(start = 12.dp, end = 14.dp, top = 10.dp, bottom = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Image(painter = painterResource(iconFor(balance)), contentDescription = null, modifier = Modifier.size(30.dp)) + Column( + modifier = Modifier + .weight(1f) + .padding(start = 6.dp) + ) { + Text( + text = stringResource(titleFor(balance)), + style = MyTheme.Typography.SubheadMedium, + color = if (selected) colors.dashBlue else colors.textPrimary + ) + if (!enabled) { + Text( + text = stringResource(R.string.internal_transfer_unavailable), + style = MyTheme.Typography.Footnote, + color = colors.textSecondary + ) + } + } + if (selected) { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_checkmark_blue), + contentDescription = null, + tint = colors.dashBlue, + modifier = Modifier.size(24.dp) + ) + } + } +} + +@Preview(showBackground = true, widthDp = 420, heightDp = 760) +@Composable +private fun InternalTransferPreview() { + DashWalletTheme { + InternalTransferScreen( + uiState = InternalTransferUIState( + shieldedEnabled = true, + hasIdentity = true, + amountText = "1", + balance = Dash.COIN * 2L, + maxSendable = Dash.COIN * 2L + ), + actions = InternalTransferActions( + onKeyInput = {}, onCurrencySelected = {}, onMaxClick = {}, onShowPicker = {}, onDismissPicker = {}, + onBalancePicked = {}, onSwap = {}, onContinue = {}, onDismissConfirm = {}, onConfirm = {}, + onHideSending = {}, onResultClosed = {} + ) + ) + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt new file mode 100644 index 0000000000..93e6ecf2ca --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -0,0 +1,497 @@ +/* + * 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.internal + +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.InternalTransferPair +import de.schildbach.wallet.service.platform.sdk.InternalTransferService +import de.schildbach.wallet.service.platform.sdk.InternalTransferSupport +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.defaultInternalTransferPair +import de.schildbach.wallet.service.platform.sdk.internalTransferBalances +import de.schildbach.wallet.service.platform.sdk.internalTransferHasShieldedLeg +import de.schildbach.wallet.service.platform.sdk.internalTransferSupport +import de.schildbach.wallet.ui.payments.send.ExternalSendStatus +import de.schildbach.wallet.ui.shielded.parseDashOrNull +import de.schildbach.wallet.ui.shielded.parseDecimalOrNull +import de.schildbach.wallet.ui.shielded.toDashAt +import de.schildbach.wallet.ui.shielded.toFiatAt +import de.schildbach.wallet.ui.shielded.toKeypadString +import de.schildbach.wallet.ui.shielded.toKeypadStringTwoDecimals +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import org.dash.wallet.common.data.WalletUIConfig +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.money.Fiat +import org.dash.wallet.common.services.ExchangeRatesProvider +import org.dash.wallet.common.ui.enter_amount.processAmountKeyInput +import org.dash.wallet.common.util.toFiat +import javax.inject.Inject + +/** Which balance picker sheet is open. */ +enum class InternalTransferPicker { FROM, TO } + +/** + * The confirm sheet: [request] is exactly what Confirm sends. [fee] null with [feeLoading] false + * means the fee cannot be known before the transfer (never fabricated). The fee is paid on top. + */ +data class InternalTransferConfirm( + val request: InternalTransferRequest, + val fee: FeeEstimate? = null, + val feeLoading: Boolean = true +) { + /** What leaves the From balance: amount plus fee, null while the fee is unknown. */ + val total: Dash? get() = fee?.let { request.amount + it.fee } +} + +/** + * Single UI state of the Advanced-mode Internal tab (MO-1125). + * + * @property shieldedEnabled `USE_KOTLIN_SDK_SHIELDED`; null until read (an unreadable flag is off). + * @property hasIdentity null = unknown: Identity is hidden. + * @property pairChosenByUser the user changed From/To; until then the default pair + * ([defaultInternalTransferPair]) follows the inputs as they arrive. + * @property balance the From balance; null = unknown (never 0), and it blocks Continue. + * @property maxSendable null = unknown: Max is unavailable and [balance] bounds the amount. + * @property sendingHidden the user closed the sending overlay of a shielded leg; the transfer + * continues and the form stays disabled until its outcome. Reset when the status changes. + * @property pinnedAmount the exact amount while [amountText] is only its rendering (see the + * External Send's `pinnedAmount`). + */ +data class InternalTransferUIState( + val from: SendBalance = SendBalance.CORE, + val to: SendBalance = SendBalance.SHIELDED, + val pairChosenByUser: Boolean = false, + val shieldedEnabled: Boolean? = null, + val hasIdentity: Boolean? = null, + val amountText: String = "0", + val dashMode: Boolean = true, + val maxAmount: Dash? = null, + val pinnedAmount: Dash? = null, + val fiatCode: String? = null, + val rate: Fiat? = null, + val balance: Dash? = null, + val maxSendable: Dash? = null, + val picker: InternalTransferPicker? = null, + val confirm: InternalTransferConfirm? = null, + val status: ExternalSendStatus = ExternalSendStatus.Idle, + val sendingHidden: Boolean = false +) { + val pair: InternalTransferPair get() = InternalTransferPair(from, to) + + /** The form can be edited: no transfer running or unacknowledged. */ + val formEditable: Boolean get() = status == ExternalSendStatus.Idle + + /** The balances the pickers list, in order; Identity only for a user known to have one. */ + val balances: List get() = internalTransferBalances(hasIdentity) + + val support: InternalTransferSupport + get() = internalTransferSupport(from, to, shieldedEnabled == true, hasIdentity == true) + + /** + * Whether picking [balance] in [picker] leads to a supported pair (picking the other side's + * balance swaps them, AC4). The current selection is always pickable (a no-op). + */ + fun pickable(picker: InternalTransferPicker, balance: SendBalance): Boolean { + val result = when (picker) { + InternalTransferPicker.FROM -> if (balance == from) return true else pair.withFrom(balance) + InternalTransferPicker.TO -> if (balance == to) return true else pair.withTo(balance) + } + return internalTransferSupport( + result.from, + result.to, + shieldedEnabled == true, + hasIdentity == true + ) == InternalTransferSupport.SUPPORTED + } + + val isMax: Boolean get() = maxAmount != null + + /** The amount in Dash (fiat converted at [rate]); zero when unparseable or no rate. */ + val amount: Dash + get() = maxAmount ?: pinnedAmount ?: if (dashMode) { + parseDashOrNull(amountText) ?: Dash.ZERO + } else { + val code = fiatCode + if (code == null) Dash.ZERO else parseDecimalOrNull(amountText)?.toFiat(code)?.toDashAt(rate) ?: Dash.ZERO + } + + /** The amount in the other currency, '.'-separated for the amount page; null without a rate. */ + val secondaryAmountText: String? + get() = if (dashMode) { + amount.toFiatAt(rate)?.toKeypadStringTwoDecimals() ?: if (rate == null) null else "0" + } else { + amount.toKeypadString() + } + + /** What the amount may not exceed: Max (balance minus fee) when known, else the balance. */ + val limit: Dash? get() = maxSendable ?: balance + + /** AC7: the amount is above Max; shown as "Insufficient balance" and blocks Continue. */ + val insufficientBalance: Boolean get() = limit?.let { amount.isGreaterThan(it) } == true + + val canContinue: Boolean + get() = support == InternalTransferSupport.SUPPORTED && + amount.isPositive && + balance != null && + !insufficientBalance && + (dashMode || rate != null || pinnedAmount != null || maxAmount != null) && + formEditable +} + +/** + * The Advanced-mode Internal tab (MO-1125): pick From and To among the user's own balances, an + * amount, then confirm → PIN/biometric (the fragment) → [InternalTransferExecutor]. Nothing + * optimistic: the transfer state is mirrored from the executor. + */ +@OptIn(ExperimentalCoroutinesApi::class) +@HiltViewModel +class InternalTransferViewModel @Inject constructor( + private val service: InternalTransferService, + private val executor: InternalTransferExecutor, + walletUIConfig: WalletUIConfig, + exchangeRates: ExchangeRatesProvider, + private val savedState: SavedStateHandle +) : ViewModel() { + + companion object { + internal const val KEY_FROM = "internal_transfer_from" + internal const val KEY_TO = "internal_transfer_to" + internal const val KEY_PAIR_CHOSEN = "internal_transfer_pair_chosen" + internal const val KEY_AMOUNT = "internal_transfer_amount" + internal const val KEY_DASH_MODE = "internal_transfer_dash_mode" + internal const val KEY_MAX_DUFFS = "internal_transfer_max_duffs" + internal const val KEY_PINNED_DUFFS = "internal_transfer_pinned_duffs" + + private const val DASH_DECIMALS = 8 + private const val FIAT_DECIMALS = 2 + } + + private val _uiState = MutableStateFlow(InternalTransferUIState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private var balanceJob: Job? = null + private var balanceGeneration = 0 + private var feeJob: Job? = null + + init { + restore() + + service.observeShieldedEnabled() + .onEach { enabled -> + _uiState.update { it.copy(shieldedEnabled = enabled) } + reconcilePair() + } + .launchIn(viewModelScope) + + service.observeHasIdentity() + .onEach { has -> + _uiState.update { it.copy(hasIdentity = has) } + reconcilePair() + } + .launchIn(viewModelScope) + + walletUIConfig.observe(WalletUIConfig.SELECTED_CURRENCY) + .filterNotNull() + .onEach { code -> _uiState.update { it.copy(fiatCode = code) } } + .flatMapLatest(exchangeRates::observeExchangeRate) + .onEach { rate -> _uiState.update { it.copy(rate = rate?.fiat) } } + .launchIn(viewModelScope) + + executor.state + .onEach { execution -> + val status = when (execution) { + InternalTransferExecution.Restoring -> ExternalSendStatus.Restoring + InternalTransferExecution.InterruptedByRestart -> + ExternalSendStatus.Done(ExternalSendResult.MayHaveGoneThrough, afterRestart = true) + InternalTransferExecution.Idle -> ExternalSendStatus.Idle + // An outcome being dismissed: no dialog, nothing can be sent yet. + InternalTransferExecution.Acknowledging -> ExternalSendStatus.Restoring + is InternalTransferExecution.Sending -> ExternalSendStatus.Sending( + internalTransferHasShieldedLeg(execution.request.from, execution.request.to) + ) + is InternalTransferExecution.Finished -> ExternalSendStatus.Done(execution.result) + } + _uiState.update { + it.copy(status = status, sendingHidden = it.sendingHidden && status is ExternalSendStatus.Sending) + } + } + .launchIn(viewModelScope) + + restartBalance() + } + + /** Process restore: the pair the user chose and the amount. */ + private fun restore() { + val from = savedState.get(KEY_FROM)?.let(::balanceOrNull) + val to = savedState.get(KEY_TO)?.let(::balanceOrNull) + val chosen = savedState.get(KEY_PAIR_CHOSEN) == true && from != null && to != null && from != to + _uiState.update { + it.copy( + from = if (chosen && from != null) from else it.from, + to = if (chosen && to != null) to else it.to, + pairChosenByUser = chosen, + amountText = savedState.get(KEY_AMOUNT) ?: "0", + dashMode = savedState.get(KEY_DASH_MODE) ?: true, + maxAmount = savedState.get(KEY_MAX_DUFFS)?.let(::Dash), + pinnedAmount = savedState.get(KEY_PINNED_DUFFS)?.let(::Dash) + ) + } + } + + private fun balanceOrNull(name: String): SendBalance? = SendBalance.entries.firstOrNull { it.name == name } + + /** + * Until the user changes the pair, follow the default as the flag and identity arrive. A + * user's pair that is no longer listed (identity gone) falls back to the default. + */ + private fun reconcilePair() { + val state = _uiState.value + val listed = state.from in state.balances && state.to in state.balances + if (state.pairChosenByUser && listed) return + val pair = defaultInternalTransferPair(state.shieldedEnabled == true, state.hasIdentity == true) + if (state.pairChosenByUser) { + _uiState.update { it.copy(pairChosenByUser = false) } + savedState[KEY_PAIR_CHOSEN] = false + } + setPair(pair, byUser = false) + } + + // ── From / To ──────────────────────────────────────────────────────────── + + fun onShowPicker(picker: InternalTransferPicker) { + if (!_uiState.value.formEditable) return + _uiState.update { it.copy(picker = picker) } + } + + fun onDismissPicker() { + _uiState.update { it.copy(picker = null) } + } + + /** A pick in the open picker; picking the other side's balance swaps them (AC4). */ + fun onBalancePicked(balance: SendBalance) { + val state = _uiState.value + val picker = state.picker ?: return + if (!state.formEditable) return + if (balance !in state.balances || !state.pickable(picker, balance)) return + val pair = when (picker) { + InternalTransferPicker.FROM -> state.pair.withFrom(balance) + InternalTransferPicker.TO -> state.pair.withTo(balance) + } + setPair(pair, byUser = true) + _uiState.update { it.copy(picker = null) } + } + + /** AC3: From and To exchange. */ + fun onSwap() { + val state = _uiState.value + if (!state.formEditable) return + setPair(state.pair.swapped(), byUser = true) + } + + private fun setPair(pair: InternalTransferPair, byUser: Boolean) { + val state = _uiState.value + val fromChanged = state.from != pair.from + val changed = fromChanged || state.to != pair.to + _uiState.update { + it.copy( + from = pair.from, + to = pair.to, + pairChosenByUser = it.pairChosenByUser || byUser, + maxAmount = if (changed) null else it.maxAmount, + // A dropped Max keeps its exact amount (no longer Max): its text may be rounded fiat. + pinnedAmount = if (changed && it.isMax) it.amount else it.pinnedAmount, + balance = if (fromChanged) null else it.balance, + maxSendable = if (changed) null else it.maxSendable + ) + } + savedState[KEY_FROM] = pair.from.name + savedState[KEY_TO] = pair.to.name + savedState[KEY_PAIR_CHOSEN] = _uiState.value.pairChosenByUser + saveAmount() + if (changed) restartBalance() + } + + /** Observe the From balance and re-read Max for the pair on every balance change. */ + private fun restartBalance() { + balanceJob?.cancel() + val from = _uiState.value.from + val to = _uiState.value.to + val generation = ++balanceGeneration + balanceJob = service.observeBalance(from) + .onEach { balance -> + if (generation == balanceGeneration) _uiState.update { it.copy(balance = balance) } + } + .mapLatest { balance -> if (balance == null) null else service.maxSendable(from, to) } + .onEach { max -> + if (generation == balanceGeneration) _uiState.update { it.copy(maxSendable = max) } + } + .launchIn(viewModelScope) + } + + // ── Amount ─────────────────────────────────────────────────────────────── + + fun onKeyInput(key: String) { + val state = _uiState.value + if (!state.formEditable) return + // Editing a Max amount edits what is on show. + val base = if (state.isMax) displayTextFor(state.amount, state.dashMode, state.rate) else state.amountText + val decimals = if (state.dashMode) DASH_DECIMALS else FIAT_DECIMALS + val text = processAmountKeyInput(base, key, decimals) + if (text == state.amountText && !state.isMax) return + _uiState.update { it.copy(amountText = text, maxAmount = null, pinnedAmount = null) } + saveAmount() + } + + fun onCurrencySelected(dashMode: Boolean) { + val state = _uiState.value + if (state.dashMode == dashMode) return + if (!dashMode && state.rate == null) return + val amount = state.amount + val text = if (amount.isZero) "0" else displayTextFor(amount, dashMode, state.rate) + _uiState.update { + it.copy( + dashMode = dashMode, + amountText = text, + pinnedAmount = if (amount.isZero || state.isMax) null else amount + ) + } + saveAmount() + } + + /** AC6: Max = the From balance minus the fee, when the service knows it. */ + fun onMaxClick() { + val state = _uiState.value + val max = state.maxSendable ?: return + if (!state.formEditable) return + _uiState.update { + it.copy(maxAmount = max, pinnedAmount = null, amountText = displayTextFor(max, it.dashMode, it.rate)) + } + saveAmount() + } + + // ── Confirm and transfer ───────────────────────────────────────────────── + + fun onContinue() { + val state = _uiState.value + if (!state.canContinue) return + // The SDK wallet is captured here, without suspending: the transfer is refused unless the + // same wallet is still bound when it runs. The own destination is resolved by the service. + val request = InternalTransferRequest( + state.from, + state.to, + state.amount, + state.isMax, + service.currentWalletIdOrNull() + ) + _uiState.update { it.copy(confirm = InternalTransferConfirm(request), picker = null) } + feeJob?.cancel() + feeJob = viewModelScope.launch { + val fee = service.estimateFee(request.from, request.to, request.amount) + _uiState.update { current -> + val confirm = current.confirm + if (confirm?.request == request) { + current.copy(confirm = confirm.copy(fee = fee, feeLoading = false)) + } else { + current + } + } + } + } + + fun onDismissConfirm() { + feeJob?.cancel() + _uiState.update { it.copy(confirm = null) } + } + + /** The request the confirm sheet shows, captured BEFORE authentication; null when none. */ + fun confirmedRequest(): InternalTransferRequest? { + val state = _uiState.value + return state.confirm?.request?.takeIf { state.canContinue } + } + + /** Authenticated: run [request], unless it is no longer the request on the confirm sheet. */ + fun submit(request: InternalTransferRequest): Boolean { + if (_uiState.value.confirm?.request != request) return false + if (!executor.submit(request)) return false + _uiState.update { it.copy(confirm = null) } + return true + } + + /** + * The user closed the outcome. Not sent → back to the same amount (Max chosen again + * deliberately); any other outcome clears the amount for a new transfer (the tab stays). + */ + fun onResultAcknowledged() { + val status = _uiState.value.status as? ExternalSendStatus.Done ?: return + if (status.result is ExternalSendResult.NotSent) { + _uiState.update { it.copy(maxAmount = null, pinnedAmount = if (it.isMax) it.amount else it.pinnedAmount) } + } else { + _uiState.update { it.copy(amountText = "0", maxAmount = null, pinnedAmount = null) } + } + saveAmount() + executor.acknowledge() + } + + /** Close on the sending overlay: the transfer continues on the app scope. */ + fun onHideSending() { + if (_uiState.value.status is ExternalSendStatus.Sending) _uiState.update { it.copy(sendingHidden = true) } + } + + /** Back closes an open sheet; false when there is nothing to close. */ + fun onBack(): Boolean { + val state = _uiState.value + return when { + state.confirm != null && state.status == ExternalSendStatus.Idle -> { + onDismissConfirm() + true + } + state.picker != null -> { + onDismissPicker() + true + } + else -> false + } + } + + private fun displayTextFor(amount: Dash, dashMode: Boolean, rate: Fiat?): String = + if (dashMode) amount.toKeypadString() else amount.toFiatAt(rate)?.toKeypadStringTwoDecimals() ?: "0" + + private fun saveAmount() { + val state = _uiState.value + savedState[KEY_AMOUNT] = state.amountText + savedState[KEY_DASH_MODE] = state.dashMode + savedState[KEY_MAX_DUFFS] = state.maxAmount?.duffs + savedState[KEY_PINNED_DUFFS] = state.pinnedAmount?.duffs + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index abd931aa4d..ee1db10a1a 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -17,6 +17,7 @@ package de.schildbach.wallet.ui.payments.send +import androidx.datastore.preferences.core.Preferences import de.schildbach.wallet.service.platform.sdk.ExternalSendResult import de.schildbach.wallet.service.platform.sdk.ExternalSendService import de.schildbach.wallet.service.platform.sdk.NotSentReason @@ -93,11 +94,18 @@ internal interface ExternalSendInFlightMarker { suspend fun clear() } -/** [ExternalSendInFlightMarker] over [DashPayConfig] (error-preserving reads). */ -internal class DashPayConfigInFlightMarker(private val config: DashPayConfig) : ExternalSendInFlightMarker { - override suspend fun isSet(): Boolean = config.getPreservingErrors(DashPayConfig.EXTERNAL_SEND_IN_FLIGHT) == true - override suspend fun set() = config.set(DashPayConfig.EXTERNAL_SEND_IN_FLIGHT, true) - override suspend fun clear() = config.set(DashPayConfig.EXTERNAL_SEND_IN_FLIGHT, false) +/** + * [ExternalSendInFlightMarker] over the [DashPayConfig] flag [key] (error-preserving reads): + * [DashPayConfig.EXTERNAL_SEND_IN_FLIGHT] by default, [DashPayConfig.INTERNAL_TRANSFER_IN_FLIGHT] + * for the internal transfer. + */ +internal class DashPayConfigInFlightMarker( + private val config: DashPayConfig, + private val key: Preferences.Key = DashPayConfig.EXTERNAL_SEND_IN_FLIGHT +) : ExternalSendInFlightMarker { + override suspend fun isSet(): Boolean = config.getPreservingErrors(key) == true + override suspend fun set() = config.set(key, true) + override suspend fun clear() = config.set(key, false) } /** @@ -296,5 +304,6 @@ class ExternalSendExecutor internal constructor( is ExternalSendResult.NotSent -> "NotSent(${result.reason})" ExternalSendResult.MayHaveGoneThrough -> "MayHaveGoneThrough" ExternalSendResult.InterruptedFundsReturnToShielded -> "InterruptedFundsReturnToShielded" + ExternalSendResult.CompletesAutomatically -> "CompletesAutomatically" } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index 5fbb465b3e..a561fe312d 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -23,7 +23,6 @@ import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable -import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -39,19 +38,15 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.res.vectorResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics @@ -61,26 +56,20 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import de.schildbach.wallet.service.platform.sdk.ExternalSendResult import de.schildbach.wallet.service.platform.sdk.IdentityResolution -import de.schildbach.wallet.service.platform.sdk.NotSentReason import de.schildbach.wallet.service.platform.sdk.SendBalance import de.schildbach.wallet.service.platform.sdk.SendDestination import de.schildbach.wallet.service.platform.sdk.SendSupport +import de.schildbach.wallet.service.platform.sdk.balanceKindOf import de.schildbach.wallet.ui.shielded.toDisplay import de.schildbach.wallet.ui.shielded.toDisplayString import de.schildbach.wallet.ui.shielded.toFiatAt import de.schildbach.wallet_test.R import org.dash.wallet.common.money.Dash -import org.dash.wallet.common.money.Fiat import org.dash.wallet.common.ui.components.ActionItem import org.dash.wallet.common.ui.components.AddressField -import org.dash.wallet.common.ui.components.ButtonData import org.dash.wallet.common.ui.components.DASH_CURRENCY_CODE import org.dash.wallet.common.ui.components.DashButton import org.dash.wallet.common.ui.components.DashWalletTheme -import org.dash.wallet.common.ui.components.EnterAmount -import org.dash.wallet.common.ui.components.Grabber -import org.dash.wallet.common.ui.components.ListItem1 -import org.dash.wallet.common.ui.components.ListItem import org.dash.wallet.common.ui.components.LocalDashColors import org.dash.wallet.common.ui.components.Menu import org.dash.wallet.common.ui.components.ModalDialog @@ -88,14 +77,10 @@ import org.dash.wallet.common.ui.components.MyImages 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.components.SystemMessage import org.dash.wallet.common.ui.components.TopIntro import org.dash.wallet.common.ui.components.TopNavBase import org.dash.wallet.common.ui.enter_amount.AmountEntryPage import org.dash.wallet.common.ui.enter_amount.AmountEntryPrimaryButton -import org.dash.wallet.common.ui.enter_amount.decimalSeparatorFor -import org.dash.wallet.common.ui.enter_amount.localizeAmountForDisplay -import java.util.Locale /** The callbacks of [ExternalSendScreen], one per user action. */ class ExternalSendActions( @@ -499,33 +484,6 @@ private fun StatusText(text: String, color: Color) { // ── Sheets ────────────────────────────────────────────────────────────────── -/** Dimmed backdrop and a bottom sheet with a grabber, as in the shielded flows. */ -@Composable -private fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { - Box( - modifier = Modifier - .fillMaxSize() - .background(Color(0x800A0B0D)) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { - onDismiss() - } - ) { - Column( - modifier = Modifier - .align(Alignment.BottomCenter) - .fillMaxWidth() - .background( - LocalDashColors.current.backgroundPrimary, - RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp) - ) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} - ) { - Grabber() - content() - } - } -} - /** Figma 7076:47424 "Select source": the four balances with a radio; unsupported rows disabled. */ @Composable private fun SourceSheet(uiState: ExternalSendUIState, actions: ExternalSendActions) { @@ -570,121 +528,31 @@ private fun Radio(selected: Boolean) { ) } -/** Figma 7076:47968 / 7107:48421: amount, From / To / Network fee / Total, info notes, buttons. */ +/** Figma 7076:47968 / 7107:48421, through the shared [SendConfirmSheet]. */ @Composable private fun ConfirmSheet(uiState: ExternalSendUIState, confirm: ExternalSendConfirm, actions: ExternalSendActions) { val request = confirm.request - val unknown = stringResource(R.string.external_send_value_unknown) - SheetOverlay(onDismiss = actions.onDismissConfirm) { - TopNavBase( - leadingPart = false, - trailingPart = false, - title = stringResource(R.string.external_send_confirm_title) - ) - Column( - modifier = Modifier - .fillMaxWidth() - .verticalScroll(rememberScrollState()) - ) { - // What the recipient receives (a Core Max drain: the amount minus the fee). - ConfirmAmount(confirm.recipientAmount, uiState.rate, uiState.fiatCode) - Spacer(modifier = Modifier.height(20.dp)) - Menu { - ListItem1( - label = stringResource(R.string.external_send_from), - value = stringResource(balanceNameFor(request.source)) - ) - val destination = request.destination - val toValue = when (destination) { - is SendDestination.Identity -> - (uiState.identityResolution as? IdentityResolution.Found)?.username - ?: ExternalSendViewModel.shorten(destination.display) - else -> ExternalSendViewModel.shorten(destination.display) - } - ListItem1(label = stringResource(R.string.external_send_to), value = toValue) - val fee = if (confirm.feeLoading) null else confirm.fee - DashValueRow( - label = stringResource(R.string.external_send_network_fee), - value = fee?.let { approximate(it.fee.toDisplayString(), !it.exact) }, - unknown = unknown - ) - DashValueRow( - label = stringResource(R.string.external_send_total), - // A drain's total is the confirmed amount itself (exact); otherwise amount + fee. - value = confirm.total?.takeIf { fee != null || confirm.feeIncluded }?.let { total -> - approximate(total.toDisplayString(), !confirm.feeIncluded && fee?.exact != true) - }, - unknown = unknown - ) - ConfirmNotes(request.source, destination) - } - } - Row( - modifier = Modifier - .fillMaxWidth() - .padding(20.dp), - horizontalArrangement = Arrangement.spacedBy(20.dp) - ) { - DashButton( - modifier = Modifier.weight(1f), - text = stringResource(R.string.button_cancel), - style = Style.TintedGray, - size = Size.Large, - onClick = actions.onDismissConfirm - ) - DashButton( - modifier = Modifier.weight(1f), - text = stringResource(R.string.button_confirm), - style = Style.FilledBlue, - size = Size.Large, - onClick = actions.onConfirm - ) - } + val destination = request.destination + val toValue = when (destination) { + is SendDestination.Identity -> + (uiState.identityResolution as? IdentityResolution.Found)?.username + ?: ExternalSendViewModel.shorten(destination.display) + else -> ExternalSendViewModel.shorten(destination.display) } -} - -/** A confirm row whose value is a Dash amount: the Dash symbol before it, or [unknown] alone. */ -@Composable -private fun DashValueRow(label: String, value: String?, unknown: String) { - val colors = LocalDashColors.current - ListItem( - label = label, - trailingText = value ?: unknown, - trailingLeadingIcon = if (value != null) { - { - Icon( - painter = painterResource(org.dash.wallet.common.R.drawable.ic_dash_d_black), - contentDescription = null, - tint = colors.textPrimary, - modifier = Modifier.size(12.dp) - ) - } - } else { - null - } - ) -} - -@Composable -private fun approximate(value: String, estimate: Boolean): String = - if (estimate) stringResource(R.string.external_send_approximately, value) else value - -/** The confirm sheet's amount block (Figma "amount" 380x97): the same bar as the amount page, read-only. */ -@Composable -private fun ConfirmAmount(amount: Dash, rate: Fiat?, fiatCode: String?) { - val separator = remember { decimalSeparatorFor(Locale.getDefault()) } - val fiat = amount.toFiatAt(rate) - EnterAmount( - primaryAmount = localizeAmountForDisplay(amount.toDisplayString(), separator), - secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", - currencyCodes = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE), - selectedCurrencyIndex = 0, - showMaxButton = false, - showBalanceButton = false, - showPrimaryChevron = false, - showSecondary = fiat != null, - showCurrencyPicker = false, - modifier = Modifier.padding(horizontal = 20.dp) + SendConfirmSheet( + // What the recipient receives (a Core Max drain: the amount minus the fee). + amount = confirm.recipientAmount, + rate = uiState.rate, + fiatCode = uiState.fiatCode, + fromValue = stringResource(balanceNameFor(request.source)), + toValue = toValue, + fee = confirm.fee, + feeLoading = confirm.feeLoading, + total = confirm.total, + feeIncluded = confirm.feeIncluded, + notes = externalConfirmNotes(request.source, destination), + onDismiss = actions.onDismissConfirm, + onConfirm = actions.onConfirm ) } @@ -692,157 +560,22 @@ private fun ConfirmAmount(amount: Dash, rate: Fiat?, fiatCode: String?) { * Figma 7107:48425: from the Shielded balance to anywhere but Shielded, the send is not instant * and becomes public. An identity destination is paid into its Platform balance (AC8). */ -@Composable -private fun ConfirmNotes(source: SendBalance, destination: SendDestination) { - val notes = buildList { - if (source == SendBalance.SHIELDED && destination !is SendDestination.Shielded) { - add(R.string.external_send_shielded_not_instant) - add( - when (destination) { - is SendDestination.Core -> R.string.external_send_shielded_public_to_core - is SendDestination.Platform -> R.string.external_send_shielded_public_to_platform - else -> R.string.external_send_shielded_public_to_identity - } - ) - } - if (destination is SendDestination.Identity) { - add(R.string.external_send_identity_balance_note) - } - } - if (notes.isEmpty()) return - Column( - modifier = Modifier - .fillMaxWidth() - .padding(start = 10.dp, end = 10.dp, top = 18.dp, bottom = 14.dp), - verticalArrangement = Arrangement.spacedBy(16.dp) - ) { - notes.forEach { note -> - SystemMessage( - description = stringResource(note), - iconRes = org.dash.wallet.common.R.drawable.ic_info_blue - ) - } - } -} - -// ── Progress and outcome ──────────────────────────────────────────────────── - -/** - * The send is running on the app scope. Leaving does not cancel it; the outcome shows when the - * user opens the external send again. - */ -@Composable -private fun SendingOverlay(shieldedLeg: Boolean, onLeave: () -> Unit) { - val colors = LocalDashColors.current - Box( - modifier = Modifier - .fillMaxSize() - .background(Color(0x800A0B0D)) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, - contentAlignment = Alignment.Center - ) { - Column( - modifier = Modifier - .padding(horizontal = 40.dp) - .background(colors.backgroundSecondary, RoundedCornerShape(20.dp)) - .padding(30.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(16.dp) - ) { - CircularProgressIndicator(color = colors.dashBlue) - Text( - text = stringResource(R.string.external_send_sending_title), - style = MyTheme.Typography.TitleMediumSemibold, - color = colors.textPrimary, - textAlign = TextAlign.Center - ) - Text( - text = stringResource( - if (shieldedLeg) R.string.external_send_sending_shielded_message else R.string.external_send_sending_message - ), - style = MyTheme.Typography.BodyMedium, - color = colors.textSecondary, - textAlign = TextAlign.Center - ) - if (shieldedLeg) { - DashButton( - text = stringResource(R.string.external_send_close), - style = Style.TintedGray, - size = Size.Large, - onClick = onLeave - ) +internal fun externalConfirmNotes(source: SendBalance, destination: SendDestination): List = buildList { + if (source == SendBalance.SHIELDED && destination !is SendDestination.Shielded) { + add(R.string.external_send_shielded_not_instant) + add( + when (destination) { + is SendDestination.Core -> R.string.external_send_shielded_public_to_core + is SendDestination.Platform -> R.string.external_send_shielded_public_to_platform + else -> R.string.external_send_shielded_public_to_identity } - } - } -} - -/** The terminal outcome. Only Not sent offers to go back and edit; nothing offers a retry. */ -@Composable -private fun ResultDialog(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { - val content = resultContentFor(result, afterRestart) - ModalDialog( - showDialog = true, - onDismissRequest = onClose, - icon = ImageVector.vectorResource(content.icon), - heading = stringResource(content.title), - textBlocks = listOf(stringResource(content.message)), - buttons = listOf( - ButtonData( - label = stringResource(content.button), - onClick = onClose, - isPrimary = true, - style = Style.TintedGray - ) ) - ) -} - -/** What the outcome dialog shows for [result]. */ -internal data class ResultContent( - @DrawableRes val icon: Int, - @StringRes val title: Int, - @StringRes val message: Int, - @StringRes val button: Int -) - -internal fun resultContentFor(result: ExternalSendResult, afterRestart: Boolean = false): ResultContent = when (result) { - is ExternalSendResult.Sent -> ResultContent( - org.dash.wallet.common.R.drawable.ic_success_green, - R.string.external_send_sent_title, - R.string.external_send_sent_message, - R.string.external_send_close - ) - is ExternalSendResult.NotSent -> ResultContent( - org.dash.wallet.common.R.drawable.ic_error, - R.string.external_send_not_sent_title, - notSentMessageFor(result.reason), - R.string.external_send_edit - ) - ExternalSendResult.MayHaveGoneThrough -> ResultContent( - org.dash.wallet.common.R.drawable.ic_toast_info_warning, - R.string.external_send_ambiguous_title, - if (afterRestart) R.string.external_send_ambiguous_after_restart_message else R.string.external_send_ambiguous_message, - R.string.external_send_close - ) - ExternalSendResult.InterruptedFundsReturnToShielded -> ResultContent( - org.dash.wallet.common.R.drawable.ic_toast_info_warning, - R.string.external_send_interrupted_title, - R.string.external_send_interrupted_message, - R.string.external_send_close - ) + } + if (destination is SendDestination.Identity) { + add(R.string.external_send_identity_balance_note) + } } -@StringRes -internal fun notSentMessageFor(reason: NotSentReason): Int = when (reason) { - NotSentReason.INSUFFICIENT_FUNDS -> R.string.external_send_not_sent_insufficient_funds - NotSentReason.NOT_SYNCED -> R.string.external_send_not_sent_not_synced - NotSentReason.SIGNER_LOCKED -> R.string.external_send_not_sent_signer_locked - NotSentReason.NOT_SUPPORTED -> R.string.external_send_not_sent_not_supported - NotSentReason.PAYMENT_STILL_CONFIRMING -> R.string.external_send_not_sent_still_confirming - NotSentReason.IN_PROGRESS -> R.string.external_send_not_sent_in_progress - NotSentReason.BALANCE_CHANGED -> R.string.external_send_not_sent_balance_changed - NotSentReason.GENERIC -> R.string.external_send_not_sent_generic -} // ── Icons and names ───────────────────────────────────────────────────────── @@ -855,7 +588,7 @@ internal fun iconFor(source: SendBalance): Int = when (source) { } @DrawableRes -internal fun iconFor(destination: SendDestination): Int = iconFor(balanceOf(destination)) +internal fun iconFor(destination: SendDestination): Int = iconFor(balanceKindOf(destination)) @StringRes internal fun titleFor(source: SendBalance): Int = when (source) { @@ -866,7 +599,7 @@ internal fun titleFor(source: SendBalance): Int = when (source) { } @StringRes -internal fun titleFor(destination: SendDestination): Int = titleFor(balanceOf(destination)) +internal fun titleFor(destination: SendDestination): Int = titleFor(balanceKindOf(destination)) @StringRes internal fun balanceNameFor(source: SendBalance): Int = when (source) { @@ -876,13 +609,6 @@ internal fun balanceNameFor(source: SendBalance): Int = when (source) { SendBalance.IDENTITY -> R.string.external_send_balance_name_identity } -/** The kind of balance a destination is paid into, for its icon and name. */ -private fun balanceOf(destination: SendDestination): SendBalance = when (destination) { - is SendDestination.Core -> SendBalance.CORE - is SendDestination.Shielded -> SendBalance.SHIELDED - is SendDestination.Platform -> SendBalance.PLATFORM - is SendDestination.Identity -> SendBalance.IDENTITY -} @Preview(showBackground = true, widthDp = 420, heightDp = 926) @Composable diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/SendConfirmComponents.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/SendConfirmComponents.kt new file mode 100644 index 0000000000..90de4ada3b --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/SendConfirmComponents.kt @@ -0,0 +1,381 @@ +/* + * 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.send + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.ui.shielded.toDisplayString +import de.schildbach.wallet.ui.shielded.toFiatAt +import de.schildbach.wallet_test.R +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.money.Fiat +import org.dash.wallet.common.ui.components.ButtonData +import org.dash.wallet.common.ui.components.DASH_CURRENCY_CODE +import org.dash.wallet.common.ui.components.DashButton +import org.dash.wallet.common.ui.components.EnterAmount +import org.dash.wallet.common.ui.components.Grabber +import org.dash.wallet.common.ui.components.ListItem +import org.dash.wallet.common.ui.components.ListItem1 +import org.dash.wallet.common.ui.components.LocalDashColors +import org.dash.wallet.common.ui.components.Menu +import org.dash.wallet.common.ui.components.ModalDialog +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.components.SystemMessage +import org.dash.wallet.common.ui.components.TopNavBase +import org.dash.wallet.common.ui.enter_amount.decimalSeparatorFor +import org.dash.wallet.common.ui.enter_amount.localizeAmountForDisplay +import java.util.Locale + +// The confirm, progress and outcome UI shared by the Advanced-mode External Send (MO-1121) and +// Internal Transfers (MO-1125): one fee + confirm sheet, one sending overlay, one result dialog. + +// ── Sheets ────────────────────────────────────────────────────────────────── + +/** Dimmed backdrop and a bottom sheet with a grabber, as in the shielded flows. */ +@Composable +internal fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { + onDismiss() + } + ) { + Column( + modifier = Modifier + .align(Alignment.BottomCenter) + .fillMaxWidth() + .background( + LocalDashColors.current.backgroundPrimary, + RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp) + ) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + ) { + Grabber() + content() + } + } +} + +/** + * Figma 7076:47968 / 7107:48421: amount, From / To / Network fee / Total, info notes, buttons. + * + * @param amount what the recipient (or the own To balance) receives. + * @param fee null with [feeLoading] false = cannot be known before the send (never fabricated). + * @param total what leaves the balance; null while unknown. + * @param feeIncluded the fee comes OUT of the amount (a Core → Core drain): [total] is exact. + * @param notes the info notes under the rows, in order. + */ +@Composable +internal fun SendConfirmSheet( + amount: Dash, + rate: Fiat?, + fiatCode: String?, + fromValue: String, + toValue: String, + fee: FeeEstimate?, + feeLoading: Boolean, + total: Dash?, + feeIncluded: Boolean, + notes: List, + onDismiss: () -> Unit, + onConfirm: () -> Unit +) { + val unknown = stringResource(R.string.external_send_value_unknown) + SheetOverlay(onDismiss = onDismiss) { + TopNavBase( + leadingPart = false, + trailingPart = false, + title = stringResource(R.string.external_send_confirm_title) + ) + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + ) { + ConfirmAmount(amount, rate, fiatCode) + Spacer(modifier = Modifier.height(20.dp)) + Menu { + ListItem1(label = stringResource(R.string.external_send_from), value = fromValue) + ListItem1(label = stringResource(R.string.external_send_to), value = toValue) + val shownFee = if (feeLoading) null else fee + DashValueRow( + label = stringResource(R.string.external_send_network_fee), + value = shownFee?.let { approximate(it.fee.toDisplayString(), !it.exact) }, + unknown = unknown + ) + DashValueRow( + label = stringResource(R.string.external_send_total), + // A drain's total is the confirmed amount itself (exact); otherwise amount + fee. + value = total?.takeIf { shownFee != null || feeIncluded }?.let { value -> + approximate(value.toDisplayString(), !feeIncluded && shownFee?.exact != true) + }, + unknown = unknown + ) + ConfirmNotes(notes) + } + } + Row( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.button_cancel), + style = Style.TintedGray, + size = Size.Large, + onClick = onDismiss + ) + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.button_confirm), + style = Style.FilledBlue, + size = Size.Large, + onClick = onConfirm + ) + } + } +} + +/** A confirm row whose value is a Dash amount: the Dash symbol before it, or [unknown] alone. */ +@Composable +private fun DashValueRow(label: String, value: String?, unknown: String) { + val colors = LocalDashColors.current + ListItem( + label = label, + trailingText = value ?: unknown, + trailingLeadingIcon = if (value != null) { + { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_dash_d_black), + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(12.dp) + ) + } + } else { + null + } + ) +} + +@Composable +private fun approximate(value: String, estimate: Boolean): String = + if (estimate) stringResource(R.string.external_send_approximately, value) else value + +/** The confirm sheet's amount block (Figma "amount" 380x97): the same bar as the amount page, read-only. */ +@Composable +private fun ConfirmAmount(amount: Dash, rate: Fiat?, fiatCode: String?) { + val separator = remember { decimalSeparatorFor(Locale.getDefault()) } + val fiat = amount.toFiatAt(rate) + EnterAmount( + primaryAmount = localizeAmountForDisplay(amount.toDisplayString(), separator), + secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", + currencyCodes = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE), + selectedCurrencyIndex = 0, + showMaxButton = false, + showBalanceButton = false, + showPrimaryChevron = false, + showSecondary = fiat != null, + showCurrencyPicker = false, + modifier = Modifier.padding(horizontal = 20.dp) + ) +} + +/** The confirm sheet's info notes (Figma 7107:48425), in order; nothing when [notes] is empty. */ +@Composable +private fun ConfirmNotes(notes: List) { + if (notes.isEmpty()) return + Column( + modifier = Modifier + .fillMaxWidth() + .padding(start = 10.dp, end = 10.dp, top = 18.dp, bottom = 14.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + notes.forEach { note -> + SystemMessage( + description = stringResource(note), + iconRes = org.dash.wallet.common.R.drawable.ic_info_blue + ) + } + } +} + +// ── Progress and outcome ──────────────────────────────────────────────────── + +/** + * The send is running on the app scope. Leaving does not cancel it; the outcome shows when the + * user opens the external send again. + */ +@Composable +internal fun SendingOverlay(shieldedLeg: Boolean, onLeave: () -> Unit) { + val colors = LocalDashColors.current + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, + contentAlignment = Alignment.Center + ) { + Column( + modifier = Modifier + .padding(horizontal = 40.dp) + .background(colors.backgroundSecondary, RoundedCornerShape(20.dp)) + .padding(30.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + CircularProgressIndicator(color = colors.dashBlue) + Text( + text = stringResource(R.string.external_send_sending_title), + style = MyTheme.Typography.TitleMediumSemibold, + color = colors.textPrimary, + textAlign = TextAlign.Center + ) + Text( + text = stringResource( + if (shieldedLeg) R.string.external_send_sending_shielded_message else R.string.external_send_sending_message + ), + style = MyTheme.Typography.BodyMedium, + color = colors.textSecondary, + textAlign = TextAlign.Center + ) + if (shieldedLeg) { + DashButton( + text = stringResource(R.string.external_send_close), + style = Style.TintedGray, + size = Size.Large, + onClick = onLeave + ) + } + } + } +} + +/** The terminal outcome. Only Not sent offers to go back and edit; nothing offers a retry. */ +@Composable +internal fun ResultDialog(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { + val content = resultContentFor(result, afterRestart) + ModalDialog( + showDialog = true, + onDismissRequest = onClose, + icon = ImageVector.vectorResource(content.icon), + heading = stringResource(content.title), + textBlocks = listOf(stringResource(content.message)), + buttons = listOf( + ButtonData( + label = stringResource(content.button), + onClick = onClose, + isPrimary = true, + style = Style.TintedGray + ) + ) + ) +} + +/** What the outcome dialog shows for [result]. */ +internal data class ResultContent( + @DrawableRes val icon: Int, + @StringRes val title: Int, + @StringRes val message: Int, + @StringRes val button: Int +) + +internal fun resultContentFor(result: ExternalSendResult, afterRestart: Boolean = false): ResultContent = when (result) { + is ExternalSendResult.Sent -> ResultContent( + org.dash.wallet.common.R.drawable.ic_success_green, + R.string.external_send_sent_title, + R.string.external_send_sent_message, + R.string.external_send_close + ) + is ExternalSendResult.NotSent -> ResultContent( + org.dash.wallet.common.R.drawable.ic_error, + R.string.external_send_not_sent_title, + notSentMessageFor(result.reason), + R.string.external_send_edit + ) + ExternalSendResult.MayHaveGoneThrough -> ResultContent( + org.dash.wallet.common.R.drawable.ic_toast_info_warning, + R.string.external_send_ambiguous_title, + if (afterRestart) R.string.external_send_ambiguous_after_restart_message else R.string.external_send_ambiguous_message, + R.string.external_send_close + ) + ExternalSendResult.CompletesAutomatically -> ResultContent( + org.dash.wallet.common.R.drawable.ic_toast_info_warning, + R.string.internal_transfer_completes_automatically_title, + R.string.internal_transfer_completes_automatically_message, + R.string.external_send_close + ) + ExternalSendResult.InterruptedFundsReturnToShielded -> ResultContent( + org.dash.wallet.common.R.drawable.ic_toast_info_warning, + R.string.external_send_interrupted_title, + R.string.external_send_interrupted_message, + R.string.external_send_close + ) +} + +@StringRes +internal fun notSentMessageFor(reason: NotSentReason): Int = when (reason) { + NotSentReason.INSUFFICIENT_FUNDS -> R.string.external_send_not_sent_insufficient_funds + NotSentReason.NOT_SYNCED -> R.string.external_send_not_sent_not_synced + NotSentReason.SIGNER_LOCKED -> R.string.external_send_not_sent_signer_locked + NotSentReason.NOT_SUPPORTED -> R.string.external_send_not_sent_not_supported + NotSentReason.PAYMENT_STILL_CONFIRMING -> R.string.external_send_not_sent_still_confirming + NotSentReason.IN_PROGRESS -> R.string.external_send_not_sent_in_progress + NotSentReason.BALANCE_CHANGED -> R.string.external_send_not_sent_balance_changed + NotSentReason.GENERIC -> R.string.external_send_not_sent_generic +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt new file mode 100644 index 0000000000..a21fbce786 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt @@ -0,0 +1,110 @@ +/* + * 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.service.platform.sdk + +import de.schildbach.wallet.service.platform.sdk.SendBalance.CORE +import de.schildbach.wallet.service.platform.sdk.SendBalance.IDENTITY +import de.schildbach.wallet.service.platform.sdk.SendBalance.PLATFORM +import de.schildbach.wallet.service.platform.sdk.SendBalance.SHIELDED +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class InternalTransferModelsTest { + + private val supported = setOf( + CORE to SHIELDED, CORE to IDENTITY, + SHIELDED to CORE, SHIELDED to PLATFORM, SHIELDED to IDENTITY, + PLATFORM to SHIELDED, PLATFORM to IDENTITY, + IDENTITY to CORE, IDENTITY to PLATFORM + ) + + @Test + fun `the full 4x4 matrix`() { + for (from in SendBalance.entries) { + for (to in SendBalance.entries) { + val expected = when { + from == to -> InternalTransferSupport.SAME_BALANCE + (from to to) in supported -> InternalTransferSupport.SUPPORTED + else -> InternalTransferSupport.NOT_SUPPORTED_YET + } + assertEquals("$from → $to", expected, internalTransferSupport(from, to, true, true)) + assertEquals("$from → $to", (from to to) in supported, internalTransferPairSupported(from, to)) + } + } + // Exactly the three pairs the SDK cannot do yet are disabled. + val notYet = SendBalance.entries.flatMap { f -> SendBalance.entries.map { f to it } } + .filter { internalTransferSupport(it.first, it.second, true, true) == InternalTransferSupport.NOT_SUPPORTED_YET } + .toSet() + assertEquals(setOf(CORE to PLATFORM, PLATFORM to CORE, IDENTITY to SHIELDED), notYet) + } + + @Test + fun `shielded off disables every shielded pair, unknown identity every identity pair`() { + assertEquals(InternalTransferSupport.SHIELDED_OFF, internalTransferSupport(CORE, SHIELDED, false, true)) + assertEquals(InternalTransferSupport.SHIELDED_OFF, internalTransferSupport(SHIELDED, IDENTITY, false, true)) + assertEquals(InternalTransferSupport.NO_IDENTITY, internalTransferSupport(CORE, IDENTITY, true, false)) + assertEquals(InternalTransferSupport.NO_IDENTITY, internalTransferSupport(IDENTITY, PLATFORM, true, false)) + assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(IDENTITY, CORE, false, true)) + // The matrix wins over the flags: an unsupported pair is "not yet", whatever they say. + assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, internalTransferSupport(CORE, PLATFORM, false, false)) + } + + @Test + fun `identity is listed only for a user known to have one`() { + assertEquals(listOf(CORE, SHIELDED, PLATFORM, IDENTITY), internalTransferBalances(true)) + assertEquals(listOf(CORE, SHIELDED, PLATFORM), internalTransferBalances(false)) + assertEquals(listOf(CORE, SHIELDED, PLATFORM), internalTransferBalances(null)) + } + + @Test + fun `swap exchanges From and To (AC3)`() { + assertEquals(InternalTransferPair(SHIELDED, CORE), InternalTransferPair(CORE, SHIELDED).swapped()) + } + + @Test + fun `picking the other side's balance swaps (AC4)`() { + val pair = InternalTransferPair(CORE, SHIELDED) + assertEquals(InternalTransferPair(SHIELDED, CORE), pair.withFrom(SHIELDED)) + assertEquals(InternalTransferPair(SHIELDED, CORE), pair.withTo(CORE)) + assertEquals(InternalTransferPair(PLATFORM, SHIELDED), pair.withFrom(PLATFORM)) + assertEquals(InternalTransferPair(CORE, IDENTITY), pair.withTo(IDENTITY)) + assertEquals(pair, pair.withFrom(CORE)) + assertEquals(pair, pair.withTo(SHIELDED)) + } + + @Test(expected = IllegalArgumentException::class) + fun `From and To are never the same`() { + InternalTransferPair(CORE, CORE) + } + + @Test + fun `default pair`() { + assertEquals(InternalTransferPair(CORE, SHIELDED), defaultInternalTransferPair(true, true)) + assertEquals(InternalTransferPair(CORE, IDENTITY), defaultInternalTransferPair(false, true)) + assertEquals(InternalTransferPair(CORE, PLATFORM), defaultInternalTransferPair(false, false)) + } + + @Test + fun `shielded leg`() { + assertTrue(internalTransferHasShieldedLeg(SHIELDED, CORE)) + assertTrue(internalTransferHasShieldedLeg(PLATFORM, SHIELDED)) + assertFalse(internalTransferHasShieldedLeg(IDENTITY, PLATFORM)) + } +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt new file mode 100644 index 0000000000..e4e127c975 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -0,0 +1,351 @@ +/* + * 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.service.platform.sdk + +import de.schildbach.wallet.service.platform.sdk.SendBalance.CORE +import de.schildbach.wallet.service.platform.sdk.SendBalance.IDENTITY +import de.schildbach.wallet.service.platform.sdk.SendBalance.PLATFORM +import de.schildbach.wallet.service.platform.sdk.SendBalance.SHIELDED +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +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 org.dash.wallet.common.money.Dash +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.Base58 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.io.IOException + +class InternalTransferServiceImplTest { + + private companion object { + const val WALLET_A = "wallet-a" + const val WALLET_B = "wallet-b" + const val POOL_FEE_CREDITS = 1_234_567L + } + + private val network = AddressNetwork.DASH_TESTNET + private val unadvertised = Base58.encodeChecked(network.addressHeader, ByteArray(20) { (it + 1).toByte() }) + private val ownPlatform = "tdash1k-own-platform" + private val ownIdentity = Base58.encode(ByteArray(32) { (255 - it).toByte() }) + private val amount = Dash.COIN + + /** One External Send call, as the fake records it. */ + private data class Send( + val source: SendBalance, + val destination: SendDestination, + val amount: Dash, + val isMax: Boolean, + val walletId: String? + ) + + private class FakeExternal : ExternalSendService { + val sends = mutableListOf() + var result: ExternalSendResult = ExternalSendResult.Sent("txid") + var walletId: String? = WALLET_A + val pairFees = mutableMapOf, FeeEstimate?>() + val pairMax = mutableMapOf, Dash?>() + + override fun observeBalance(source: SendBalance): Flow = flowOf(Dash.COIN) + override fun observeHasIdentity(): Flow = flowOf(true) + override fun currentWalletIdOrNull(): String? = walletId + override suspend fun isOwnIdentity(identityIdBase58: String): Boolean? = true + override suspend fun resolveIdentity(identityIdBase58: String) = IdentityResolution.Found(null) + override suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash) = + error("internal transfers use the per-pair estimate") + override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = + error("internal transfers use the per-pair max") + override suspend fun estimateFeeForPair(source: SendBalance, destinationKind: SendBalance, amount: Dash) = + pairFees[source to destinationKind] + override suspend fun maxSendableForPair(source: SendBalance, destinationKind: SendBalance) = + pairMax[source to destinationKind] + override suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + sends += Send(source, destination, amount, isMax, expectedWalletIdHex) + return result + } + override suspend fun resumePendingPlatformFunding(): Int = 0 + } + + private inner class FakeSource : InternalTransferSource { + var committed: Boolean? = true + var shielded: Boolean? = true + var identity: Result = Result.success(ownIdentity) + val boundWallets = ArrayDeque() + var defaultBound: String? = WALLET_A + var coreAddress: () -> String = { unadvertised } + var platformAddress: String? = ownPlatform + var feeCredits: Long? = POOL_FEE_CREDITS + var shieldFromWalletResult: SdkWriteResult = + SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) + var shieldFromWalletThrows: Throwable? = null + var creditsResult: SdkWriteResult = SdkWriteResult.Broadcast(Unit) + val unshieldResults = ArrayDeque>() + val writes = mutableListOf() + var flag: Flow = flowOf(true) + + override suspend fun cutoverCommittedOrThrow(): Boolean = committed ?: throw IOException("unreadable") + override suspend fun shieldedEnabledOrThrow(): Boolean = shielded ?: throw IOException("unreadable") + override fun observeShieldedFlag(): Flow = flag + override suspend fun boundWalletIdOrNull(): String? = boundWallets.removeFirstOrNull() ?: defaultBound + override suspend fun ownIdentityIdOrThrow(): String? = identity.getOrThrow() + override fun unadvertisedCoreAddress(): String = coreAddress() + override suspend fun ownPlatformAddress(): String? = platformAddress + override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = feeCredits + + override suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult { + shieldFromWalletThrows?.let { throw it } + writes += "shieldFromWallet(${amount.duffs}, $walletIdHex)" + return shieldFromWalletResult + } + + override suspend fun shieldFromCredits(amount: Dash, walletIdHex: String): SdkWriteResult { + writes += "shieldFromCredits(${amount.duffs}, $walletIdHex)" + return creditsResult + } + + override suspend fun unshieldToCredits(amount: Dash, walletIdHex: String): SdkWriteResult { + writes += "unshieldToCredits(${amount.duffs}, $walletIdHex)" + return unshieldResults.removeFirstOrNull() ?: creditsResult + } + } + + private val external = FakeExternal() + private val source = FakeSource() + private val service = InternalTransferServiceImpl(external, source, Dispatchers.Unconfined, retryDelayMs = { 0L }) + + private fun transfer(from: SendBalance, to: SendBalance, isMax: Boolean = false, wallet: String? = WALLET_A) = + runBlocking { service.transfer(from, to, amount, isMax, wallet) } + + private fun assertNothingSubmitted() { + assertEquals(emptyList(), external.sends) + assertEquals(emptyList(), source.writes) + } + + // ── own destinations ───────────────────────────────────────────────────── + + @Test + fun `Core destinations are the unadvertised address`() { + assertEquals(ExternalSendResult.Sent("txid"), transfer(SHIELDED, CORE)) + assertEquals(ExternalSendResult.Sent("txid"), transfer(IDENTITY, CORE, isMax = true)) + assertEquals( + listOf( + Send(SHIELDED, SendDestination.Core(unadvertised), amount, false, WALLET_A), + Send(IDENTITY, SendDestination.Core(unadvertised), amount, true, WALLET_A) + ), + external.sends + ) + } + + @Test + fun `no unadvertised Core address fails closed before anything is submitted`() { + source.coreAddress = { throw IllegalStateException("no unadvertised destination post-cutover") } + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(SHIELDED, CORE)) + assertNothingSubmitted() + } + + @Test + fun `identity to Platform pays the own Platform address, and none fails closed`() { + assertEquals(ExternalSendResult.Sent("txid"), transfer(IDENTITY, PLATFORM)) + assertEquals(listOf(Send(IDENTITY, SendDestination.Platform(ownPlatform), amount, false, WALLET_A)), external.sends) + + external.sends.clear() + source.platformAddress = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, PLATFORM)) + assertNothingSubmitted() + } + + @Test + fun `identity destinations are the own identity`() { + transfer(CORE, IDENTITY) + transfer(SHIELDED, IDENTITY) + transfer(PLATFORM, IDENTITY) + assertEquals( + listOf(CORE, SHIELDED, PLATFORM).map { Send(it, SendDestination.Identity(ownIdentity), amount, false, WALLET_A) }, + external.sends + ) + assertEquals(emptyList(), source.writes) + } + + // ── self routes ────────────────────────────────────────────────────────── + + @Test + fun `Core to Shielded self-shields amount plus the pool fee, pinned`() { + assertEquals(ExternalSendResult.Sent(null), transfer(CORE, SHIELDED)) + val lock = amount.duffs + shieldPoolFeeDuffs(POOL_FEE_CREDITS) + assertEquals(listOf("shieldFromWallet($lock, $WALLET_A)"), source.writes) + assertEquals(emptyList(), external.sends) + } + + @Test + fun `Core to Shielded outcomes map without a retry`() { + source.shieldFromWalletResult = SdkWriteResult.Broadcast(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY) + assertEquals(ExternalSendResult.CompletesAutomatically, transfer(CORE, SHIELDED)) + source.shieldFromWalletResult = SdkWriteResult.Ambiguous(IllegalStateException("unknown")) + assertEquals(ExternalSendResult.MayHaveGoneThrough, transfer(CORE, SHIELDED)) + source.shieldFromWalletResult = SdkWriteResult.NotBroadcast("shielded runtime not ready") + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), transfer(CORE, SHIELDED)) + assertEquals(3, source.writes.size) + } + + @Test + fun `Core to Shielded with an unknown pool fee is not sent`() { + source.feeCredits = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(CORE, SHIELDED)) + assertNothingSubmitted() + } + + @Test + fun `Platform to Shielded shields from credits, Shielded to Platform unshields, both pinned`() { + assertEquals(ExternalSendResult.Sent(null), transfer(PLATFORM, SHIELDED)) + assertEquals(ExternalSendResult.Sent(null), transfer(SHIELDED, PLATFORM)) + assertEquals( + listOf("shieldFromCredits(${amount.duffs}, $WALLET_A)", "unshieldToCredits(${amount.duffs}, $WALLET_A)"), + source.writes + ) + assertEquals(emptyList(), external.sends) + } + + @Test + fun `a Max unshield retries once with the reported fee deficit`() { + val credits = dashToCredits(amount) + source.unshieldResults += SdkWriteResult.NotBroadcast( + "Insufficient shielded balance: available $credits, required ${credits + 1000}" + ) + transfer(SHIELDED, PLATFORM, isMax = true) + assertEquals(2, source.writes.size) + } + + // ── gating ─────────────────────────────────────────────────────────────── + + @Test + fun `the matrix is enforced by the service`() { + for ((from, to) in listOf(CORE to PLATFORM, PLATFORM to CORE, IDENTITY to SHIELDED, CORE to CORE)) { + assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(from, to)) + } + assertNothingSubmitted() + } + + @Test + fun `shielded flag off or unreadable, no identity, or no cutover refuse`() { + source.shielded = false + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(CORE, SHIELDED)) + source.shielded = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(SHIELDED, CORE)) + source.shielded = true + source.identity = Result.success(null) + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(CORE, IDENTITY)) + source.identity = Result.failure(IOException("unreadable")) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, CORE)) + source.identity = Result.success(ownIdentity) + source.committed = false + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, CORE)) + source.committed = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, CORE)) + assertNothingSubmitted() + } + + @Test + fun `a wallet other than the confirmed one is not sent`() { + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(SHIELDED, CORE, wallet = WALLET_B)) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(SHIELDED, CORE, wallet = null)) + source.defaultBound = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(CORE, SHIELDED)) + assertNothingSubmitted() + } + + @Test + fun `the wallet changing after the first check is caught before the write`() { + source.boundWallets += listOf(WALLET_A, WALLET_B) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(CORE, SHIELDED)) + source.boundWallets += listOf(WALLET_A, WALLET_B) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(SHIELDED, CORE)) + assertNothingSubmitted() + } + + @Test + fun `non-positive amounts are refused`() { + val result = runBlocking { service.transfer(SHIELDED, CORE, Dash.ZERO, false, WALLET_A) } + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), result) + assertNothingSubmitted() + } + + @Test + fun `cancellation is rethrown`() { + source.shieldFromWalletThrows = CancellationException("cancelled") + try { + transfer(CORE, SHIELDED) + fail("expected CancellationException") + } catch (e: CancellationException) { + assertEquals("cancelled", e.message) + } + // The single-flight latch was released. + source.shieldFromWalletThrows = null + assertEquals(ExternalSendResult.Sent(null), transfer(CORE, SHIELDED)) + } + + @Test + fun `an unclassified failure in a write may have gone through`() { + source.shieldFromWalletThrows = IllegalStateException("boom") + assertEquals(ExternalSendResult.MayHaveGoneThrough, transfer(CORE, SHIELDED)) + } + + // ── fee, max and reads ─────────────────────────────────────────────────── + + @Test + fun `fee and max come from the per-pair estimate, null for unsupported pairs`() = runBlocking { + val fee = FeeEstimate(Dash(1000), exact = false) + external.pairFees[SHIELDED to CORE] = fee + external.pairMax[SHIELDED to CORE] = Dash(5000) + external.pairFees[CORE to PLATFORM] = fee + external.pairMax[CORE to PLATFORM] = Dash(5000) + assertEquals(fee, service.estimateFee(SHIELDED, CORE, amount)) + assertEquals(Dash(5000), service.maxSendable(SHIELDED, CORE)) + assertNull(service.estimateFee(CORE, PLATFORM, amount)) + assertNull(service.maxSendable(CORE, PLATFORM)) + assertNull(service.estimateFee(PLATFORM, SHIELDED, amount)) + } + + @Test + fun `an unreadable shielded flag reads as off and keeps observing`() = runBlocking { + var reads = 0 + source.flag = flow { + if (reads++ == 0) throw IOException("datastore") + emit(true) + } + assertEquals(listOf(false, true), service.observeShieldedEnabled().take(2).toList()) + assertTrue(reads >= 2) + source.flag = MutableStateFlow(null) + assertEquals(false, service.observeShieldedEnabled().first()) + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt index c7569a1fd7..d7f4e0f996 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt @@ -17,80 +17,34 @@ 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()) + fun `Internal is always shown where Platform is supported, whatever the shielded flag`() { + assertEquals(threeTabs, advancedPaymentsTabIds(supportsPlatform = true)) + assertEquals(twoTabs, advancedPaymentsTabIds(supportsPlatform = false)) } @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) + fun `view model state has the tab set from the start`() { + assertEquals(threeTabs, AdvancedPaymentsViewModel(supportsPlatform = true).uiState.value.tabIds) + assertEquals(twoTabs, AdvancedPaymentsViewModel(supportsPlatform = false).uiState.value.tabIds) } @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) + fun `Basic mode keeps its shielded gating`() { + // PaymentsFragment shows Internal only with the shielded flag on; Advanced no longer reads it. + assertEquals(twoTabs, PaymentsFragment.tabIdsFor(showInternalTab = false)) + assertEquals(threeTabs, PaymentsFragment.tabIdsFor(showInternalTab = true)) } @Test diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt new file mode 100644 index 0000000000..6ef83f8a42 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -0,0 +1,378 @@ +/* + * 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.internal + +import androidx.lifecycle.SavedStateHandle +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.InternalTransferService +import de.schildbach.wallet.service.platform.sdk.InternalTransferSupport +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.SendBalance.CORE +import de.schildbach.wallet.service.platform.sdk.SendBalance.IDENTITY +import de.schildbach.wallet.service.platform.sdk.SendBalance.PLATFORM +import de.schildbach.wallet.service.platform.sdk.SendBalance.SHIELDED +import de.schildbach.wallet.ui.payments.send.ExternalSendInFlightMarker +import de.schildbach.wallet.ui.payments.send.ExternalSendStatus +import de.schildbach.wallet_test.R +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.dash.wallet.common.data.WalletUIConfig +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.services.ExchangeRatesProvider +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 + +@OptIn(ExperimentalCoroutinesApi::class) +class InternalTransferViewModelTest { + + private companion object { + const val WALLET_A = "wallet-a" + } + + private val oneDash = Dash.COIN + private val twoDash = Dash.COIN * 2L + + /** A fake service: every answer is a field the test sets; every transfer is recorded. */ + private class FakeService : InternalTransferService { + val balances = SendBalance.entries.associateWith { MutableStateFlow(null) } + val hasIdentity = MutableStateFlow(true) + val shielded = MutableStateFlow(true) + var fee: FeeEstimate? = null + val max = mutableMapOf, Dash?>() + var gate: CompletableDeferred? = null + var result: ExternalSendResult = ExternalSendResult.Sent(null) + val transfers = mutableListOf() + var walletId: String? = WALLET_A + + override fun observeBalance(balance: SendBalance): Flow = balances.getValue(balance) + override fun observeHasIdentity(): Flow = hasIdentity + override fun observeShieldedEnabled(): Flow = shielded + override fun currentWalletIdOrNull(): String? = walletId + override suspend fun estimateFee(from: SendBalance, to: SendBalance, amount: Dash) = fee + override suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? = max[from to to] + override suspend fun transfer( + from: SendBalance, + to: SendBalance, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + transfers += InternalTransferRequest(from, to, amount, isMax, expectedWalletIdHex) + return gate?.await() ?: result + } + } + + private class FakeMarker : ExternalSendInFlightMarker { + var value = false + override suspend fun isSet(): Boolean = value + override suspend fun set() { + value = true + } + override suspend fun clear() { + value = false + } + } + + private val service = FakeService() + private val marker = FakeMarker() + private lateinit var executor: InternalTransferExecutor + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + executor = InternalTransferExecutor(service, marker, CoroutineScope(UnconfinedTestDispatcher())) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun buildViewModel(savedState: SavedStateHandle = SavedStateHandle()): InternalTransferViewModel { + val walletUIConfig = mockk { + every { observe(WalletUIConfig.SELECTED_CURRENCY) } returns flowOf("USD") + } + val rates = mockk { + every { observeExchangeRate(any()) } returns flowOf(null) + } + return InternalTransferViewModel(service, executor, walletUIConfig, rates, savedState) + } + + private fun InternalTransferViewModel.type(amount: String) { + amount.forEach { onKeyInput(it.toString()) } + } + + private val InternalTransferViewModel.state get() = uiState.value + + // ── pair ───────────────────────────────────────────────────────────────── + + @Test + fun `default pair follows the flag and identity until the user picks`() { + val viewModel = buildViewModel() + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + service.shielded.value = false + assertEquals(CORE to IDENTITY, viewModel.state.from to viewModel.state.to) + service.hasIdentity.value = false + assertEquals(CORE to PLATFORM, viewModel.state.from to viewModel.state.to) + + service.shielded.value = true + viewModel.onSwap() + assertEquals(SHIELDED to CORE, viewModel.state.from to viewModel.state.to) + service.hasIdentity.value = true + // The user's pair stays. + assertEquals(SHIELDED to CORE, viewModel.state.from to viewModel.state.to) + } + + @Test + fun `swap exchanges From and To (AC3)`() { + val viewModel = buildViewModel() + viewModel.onSwap() + assertEquals(SHIELDED to CORE, viewModel.state.from to viewModel.state.to) + viewModel.onSwap() + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + } + + @Test + fun `picking the other side's balance swaps (AC4)`() { + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.FROM) + viewModel.onBalancePicked(SHIELDED) + assertEquals(SHIELDED to CORE, viewModel.state.from to viewModel.state.to) + assertNull(viewModel.state.picker) + + viewModel.onShowPicker(InternalTransferPicker.TO) + viewModel.onBalancePicked(SHIELDED) + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + + viewModel.onShowPicker(InternalTransferPicker.TO) + viewModel.onBalancePicked(IDENTITY) + assertEquals(CORE to IDENTITY, viewModel.state.from to viewModel.state.to) + } + + @Test + fun `a pick that leads to an unsupported pair is refused`() { + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.TO) + assertFalse(viewModel.state.pickable(InternalTransferPicker.TO, PLATFORM)) + viewModel.onBalancePicked(PLATFORM) + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + } + + @Test + fun `shielded flag off disables Shielded in the pickers`() { + service.shielded.value = false + val viewModel = buildViewModel() + assertTrue(SHIELDED in viewModel.state.balances) + assertFalse(viewModel.state.pickable(InternalTransferPicker.TO, SHIELDED)) + assertFalse(viewModel.state.pickable(InternalTransferPicker.FROM, SHIELDED)) + assertTrue(viewModel.state.pickable(InternalTransferPicker.FROM, PLATFORM)) + } + + @Test + fun `identity is hidden without one, and while unknown`() { + service.hasIdentity.value = null + val viewModel = buildViewModel() + assertFalse(IDENTITY in viewModel.state.balances) + service.hasIdentity.value = false + assertFalse(IDENTITY in viewModel.state.balances) + service.hasIdentity.value = true + assertTrue(IDENTITY in viewModel.state.balances) + } + + @Test + fun `a chosen Identity pair falls back to the default when the identity goes`() { + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.TO) + viewModel.onBalancePicked(IDENTITY) + service.hasIdentity.value = false + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + assertFalse(viewModel.state.pairChosenByUser) + } + + // ── amount ─────────────────────────────────────────────────────────────── + + @Test + fun `Max is the service's max for the pair`() { + service.balances.getValue(CORE).value = twoDash + service.max[CORE to SHIELDED] = oneDash + val viewModel = buildViewModel() + viewModel.onMaxClick() + assertEquals(oneDash, viewModel.state.amount) + assertTrue(viewModel.state.isMax) + assertTrue(viewModel.state.canContinue) + } + + @Test + fun `an amount above Max is insufficient and disables Continue (AC7)`() { + service.balances.getValue(CORE).value = twoDash + service.max[CORE to SHIELDED] = oneDash + val viewModel = buildViewModel() + viewModel.type("1.5") + assertTrue(viewModel.state.insufficientBalance) + assertFalse(viewModel.state.canContinue) + viewModel.onKeyInput("back") + assertFalse(viewModel.state.insufficientBalance) + assertTrue(viewModel.state.canContinue) + } + + @Test + fun `an unknown balance blocks Continue`() { + val viewModel = buildViewModel() + viewModel.type("1") + assertNull(viewModel.state.balance) + assertFalse(viewModel.state.canContinue) + } + + @Test + fun `an unsupported pair (reached by a swap) blocks Continue`() { + service.balances.getValue(IDENTITY).value = twoDash + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.FROM) + viewModel.onBalancePicked(SHIELDED) // Shielded → Core + viewModel.onShowPicker(InternalTransferPicker.TO) + viewModel.onBalancePicked(IDENTITY) // Shielded → Identity + viewModel.onSwap() + assertEquals(IDENTITY to SHIELDED, viewModel.state.from to viewModel.state.to) + assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, viewModel.state.support) + viewModel.type("1") + assertFalse(viewModel.state.canContinue) + viewModel.onContinue() + assertNull(viewModel.state.confirm) + } + + @Test + fun `changing the pair drops Max but keeps its exact amount`() { + service.balances.getValue(CORE).value = twoDash + service.max[CORE to SHIELDED] = oneDash + val viewModel = buildViewModel() + viewModel.onMaxClick() + viewModel.onShowPicker(InternalTransferPicker.TO) + viewModel.onBalancePicked(IDENTITY) + assertFalse(viewModel.state.isMax) + assertEquals(oneDash, viewModel.state.amount) + } + + // ── confirm and transfer ───────────────────────────────────────────────── + + @Test + fun `Continue builds the confirm for the own To balance with the captured wallet`() { + service.balances.getValue(CORE).value = twoDash + service.fee = FeeEstimate(Dash(1000), exact = false) + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + val confirm = requireNotNull(viewModel.state.confirm) + assertEquals(InternalTransferRequest(CORE, SHIELDED, oneDash, false, WALLET_A), confirm.request) + assertFalse(confirm.feeLoading) + assertEquals(oneDash + Dash(1000), confirm.total) + assertEquals(confirm.request, viewModel.confirmedRequest()) + } + + @Test + fun `submit runs exactly the confirmed request and mirrors the executor`() { + service.balances.getValue(CORE).value = twoDash + service.gate = CompletableDeferred() + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + assertTrue(viewModel.submit(request)) + assertEquals(ExternalSendStatus.Sending(shieldedLeg = true), viewModel.state.status) + assertFalse(viewModel.state.formEditable) + assertNull(viewModel.state.confirm) + + viewModel.onHideSending() + assertTrue(viewModel.state.sendingHidden) + + service.gate?.complete(ExternalSendResult.Sent(null)) + assertEquals(ExternalSendStatus.Done(ExternalSendResult.Sent(null)), viewModel.state.status) + assertFalse(viewModel.state.sendingHidden) + assertEquals(listOf(request), service.transfers) + + viewModel.onResultAcknowledged() + assertEquals(ExternalSendStatus.Idle, viewModel.state.status) + assertEquals("0", viewModel.state.amountText) + assertFalse(marker.value) + } + + @Test + fun `a dismissed confirm is never submitted`() { + service.balances.getValue(CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + viewModel.onDismissConfirm() + assertFalse(viewModel.submit(request)) + assertTrue(service.transfers.isEmpty()) + } + + @Test + fun `Not sent keeps the amount for a retry (AC14)`() { + service.balances.getValue(CORE).value = twoDash + service.result = ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS) + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + viewModel.submit(requireNotNull(viewModel.confirmedRequest())) + viewModel.onResultAcknowledged() + assertEquals(ExternalSendStatus.Idle, viewModel.state.status) + assertEquals(oneDash, viewModel.state.amount) + assertTrue(viewModel.state.canContinue) + } + + @Test + fun `pair and amount survive process death`() { + service.balances.getValue(SHIELDED).value = twoDash + val savedState = SavedStateHandle() + val first = buildViewModel(savedState) + first.onSwap() + first.type("1.5") + val restored = buildViewModel(savedState) + assertEquals(SHIELDED to CORE, restored.state.from to restored.state.to) + assertEquals("1.5", restored.state.amountText) + assertTrue(restored.state.pairChosenByUser) + } + + @Test + fun `confirm notes reuse the External Send notes`() { + assertEquals( + listOf(R.string.external_send_shielded_not_instant, R.string.external_send_shielded_public_to_core), + internalConfirmNotes(SHIELDED, CORE) + ) + assertEquals(listOf(R.string.internal_transfer_withdrawal_not_instant), internalConfirmNotes(IDENTITY, CORE)) + assertEquals(emptyList(), internalConfirmNotes(CORE, SHIELDED)) + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index e319dad77d..df90c9bb02 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -93,6 +93,8 @@ class ExternalSendViewModelTest { override suspend fun resolveIdentity(identityIdBase58: String): IdentityResolution = resolution override suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash) = fee override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = max[source] + override suspend fun estimateFeeForPair(source: SendBalance, destinationKind: SendBalance, amount: Dash) = fee + override suspend fun maxSendableForPair(source: SendBalance, destinationKind: SendBalance): Dash? = max[source] override suspend fun send( source: SendBalance, destination: SendDestination, From bc792e6c966ee3f41b06df4cecce0af65e36c445 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sat, 7 Nov 2026 09:53:00 -0800 Subject: [PATCH 02/17] fix(payments): address pre-review round 1 on Internal transfers (MO-1125) - Identity -> Platform resolves the wallet's own Platform address through a wallet-pinned SDK address-store read that does not need the shielded runtime, so the pair works with the shielded flag off. - A chosen or restored pair is dropped only on confirmed absence (hasIdentity == false / shielded flag == false); an unreadable shielded flag is now null (unknown), not false. - Focused InternalTransferExecutor tests for the durable in-flight marker. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/InternalTransferService.kt | 7 +- .../sdk/InternalTransferServiceImpl.kt | 22 +- .../platform/sdk/ShieldedBalanceService.kt | 10 + .../sdk/ShieldedBalanceServiceImpl.kt | 11 + .../internal/InternalTransferViewModel.kt | 17 +- .../sdk/InternalTransferServiceImplTest.kt | 18 +- .../internal/InternalTransferExecutorTest.kt | 210 ++++++++++++++++++ .../internal/InternalTransferViewModelTest.kt | 59 ++++- 8 files changed, 331 insertions(+), 23 deletions(-) create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt index 80637f1a0c..ac91c0c7cf 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt @@ -37,10 +37,11 @@ interface InternalTransferService { fun observeHasIdentity(): Flow /** - * `USE_KOTLIN_SDK_SHIELDED`, error-preserving: an unreadable flag emits false (off) and - * keeps observing. Never completes on a transient error. + * `USE_KOTLIN_SDK_SHIELDED`, error-preserving: true/false when read (absent = false), null + * when unreadable (unknown: treated as off for gating, never as a confirmed "off"); keeps + * observing and never completes on a transient error. */ - fun observeShieldedEnabled(): Flow + fun observeShieldedEnabled(): Flow /** [ExternalSendService.currentWalletIdOrNull]: captured, without suspending, at confirmation. */ fun currentWalletIdOrNull(): String? diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index 7d68af637b..f6ea806d3c 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -64,8 +64,11 @@ internal interface InternalTransferSource { */ fun unadvertisedCoreAddress(): String - /** [ShieldedBalanceService.platformReceiveAddress]: the wallet's own Platform address, or null. */ - suspend fun ownPlatformAddress(): String? + /** + * [ShieldedBalanceService.ownPlatformAddressOf]: the own Platform address of [walletIdHex] from + * the SDK's address store (no shielded flag or runtime needed), or null. + */ + suspend fun ownPlatformAddress(walletIdHex: String): String? suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? @@ -105,7 +108,8 @@ internal class DashSdkInternalTransferSource( override fun unadvertisedCoreAddress(): String = walletData.unadvertisedDestinationLive().toBase58() - override suspend fun ownPlatformAddress(): String? = shieldedBalanceService.platformReceiveAddress() + override suspend fun ownPlatformAddress(walletIdHex: String): String? = + shieldedBalanceService.ownPlatformAddressOf(walletIdHex) override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = shieldedBalanceService.estimateShieldedFeeCredits(kind) @@ -137,8 +141,8 @@ internal class DashSdkInternalTransferSource( * - Shielded → Platform: [ShieldedBalanceService.unshieldToCreditsPinned] (own Platform address), * with the shielded Max fee retry. * - Platform → Shielded: [ShieldedBalanceService.shieldFromCreditsPinned]. - * - Identity → Platform: [ExternalSendService.send] to the wallet's own Platform address - * ([ShieldedBalanceService.platformReceiveAddress]); unavailable = Not sent. + * - Identity → Platform: [ExternalSendService.send] to the confirmed wallet's own Platform address + * ([ShieldedBalanceService.ownPlatformAddressOf], no shielded flag needed); unavailable = Not sent. * * Funds safety, in order, for every [transfer]: single-flight; positive amount; the pair matrix; * cutover committed and (for a shielded leg) the shielded flag, error-preserving; the wallet @@ -178,10 +182,10 @@ class InternalTransferServiceImpl internal constructor( override fun observeHasIdentity(): Flow = externalSendService.observeHasIdentity() - override fun observeShieldedEnabled(): Flow = + override fun observeShieldedEnabled(): Flow = source.observeShieldedFlag() - .map { it == true } - .retryReadErrors("shielded flag", false, retryDelayMs) + .map { it == true } + .retryReadErrors("shielded flag", null, retryDelayMs) .distinctUntilChanged() override fun currentWalletIdOrNull(): String? = externalSendService.currentWalletIdOrNull() @@ -286,7 +290,7 @@ class InternalTransferServiceImpl internal constructor( SendBalance.PLATFORM -> when (from) { SendBalance.SHIELDED -> unshieldToOwnPlatform(pair, walletIdHex, amount, isMax) else -> { - val address = readOrNull("own platform address") { source.ownPlatformAddress() } + val address = readOrNull("own platform address") { source.ownPlatformAddress(walletIdHex) } ?: return notSent(pair, NotSentReason.GENERIC, "own platform address unavailable") delegate(pair, walletIdHex, from, SendDestination.Platform(address), amount, isMax) } 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 a54db7a64f..4dbdef7917 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -360,6 +360,16 @@ interface ShieldedBalanceService { */ suspend fun platformReceiveAddress(): String? + /** + * The own Platform (DIP-17) receive address of the SDK wallet [walletIdHex] — the same row + * [platformReceiveAddress] picks — read straight from the SDK's address store. Unlike + * [platformReceiveAddress] it needs only the SDK started, NOT the shielded flag or runtime, + * and it is pinned to the given wallet. Null when [walletIdHex] is malformed, the store has + * no row for it, or the read fails (fail closed). Never throws (except cancellation); the + * address is never logged. + */ + suspend fun ownPlatformAddressOf(walletIdHex: String): 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 b0c4023118..6a516914ce 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -2138,6 +2138,17 @@ class ShieldedBalanceServiceImpl internal constructor( } } + override suspend fun ownPlatformAddressOf(walletIdHex: String): String? { + val walletId = walletIdFromHex(walletIdHex) ?: return null + return try { + source.ownPlatformAddressOrNull(walletId) + } catch (t: Throwable) { + if (t is CancellationException) throw t + log.warn("failed to read the wallet's own platform address", t) + null + } + } + override suspend fun shieldFromCredits(amount: Dash): SdkWriteResult = shieldFromCreditsInternal(amount, expectedWalletIdHex = null) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt index 93e6ecf2ca..f2708e16b3 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -77,7 +77,8 @@ data class InternalTransferConfirm( /** * Single UI state of the Advanced-mode Internal tab (MO-1125). * - * @property shieldedEnabled `USE_KOTLIN_SDK_SHIELDED`; null until read (an unreadable flag is off). + * @property shieldedEnabled `USE_KOTLIN_SDK_SHIELDED`; null = unknown (not read yet, or unreadable): + * Shielded pairs are disabled, but a chosen Shielded pair is kept. * @property hasIdentity null = unknown: Identity is hidden. * @property pairChosenByUser the user changed From/To; until then the default pair * ([defaultInternalTransferPair]) follows the inputs as they arrive. @@ -273,18 +274,22 @@ class InternalTransferViewModel @Inject constructor( /** * Until the user changes the pair, follow the default as the flag and identity arrive. A - * user's pair that is no longer listed (identity gone) falls back to the default. + * user's (or restored) pair is dropped for the default only on CONFIRMED absence: the user + * has no identity ([InternalTransferUIState.hasIdentity] false) for an Identity pair, or the + * shielded flag is read as off (false) for a Shielded pair. While either is unknown (null: + * not read yet, or a read error) the pair is kept and Continue stays disabled. */ private fun reconcilePair() { val state = _uiState.value - val listed = state.from in state.balances && state.to in state.balances - if (state.pairChosenByUser && listed) return - val pair = defaultInternalTransferPair(state.shieldedEnabled == true, state.hasIdentity == true) if (state.pairChosenByUser) { + val sides = setOf(state.from, state.to) + val identityGone = SendBalance.IDENTITY in sides && state.hasIdentity == false + val shieldedOff = SendBalance.SHIELDED in sides && state.shieldedEnabled == false + if (!identityGone && !shieldedOff) return _uiState.update { it.copy(pairChosenByUser = false) } savedState[KEY_PAIR_CHOSEN] = false } - setPair(pair, byUser = false) + setPair(defaultInternalTransferPair(state.shieldedEnabled == true, state.hasIdentity == true), byUser = false) } // ── From / To ──────────────────────────────────────────────────────────── diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt index e4e127c975..6c647fe053 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -120,7 +120,11 @@ class InternalTransferServiceImplTest { override suspend fun boundWalletIdOrNull(): String? = boundWallets.removeFirstOrNull() ?: defaultBound override suspend fun ownIdentityIdOrThrow(): String? = identity.getOrThrow() override fun unadvertisedCoreAddress(): String = coreAddress() - override suspend fun ownPlatformAddress(): String? = platformAddress + val platformAddressReads = mutableListOf() + override suspend fun ownPlatformAddress(walletIdHex: String): String? { + platformAddressReads += walletIdHex + return platformAddress + } override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = feeCredits override suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult { @@ -185,6 +189,14 @@ class InternalTransferServiceImplTest { assertNothingSubmitted() } + @Test + fun `identity to Platform works with the shielded flag off, pinned to the confirmed wallet`() { + source.shielded = false + assertEquals(ExternalSendResult.Sent("txid"), transfer(IDENTITY, PLATFORM)) + assertEquals(listOf(WALLET_A), source.platformAddressReads) + assertEquals(listOf(Send(IDENTITY, SendDestination.Platform(ownPlatform), amount, false, WALLET_A)), external.sends) + } + @Test fun `identity destinations are the own identity`() { transfer(CORE, IDENTITY) @@ -337,13 +349,13 @@ class InternalTransferServiceImplTest { } @Test - fun `an unreadable shielded flag reads as off and keeps observing`() = runBlocking { + fun `an unreadable shielded flag reads as unknown and keeps observing`() = runBlocking { var reads = 0 source.flag = flow { if (reads++ == 0) throw IOException("datastore") emit(true) } - assertEquals(listOf(false, true), service.observeShieldedEnabled().take(2).toList()) + assertEquals(listOf(null, true), service.observeShieldedEnabled().take(2).toList()) assertTrue(reads >= 2) source.flag = MutableStateFlow(null) assertEquals(false, service.observeShieldedEnabled().first()) diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt new file mode 100644 index 0000000000..2d22c5189c --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt @@ -0,0 +1,210 @@ +/* + * 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.internal + +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.InternalTransferService +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.ui.payments.send.ExternalSendInFlightMarker +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import org.dash.wallet.common.money.Dash +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** [InternalTransferExecutor]'s durable-marker contract, mirroring the External Send executor's tests. */ +@OptIn(ExperimentalCoroutinesApi::class) +class InternalTransferExecutorTest { + + private val request = InternalTransferRequest(SendBalance.SHIELDED, SendBalance.CORE, Dash.COIN, false, "wallet-a") + + private class FakeService : InternalTransferService { + var gate: CompletableDeferred? = null + var result: ExternalSendResult = ExternalSendResult.Sent(null) + val transfers = mutableListOf() + + override fun observeBalance(balance: SendBalance): Flow = flowOf(null) + override fun observeHasIdentity(): Flow = flowOf(null) + override fun observeShieldedEnabled(): Flow = flowOf(null) + override fun currentWalletIdOrNull(): String? = null + override suspend fun estimateFee(from: SendBalance, to: SendBalance, amount: Dash): FeeEstimate? = null + override suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? = null + override suspend fun transfer( + from: SendBalance, + to: SendBalance, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + transfers += InternalTransferRequest(from, to, amount, isMax, expectedWalletIdHex) + return gate?.await() ?: result + } + } + + /** The persisted flag; reads, writes and clears can be gated or made to throw. */ + private class FakeMarker : ExternalSendInFlightMarker { + var value = false + var failReads = false + var failWrites = false + var readGate: CompletableDeferred? = null + var clearGate: CompletableDeferred? = null + var clearCalls = 0 + val log = mutableListOf() + + override suspend fun isSet(): Boolean { + readGate?.await() + if (failReads) throw java.io.IOException("datastore") + return value + } + + override suspend fun set() { + if (failWrites) throw java.io.IOException("datastore") + log += "set" + value = true + } + + override suspend fun clear() { + clearCalls++ + clearGate?.await() + if (failWrites) throw java.io.IOException("datastore") + log += "clear" + value = false + } + } + + private val service = FakeService() + private val marker = FakeMarker() + + private fun newExecutor() = InternalTransferExecutor(service, marker, CoroutineScope(UnconfinedTestDispatcher())) + + @Test + fun `nothing can be submitted until the startup marker has been read`() { + val readGate = CompletableDeferred() + marker.readGate = readGate + val executor = newExecutor() + assertEquals(InternalTransferExecution.Restoring, executor.state.value) + assertFalse(executor.submit(request)) + assertTrue(service.transfers.isEmpty()) + + readGate.complete(Unit) + assertEquals(InternalTransferExecution.Idle, executor.state.value) + assertTrue(executor.submit(request)) + } + + @Test + fun `a set or unreadable startup marker restarts into may-have-gone-through`() { + marker.value = true + assertEquals(InternalTransferExecution.InterruptedByRestart, newExecutor().state.value) + marker.value = false + marker.failReads = true + val executor = newExecutor() + assertEquals(InternalTransferExecution.InterruptedByRestart, executor.state.value) + assertFalse(executor.submit(request)) + + marker.failReads = false + executor.acknowledge() + assertEquals(InternalTransferExecution.Idle, executor.state.value) + assertFalse(marker.value) + } + + @Test + fun `the marker is written before the transfer, kept on Sent until acknowledged, cleared on Not sent`() { + val gate = CompletableDeferred() + service.gate = gate + val executor = newExecutor() + assertTrue(executor.submit(request)) + assertEquals(listOf(request), service.transfers) + assertTrue("set before the service runs", marker.value) + gate.complete(ExternalSendResult.Sent(null)) + assertTrue(marker.value) + assertEquals(InternalTransferExecution.InterruptedByRestart, newExecutor().state.value) + + executor.acknowledge() + assertFalse(marker.value) + assertEquals(InternalTransferExecution.Idle, executor.state.value) + + service.gate = null + service.result = ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED) + marker.log.clear() + assertTrue(executor.submit(request)) + assertFalse(marker.value) + assertEquals(listOf("set", "clear"), marker.log) + executor.acknowledge() + assertEquals(InternalTransferExecution.Idle, executor.state.value) + } + + @Test + fun `a marker that cannot be persisted sends nothing`() { + marker.failWrites = true + val executor = newExecutor() + assertTrue(executor.submit(request)) + assertTrue(service.transfers.isEmpty()) + assertEquals( + InternalTransferExecution.Finished(request, ExternalSendResult.NotSent(NotSentReason.GENERIC)), + executor.state.value + ) + } + + @Test + fun `a second submission is refused while one runs or is unacknowledged`() { + val gate = CompletableDeferred() + service.gate = gate + val executor = newExecutor() + assertTrue(executor.submit(request)) + assertFalse(executor.submit(request)) + gate.complete(ExternalSendResult.MayHaveGoneThrough) + assertFalse(executor.submit(request)) + assertEquals(1, service.transfers.size) + } + + @Test + fun `a double or stale acknowledgement cannot clear a later transfer's marker`() { + val executor = newExecutor() + executor.submit(request) + val clearGate = CompletableDeferred() + marker.clearGate = clearGate + + executor.acknowledge() + assertEquals(InternalTransferExecution.Acknowledging, executor.state.value) + executor.acknowledge() + assertEquals(1, marker.clearCalls) + assertFalse(executor.submit(request)) + + clearGate.complete(Unit) + marker.clearGate = null + assertEquals(InternalTransferExecution.Idle, executor.state.value) + + // A later transfer's marker survives a stale acknowledgement. + val gate = CompletableDeferred() + service.gate = gate + assertTrue(executor.submit(request)) + executor.acknowledge() + assertTrue(marker.value) + assertEquals(1, marker.clearCalls) + gate.complete(ExternalSendResult.MayHaveGoneThrough) + assertTrue(marker.value) + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index 6ef83f8a42..4d1ed9d7a1 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -68,7 +68,7 @@ class InternalTransferViewModelTest { private class FakeService : InternalTransferService { val balances = SendBalance.entries.associateWith { MutableStateFlow(null) } val hasIdentity = MutableStateFlow(true) - val shielded = MutableStateFlow(true) + val shielded = MutableStateFlow(true) var fee: FeeEstimate? = null val max = mutableMapOf, Dash?>() var gate: CompletableDeferred? = null @@ -78,7 +78,7 @@ class InternalTransferViewModelTest { override fun observeBalance(balance: SendBalance): Flow = balances.getValue(balance) override fun observeHasIdentity(): Flow = hasIdentity - override fun observeShieldedEnabled(): Flow = shielded + override fun observeShieldedEnabled(): Flow = shielded override fun currentWalletIdOrNull(): String? = walletId override suspend fun estimateFee(from: SendBalance, to: SendBalance, amount: Dash) = fee override suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? = max[from to to] @@ -221,6 +221,61 @@ class InternalTransferViewModelTest { assertFalse(viewModel.state.pairChosenByUser) } + @Test + fun `a restored Identity pair survives an identity that is not known yet`() { + val savedState = SavedStateHandle( + mapOf( + InternalTransferViewModel.KEY_FROM to IDENTITY.name, + InternalTransferViewModel.KEY_TO to CORE.name, + InternalTransferViewModel.KEY_PAIR_CHOSEN to true + ) + ) + service.hasIdentity.value = null + service.shielded.value = true // the flag arrives first + val viewModel = buildViewModel(savedState) + assertEquals(IDENTITY to CORE, viewModel.state.from to viewModel.state.to) + assertTrue(viewModel.state.pairChosenByUser) + assertEquals(true, savedState.get(InternalTransferViewModel.KEY_PAIR_CHOSEN)) + assertEquals(IDENTITY.name, savedState.get(InternalTransferViewModel.KEY_FROM)) + // Unknown blocks Continue but keeps the pair. + service.balances.getValue(IDENTITY).value = twoDash + viewModel.type("1") + assertFalse(viewModel.state.canContinue) + + service.hasIdentity.value = true + assertEquals(IDENTITY to CORE, viewModel.state.from to viewModel.state.to) + assertTrue(viewModel.state.canContinue) + } + + @Test + fun `a restored Identity pair falls back to the default once there is confirmedly no identity`() { + val savedState = SavedStateHandle( + mapOf( + InternalTransferViewModel.KEY_FROM to IDENTITY.name, + InternalTransferViewModel.KEY_TO to CORE.name, + InternalTransferViewModel.KEY_PAIR_CHOSEN to true + ) + ) + service.hasIdentity.value = null + val viewModel = buildViewModel(savedState) + service.hasIdentity.value = false + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + assertFalse(viewModel.state.pairChosenByUser) + assertEquals(false, savedState.get(InternalTransferViewModel.KEY_PAIR_CHOSEN)) + } + + @Test + fun `a chosen Shielded pair survives an unreadable flag, and falls back when the flag is off`() { + val viewModel = buildViewModel() + viewModel.onSwap() // Shielded → Core, chosen + service.shielded.value = null + assertEquals(SHIELDED to CORE, viewModel.state.from to viewModel.state.to) + assertEquals(InternalTransferSupport.SHIELDED_OFF, viewModel.state.support) + service.shielded.value = false + assertEquals(CORE to IDENTITY, viewModel.state.from to viewModel.state.to) + assertFalse(viewModel.state.pairChosenByUser) + } + // ── amount ─────────────────────────────────────────────────────────────── @Test From 30c360c29aa02307e6001bccf012c1f831bc9690 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sat, 7 Nov 2026 12:35:46 -0800 Subject: [PATCH 03/17] fix(payments): address pre-review round 2 on Internal transfers (MO-1125) - Gate the Internal tab's BackHandler on the page being RESUMED, so Back on another Advanced Payments tab no longer closes a hidden sheet. - Confirm validates the captured request (pair, wallet, balance/limit) instead of the live fiat-derived form; a refusal closes the sheet with a visible message, and submit re-checks after authentication. - Re-render the fiat text of a Max or pinned amount when the exchange rate changes. Co-Authored-By: Claude Opus 5.5 --- wallet/res/values/strings.xml | 1 + .../internal/InternalTransferFragment.kt | 11 ++- .../internal/InternalTransferScreen.kt | 2 + .../internal/InternalTransferViewModel.kt | 79 ++++++++++++++-- .../internal/InternalTransferViewModelTest.kt | 90 ++++++++++++++++++- 5 files changed, 172 insertions(+), 11 deletions(-) diff --git a/wallet/res/values/strings.xml b/wallet/res/values/strings.xml index c6f04dc5ae..1ec2b4124f 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -599,6 +599,7 @@ Swap the From and To balances Not available yet Insufficient balance + Your balance changed and no longer covers this transfer. Nothing was sent. Check the amount and try again. Withdrawals from your Identity balance to Core are not instant and take some time Transfer in progress Your funds left your Core balance and will arrive in your Shielded balance automatically. Do not transfer them again. diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt index 6c0112b8f9..e645bfbd37 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt @@ -27,7 +27,10 @@ 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.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.compose.currentStateAsState import androidx.lifecycle.lifecycleScope import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @@ -62,7 +65,13 @@ class InternalTransferFragment : Fragment() { setContent { DashWalletTheme { val uiState by viewModel.uiState.collectAsStateWithLifecycle() - BackHandler(enabled = uiState.picker != null || uiState.confirm != null) { viewModel.onBack() } + // ViewPager2 lifts only the selected page to RESUMED: an offscreen Internal page + // must not take Back from the page on show. + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + val selectedPage = lifecycleState.isAtLeast(Lifecycle.State.RESUMED) + BackHandler(enabled = selectedPage && (uiState.picker != null || uiState.confirm != null)) { + viewModel.onBack() + } InternalTransferScreen( uiState = uiState, actions = InternalTransferActions( diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt index 316bbbcb25..ae0bb2db94 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -383,6 +383,8 @@ private fun PairStatus(uiState: InternalTransferUIState) { when { uiState.support != InternalTransferSupport.SUPPORTED && uiState.shieldedEnabled != null -> StatusText(stringResource(R.string.internal_transfer_unavailable), colors.textSecondary) + uiState.confirmRefused -> + StatusText(stringResource(R.string.internal_transfer_confirm_refused), colors.red) uiState.insufficientBalance -> StatusText(stringResource(R.string.internal_transfer_insufficient_balance), colors.red) } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt index f2708e16b3..6b74acdcf4 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -88,6 +88,9 @@ data class InternalTransferConfirm( * continues and the form stays disabled until its outcome. Reset when the status changes. * @property pinnedAmount the exact amount while [amountText] is only its rendering (see the * External Send's `pinnedAmount`). + * @property confirmRefused Confirm was refused because the captured request no longer fits the + * balance or pair (see [InternalTransferViewModel.confirmedRequest]); the sheet was closed and + * the form says so until the user edits it or continues again. */ data class InternalTransferUIState( val from: SendBalance = SendBalance.CORE, @@ -106,7 +109,8 @@ data class InternalTransferUIState( val picker: InternalTransferPicker? = null, val confirm: InternalTransferConfirm? = null, val status: ExternalSendStatus = ExternalSendStatus.Idle, - val sendingHidden: Boolean = false + val sendingHidden: Boolean = false, + val confirmRefused: Boolean = false ) { val pair: InternalTransferPair get() = InternalTransferPair(from, to) @@ -226,7 +230,7 @@ class InternalTransferViewModel @Inject constructor( .filterNotNull() .onEach { code -> _uiState.update { it.copy(fiatCode = code) } } .flatMapLatest(exchangeRates::observeExchangeRate) - .onEach { rate -> _uiState.update { it.copy(rate = rate?.fiat) } } + .onEach { rate -> onRateChanged(rate?.fiat) } .launchIn(viewModelScope) executor.state @@ -292,6 +296,23 @@ class InternalTransferViewModel @Inject constructor( setPair(defaultInternalTransferPair(state.shieldedEnabled == true, state.hasIdentity == true), byUser = false) } + /** + * A typed fiat amount stays authoritative (its Dash value follows the rate, as [amount] + * computes it). A Max or pinned amount is authoritative in Dash: in fiat mode its text is + * only a rendering, so it is re-rendered at the new rate. + */ + private fun onRateChanged(rate: Fiat?) { + _uiState.update { + val coinAuthoritative = it.maxAmount != null || it.pinnedAmount != null + if (!it.dashMode && coinAuthoritative && rate != null) { + it.copy(rate = rate, amountText = displayTextFor(it.amount, dashMode = false, rate = rate)) + } else { + it.copy(rate = rate) + } + } + saveAmount() + } + // ── From / To ──────────────────────────────────────────────────────────── fun onShowPicker(picker: InternalTransferPicker) { @@ -333,6 +354,7 @@ class InternalTransferViewModel @Inject constructor( from = pair.from, to = pair.to, pairChosenByUser = it.pairChosenByUser || byUser, + confirmRefused = if (changed) false else it.confirmRefused, maxAmount = if (changed) null else it.maxAmount, // A dropped Max keeps its exact amount (no longer Max): its text may be rounded fiat. pinnedAmount = if (changed && it.isMax) it.amount else it.pinnedAmount, @@ -374,7 +396,7 @@ class InternalTransferViewModel @Inject constructor( val decimals = if (state.dashMode) DASH_DECIMALS else FIAT_DECIMALS val text = processAmountKeyInput(base, key, decimals) if (text == state.amountText && !state.isMax) return - _uiState.update { it.copy(amountText = text, maxAmount = null, pinnedAmount = null) } + _uiState.update { it.copy(amountText = text, maxAmount = null, pinnedAmount = null, confirmRefused = false) } saveAmount() } @@ -388,7 +410,8 @@ class InternalTransferViewModel @Inject constructor( it.copy( dashMode = dashMode, amountText = text, - pinnedAmount = if (amount.isZero || state.isMax) null else amount + pinnedAmount = if (amount.isZero || state.isMax) null else amount, + confirmRefused = false ) } saveAmount() @@ -400,7 +423,12 @@ class InternalTransferViewModel @Inject constructor( val max = state.maxSendable ?: return if (!state.formEditable) return _uiState.update { - it.copy(maxAmount = max, pinnedAmount = null, amountText = displayTextFor(max, it.dashMode, it.rate)) + it.copy( + maxAmount = max, + pinnedAmount = null, + amountText = displayTextFor(max, it.dashMode, it.rate), + confirmRefused = false + ) } saveAmount() } @@ -419,7 +447,7 @@ class InternalTransferViewModel @Inject constructor( state.isMax, service.currentWalletIdOrNull() ) - _uiState.update { it.copy(confirm = InternalTransferConfirm(request), picker = null) } + _uiState.update { it.copy(confirm = InternalTransferConfirm(request), picker = null, confirmRefused = false) } feeJob?.cancel() feeJob = viewModelScope.launch { val fee = service.estimateFee(request.from, request.to, request.amount) @@ -439,20 +467,53 @@ class InternalTransferViewModel @Inject constructor( _uiState.update { it.copy(confirm = null) } } - /** The request the confirm sheet shows, captured BEFORE authentication; null when none. */ + /** + * The request the confirm sheet shows, captured BEFORE authentication; null when none. + * + * The CAPTURED request is validated, not the live form (whose fiat amount follows the rate). + * When it no longer validates the sheet is closed and [InternalTransferUIState.confirmRefused] + * says why, so Confirm never does nothing silently. + */ fun confirmedRequest(): InternalTransferRequest? { - val state = _uiState.value - return state.confirm?.request?.takeIf { state.canContinue } + val request = _uiState.value.confirm?.request ?: return null + return request.takeIf { stillValid(it) } } /** Authenticated: run [request], unless it is no longer the request on the confirm sheet. */ fun submit(request: InternalTransferRequest): Boolean { if (_uiState.value.confirm?.request != request) return false + // The balance may have moved during authentication. + if (!stillValid(request)) return false if (!executor.submit(request)) return false _uiState.update { it.copy(confirm = null) } return true } + /** + * Whether the captured [request] can still be sent: it is the selected, supported pair, the + * form is idle, the same SDK wallet is bound, and the From balance is known and covers the + * captured amount (Max when known, as for Continue). Otherwise the confirm sheet is closed + * with [InternalTransferUIState.confirmRefused] set. + */ + private fun stillValid(request: InternalTransferRequest): Boolean { + val state = _uiState.value + if (!state.formEditable) return false + val limit = state.limit + val valid = state.from == request.from && + state.to == request.to && + state.support == InternalTransferSupport.SUPPORTED && + request.amount.isPositive && + state.balance != null && + limit != null && + !request.amount.isGreaterThan(limit) && + service.currentWalletIdOrNull() == request.expectedWalletIdHex + if (!valid) { + feeJob?.cancel() + _uiState.update { if (it.confirm?.request == request) it.copy(confirm = null, confirmRefused = true) else it } + } + return valid + } + /** * The user closed the outcome. Not sent → back to the same amount (Max chosen again * deliberately); any other outcome clears the amount for a new transfer (the tab stays). diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index 4d1ed9d7a1..b59d2bad1d 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -44,6 +44,7 @@ import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.dash.wallet.common.data.WalletUIConfig +import org.dash.wallet.common.data.entity.ExchangeRate import org.dash.wallet.common.money.Dash import org.dash.wallet.common.services.ExchangeRatesProvider import org.junit.After @@ -106,6 +107,7 @@ class InternalTransferViewModelTest { } private val service = FakeService() + private val rate = MutableStateFlow(null) private val marker = FakeMarker() private lateinit var executor: InternalTransferExecutor @@ -125,7 +127,7 @@ class InternalTransferViewModelTest { every { observe(WalletUIConfig.SELECTED_CURRENCY) } returns flowOf("USD") } val rates = mockk { - every { observeExchangeRate(any()) } returns flowOf(null) + every { observeExchangeRate(any()) } returns rate } return InternalTransferViewModel(service, executor, walletUIConfig, rates, savedState) } @@ -430,4 +432,90 @@ class InternalTransferViewModelTest { assertEquals(listOf(R.string.internal_transfer_withdrawal_not_instant), internalConfirmNotes(IDENTITY, CORE)) assertEquals(emptyList(), internalConfirmNotes(CORE, SHIELDED)) } + + // ── rate changes ───────────────────────────────────────────────────────── + + /** 2 DASH on Core, 100 fiat typed at 100 USD/DASH (1 DASH), then Continue. */ + private fun confirmOneDashTypedInFiat(): InternalTransferViewModel { + rate.value = ExchangeRate("USD", "100") + service.balances.getValue(CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.onCurrencySelected(dashMode = false) + viewModel.type("100") + assertEquals(oneDash, viewModel.state.amount) + viewModel.onContinue() + assertEquals(oneDash, requireNotNull(viewModel.state.confirm).request.amount) + return viewModel + } + + @Test + fun `a rate change while the confirm is open still submits the captured request`() { + val viewModel = confirmOneDashTypedInFiat() + // The typed fiat is now 2.5 DASH: the live form no longer fits, the captured 1 DASH does. + rate.value = ExchangeRate("USD", "40") + assertFalse(viewModel.state.canContinue) + + val request = requireNotNull(viewModel.confirmedRequest()) + assertEquals(oneDash, request.amount) + assertTrue(viewModel.submit(request)) + assertEquals(listOf(request), service.transfers) + assertFalse(viewModel.state.confirmRefused) + } + + @Test + fun `Confirm is refused explicitly when the balance no longer covers the captured request`() { + val viewModel = confirmOneDashTypedInFiat() + rate.value = ExchangeRate("USD", "40") + service.balances.getValue(CORE).value = Dash(50_000_000) + + assertNull(viewModel.confirmedRequest()) + assertNull(viewModel.state.confirm) + assertTrue(viewModel.state.confirmRefused) + assertTrue(service.transfers.isEmpty()) + + // Editing the amount clears the refusal. + viewModel.onKeyInput("back") + assertFalse(viewModel.state.confirmRefused) + } + + @Test + fun `a balance drop during authentication refuses the submit explicitly`() { + val viewModel = confirmOneDashTypedInFiat() + val request = requireNotNull(viewModel.confirmedRequest()) + service.balances.getValue(CORE).value = Dash(50_000_000) + + assertFalse(viewModel.submit(request)) + assertNull(viewModel.state.confirm) + assertTrue(viewModel.state.confirmRefused) + assertTrue(service.transfers.isEmpty()) + } + + @Test + fun `Max in fiat mode is re-rendered at a new rate`() { + rate.value = ExchangeRate("USD", "100") + service.balances.getValue(CORE).value = twoDash + service.max[CORE to SHIELDED] = oneDash + val viewModel = buildViewModel() + viewModel.onCurrencySelected(dashMode = false) + viewModel.onMaxClick() + assertEquals("100.00", viewModel.state.amountText) + + rate.value = ExchangeRate("USD", "50") + assertEquals("50.00", viewModel.state.amountText) + assertEquals(oneDash, viewModel.state.amount) + assertTrue(viewModel.state.isMax) + } + + @Test + fun `a typed fiat amount keeps its text and follows the rate in Dash`() { + rate.value = ExchangeRate("USD", "100") + service.balances.getValue(CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.onCurrencySelected(dashMode = false) + viewModel.type("100") + + rate.value = ExchangeRate("USD", "50") + assertEquals("100", viewModel.state.amountText) + assertEquals(twoDash, viewModel.state.amount) + } } From fad8d31e40d275a643cfc6fa707033e2662f8453 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 9 Nov 2026 07:31:44 -0800 Subject: [PATCH 04/17] =?UTF-8?q?feat(payments):=20enable=20Platform=20?= =?UTF-8?q?=E2=86=92=20Core=20internal=20transfers=20(MO-1125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Route the Internal Platform → Core pair through the External Send's partial Platform withdrawal (#1680) to the wallet's own unadvertised Core address, pinned to the confirmed wallet, like Shielded → Core and Identity → Core. No pre-send fee or Max, as in External Send. Core → Platform and Identity → Shielded stay unavailable. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/InternalTransferModels.kt | 7 ++-- .../sdk/InternalTransferServiceImpl.kt | 9 +++-- .../sdk/InternalTransferModelsTest.kt | 12 +++++-- .../sdk/InternalTransferServiceImplTest.kt | 35 +++++++++++++++++-- 4 files changed, 52 insertions(+), 11 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt index baeda4baae..e97621c32f 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt @@ -45,11 +45,12 @@ enum class InternalTransferSupport { * |---|---|---|---|---| * | Core | — | yes | no (1) | yes | * | Shielded | yes | — | yes | yes | - * | Platform | no (2) | yes | — | yes | + * | Platform | yes (2) | yes | — | yes | * | Identity | yes | no (3) | yes | — | * * 1. The Platform-address funding from an asset lock is not wired for this flow yet. - * 2. The SDK's Platform-address withdrawal only withdraws the full balance. + * 2. The External Send's partial Platform → Core withdrawal (`withdrawCredits` with the + * inputs the wallet selects) to the wallet's own unadvertised Core address. * 3. `shieldedShieldFromIdentity` (Type 21) is not bound in the wallet yet. * * [shieldedEnabled] and [hasIdentity] are the error-preserving reads: unknown is false. @@ -75,7 +76,7 @@ fun internalTransferSupport( fun internalTransferPairSupported(from: SendBalance, to: SendBalance): Boolean = when (from) { SendBalance.CORE -> to == SendBalance.SHIELDED || to == SendBalance.IDENTITY SendBalance.SHIELDED -> to != SendBalance.SHIELDED - SendBalance.PLATFORM -> to == SendBalance.SHIELDED || to == SendBalance.IDENTITY + SendBalance.PLATFORM -> to != SendBalance.PLATFORM SendBalance.IDENTITY -> to == SendBalance.CORE || to == SendBalance.PLATFORM } diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index f6ea806d3c..48070904d6 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -129,15 +129,18 @@ internal class DashSdkInternalTransferSource( * [ExternalSendService.send] to the resolved OWN destination (that route's gating, pinning and * classification apply unchanged) or one of [ShieldedBalanceService]'s pinned self routes. * - * Routes (the 9 supported pairs of [internalTransferSupport]): + * Routes (the 10 supported pairs of [internalTransferSupport]): * - Core → Shielded: [ShieldedBalanceService.shieldFromWalletPinned] of `amount + pool fee` * ([shieldPoolFeeDuffs]), so the own shielded balance receives the confirmed amount (the * External Send's Core → Shielded convention). A lock that went out with the shield still * pending is [ExternalSendResult.CompletesAutomatically]. * - Core → Identity, Shielded → Identity, Platform → Identity: [ExternalSendService.send] to * the user's own identity id. - * - Shielded → Core, Identity → Core: [ExternalSendService.send] to the UNADVERTISED Core - * address ([InternalTransferSource.unadvertisedCoreAddress]); unavailable = Not sent. + * - Shielded → Core, Platform → Core, Identity → Core: [ExternalSendService.send] to the + * UNADVERTISED Core address ([InternalTransferSource.unadvertisedCoreAddress]); unavailable = + * Not sent. Platform → Core is the External Send's partial withdrawal: [amount] is the gross + * withdrawal (the asset unlock's Core fee comes out of it) and one below the withdrawal + * minimum is refused there before anything is signed. * - Shielded → Platform: [ShieldedBalanceService.unshieldToCreditsPinned] (own Platform address), * with the shielded Max fee retry. * - Platform → Shielded: [ShieldedBalanceService.shieldFromCreditsPinned]. diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt index a21fbce786..7abc0aef94 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt @@ -31,7 +31,7 @@ class InternalTransferModelsTest { private val supported = setOf( CORE to SHIELDED, CORE to IDENTITY, SHIELDED to CORE, SHIELDED to PLATFORM, SHIELDED to IDENTITY, - PLATFORM to SHIELDED, PLATFORM to IDENTITY, + PLATFORM to CORE, PLATFORM to SHIELDED, PLATFORM to IDENTITY, IDENTITY to CORE, IDENTITY to PLATFORM ) @@ -48,11 +48,11 @@ class InternalTransferModelsTest { assertEquals("$from → $to", (from to to) in supported, internalTransferPairSupported(from, to)) } } - // Exactly the three pairs the SDK cannot do yet are disabled. + // Exactly the two pairs the SDK cannot do yet are disabled. val notYet = SendBalance.entries.flatMap { f -> SendBalance.entries.map { f to it } } .filter { internalTransferSupport(it.first, it.second, true, true) == InternalTransferSupport.NOT_SUPPORTED_YET } .toSet() - assertEquals(setOf(CORE to PLATFORM, PLATFORM to CORE, IDENTITY to SHIELDED), notYet) + assertEquals(setOf(CORE to PLATFORM, IDENTITY to SHIELDED), notYet) } @Test @@ -64,6 +64,8 @@ class InternalTransferModelsTest { assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(IDENTITY, CORE, false, true)) // The matrix wins over the flags: an unsupported pair is "not yet", whatever they say. assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, internalTransferSupport(CORE, PLATFORM, false, false)) + // Platform → Core needs neither the shielded feature nor an identity. + assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(PLATFORM, CORE, false, false)) } @Test @@ -76,6 +78,10 @@ class InternalTransferModelsTest { @Test fun `swap exchanges From and To (AC3)`() { assertEquals(InternalTransferPair(SHIELDED, CORE), InternalTransferPair(CORE, SHIELDED).swapped()) + // The default with no shielded feature and no identity swaps to the one supported pair left. + val swapped = defaultInternalTransferPair(false, false).swapped() + assertEquals(InternalTransferPair(PLATFORM, CORE), swapped) + assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(swapped.from, swapped.to, false, false)) } @Test diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt index 6c647fe053..d07186a8b7 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -162,19 +162,43 @@ class InternalTransferServiceImplTest { fun `Core destinations are the unadvertised address`() { assertEquals(ExternalSendResult.Sent("txid"), transfer(SHIELDED, CORE)) assertEquals(ExternalSendResult.Sent("txid"), transfer(IDENTITY, CORE, isMax = true)) + assertEquals(ExternalSendResult.Sent("txid"), transfer(PLATFORM, CORE)) assertEquals( listOf( Send(SHIELDED, SendDestination.Core(unadvertised), amount, false, WALLET_A), - Send(IDENTITY, SendDestination.Core(unadvertised), amount, true, WALLET_A) + Send(IDENTITY, SendDestination.Core(unadvertised), amount, true, WALLET_A), + Send(PLATFORM, SendDestination.Core(unadvertised), amount, false, WALLET_A) ), external.sends ) } + @Test + fun `Platform to Core withdraws to the unadvertised address, pinned, with the shielded flag off and no identity`() { + source.shielded = null // unreadable: Platform → Core has no shielded leg, so it is never read + source.identity = Result.failure(IOException("unreadable")) // nor the identity record + assertEquals(ExternalSendResult.Sent("txid"), transfer(PLATFORM, CORE)) + assertEquals(listOf(Send(PLATFORM, SendDestination.Core(unadvertised), amount, false, WALLET_A)), external.sends) + assertEquals(emptyList(), source.writes) + } + + @Test + fun `Platform to Core passes the withdrawal's outcome through unchanged`() { + for (outcome in listOf( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + ExternalSendResult.MayHaveGoneThrough + )) { + external.result = outcome + assertEquals(outcome, transfer(PLATFORM, CORE)) + } + } + @Test fun `no unadvertised Core address fails closed before anything is submitted`() { source.coreAddress = { throw IllegalStateException("no unadvertised destination post-cutover") } assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(SHIELDED, CORE)) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(PLATFORM, CORE)) assertNothingSubmitted() } @@ -262,7 +286,7 @@ class InternalTransferServiceImplTest { @Test fun `the matrix is enforced by the service`() { - for ((from, to) in listOf(CORE to PLATFORM, PLATFORM to CORE, IDENTITY to SHIELDED, CORE to CORE)) { + for ((from, to) in listOf(CORE to PLATFORM, IDENTITY to SHIELDED, CORE to CORE)) { assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(from, to)) } assertNothingSubmitted() @@ -346,6 +370,13 @@ class InternalTransferServiceImplTest { assertNull(service.estimateFee(CORE, PLATFORM, amount)) assertNull(service.maxSendable(CORE, PLATFORM)) assertNull(service.estimateFee(PLATFORM, SHIELDED, amount)) + // Platform → Core asks the External Send's own figures (null today: metered by Rust). + assertNull(service.estimateFee(PLATFORM, CORE, amount)) + assertNull(service.maxSendable(PLATFORM, CORE)) + external.pairFees[PLATFORM to CORE] = fee + external.pairMax[PLATFORM to CORE] = Dash(5000) + assertEquals(fee, service.estimateFee(PLATFORM, CORE, amount)) + assertEquals(Dash(5000), service.maxSendable(PLATFORM, CORE)) } @Test From e0b969bbce968781455fd36c55f8a261cc9ec337 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 9 Nov 2026 15:44:23 -0800 Subject: [PATCH 05/17] fix(payments): show the Internal transfer sheets above the bottom navigation (MO-1125) The Internal tab is a pager page of AdvancedPaymentsFragment, whose destination keeps MainActivity's bottom navigation drawn over the bottom of the nav host, so the "Transfer from/to" picker, the confirm sheet and the sending card were partly hidden under it. Host them in their own full-screen window (selected page only), as the app's other sheets over the bottom navigation are. External Send, which has no bottom navigation, is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../internal/InternalTransferScreen.kt | 91 +++++++++++++++---- 1 file changed, 74 insertions(+), 17 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt index ae0bb2db94..6da04b7ebf 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -37,6 +37,15 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.window.DialogWindowProvider +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.currentStateAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha @@ -115,33 +124,40 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr val picker = uiState.picker if (picker != null && uiState.formEditable) { - PickerSheet(uiState, picker, actions) + AboveBottomNavigation(onBack = actions.onDismissPicker) { + PickerSheet(uiState, picker, actions) + } } val confirm = uiState.confirm if (confirm != null && uiState.status == ExternalSendStatus.Idle) { val request = confirm.request - SendConfirmSheet( - amount = request.amount, - rate = uiState.rate, - fiatCode = uiState.fiatCode, - fromValue = stringResource(balanceNameFor(request.from)), - toValue = stringResource(balanceNameFor(request.to)), - fee = confirm.fee, - feeLoading = confirm.feeLoading, - total = confirm.total, - feeIncluded = false, - notes = internalConfirmNotes(request.from, request.to), - onDismiss = actions.onDismissConfirm, - onConfirm = actions.onConfirm - ) + AboveBottomNavigation(onBack = actions.onDismissConfirm) { + SendConfirmSheet( + amount = request.amount, + rate = uiState.rate, + fiatCode = uiState.fiatCode, + fromValue = stringResource(balanceNameFor(request.from)), + toValue = stringResource(balanceNameFor(request.to)), + fee = confirm.fee, + feeLoading = confirm.feeLoading, + total = confirm.total, + feeIncluded = false, + notes = internalConfirmNotes(request.from, request.to), + onDismiss = actions.onDismissConfirm, + onConfirm = actions.onConfirm + ) + } } when (val status = uiState.status) { // A shielded leg's ~30 s proof can be left: Close hides the overlay (the form stays - // disabled) and the outcome shows when it arrives. + // disabled) and the outcome shows when it arrives. Back does what Close does, and + // nothing while a Core / Platform transfer (seconds, not leavable) runs. is ExternalSendStatus.Sending -> if (!uiState.sendingHidden) { - SendingOverlay(status.shieldedLeg, actions.onHideSending) + AboveBottomNavigation(onBack = if (status.shieldedLeg) actions.onHideSending else null) { + SendingOverlay(status.shieldedLeg, actions.onHideSending) + } } is ExternalSendStatus.Done -> ResultDialog(status.result, status.afterRestart, actions.onResultClosed) ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} @@ -149,6 +165,47 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr } } +/** + * Shows [content] (a full-screen scrim with a sheet or a card) in its own window, over the host's + * tab picker and the app's bottom navigation. The Internal page is a pager page of + * AdvancedPaymentsFragment, whose `nav_home` destination keeps MainActivity's bottom navigation + * drawn over the bottom of the nav host: drawn in the page, the sheet's lower rows would sit under + * it, and the scrim would leave the tab picker and the navigation tappable. The External Send has + * no bottom navigation, so it draws the same overlays in place. + * + * The window fits the system bars, as MainActivity's content does, and has no dim of its own: the + * overlay's scrim is the only one, so it looks as it does in the External Send. Back calls [onBack] + * (null: Back does nothing while the window shows). + * + * Only the selected pager page (RESUMED; ViewPager2 keeps the offscreen one at STARTED) opens the + * window: an offscreen Internal page draws the overlay in place, where it is not seen. + */ +@Composable +private fun AboveBottomNavigation(onBack: (() -> Unit)?, content: @Composable () -> Unit) { + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + if (!lifecycleState.isAtLeast(Lifecycle.State.RESUMED)) { + content() + return + } + Dialog( + onDismissRequest = { onBack?.invoke() }, + properties = DialogProperties( + dismissOnBackPress = onBack != null, + dismissOnClickOutside = false, + usePlatformDefaultWidth = false + ) + ) { + val window = (LocalView.current.parent as? DialogWindowProvider)?.window + SideEffect { + window?.setDimAmount(0f) + window?.setWindowAnimations(0) + } + Box(modifier = Modifier.fillMaxSize()) { + content() + } + } +} + /** * The confirm notes (AC11/AC13, reusing the External Send's): out of Shielded the transfer is not * instant and its amount becomes public; Identity → Core is a withdrawal that takes some time. From 66c6ffc0ad6c4a1de6b1c38674dd6a564213cc38 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 9 Nov 2026 22:20:02 -0800 Subject: [PATCH 06/17] fix(payments): keep the Internal tab clear of the bars (MO-1125) - The overlay window now covers the screen and pads itself by the system bars, so the scrim meets the status bar with no undimmed strip. - The Internal page leaves the bottom navigation's height free, so the keypad's Continue is no longer drawn under it. Co-Authored-By: Claude Opus 5.5 --- .../internal/InternalTransferScreen.kt | 66 ++++++++++++++++--- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt index 6da04b7ebf..dae3d1b745 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -17,6 +17,8 @@ package de.schildbach.wallet.ui.payments.internal +import android.os.Build +import android.view.Window import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.background @@ -27,24 +29,31 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.displayCutout import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogWindowProvider import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.core.view.WindowCompat import androidx.lifecycle.compose.currentStateAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -52,6 +61,7 @@ import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout +import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -84,6 +94,7 @@ import org.dash.wallet.common.ui.components.Menu import org.dash.wallet.common.ui.components.MyImages import org.dash.wallet.common.ui.components.MyTheme import org.dash.wallet.common.ui.components.TopNavBase +import org.dash.wallet.common.ui.getActivity import org.dash.wallet.common.ui.enter_amount.AmountEntryPage import org.dash.wallet.common.ui.enter_amount.AmountEntryPrimaryButton @@ -173,9 +184,15 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr * it, and the scrim would leave the tab picker and the navigation tappable. The External Send has * no bottom navigation, so it draws the same overlays in place. * - * The window fits the system bars, as MainActivity's content does, and has no dim of its own: the - * overlay's scrim is the only one, so it looks as it does in the External Send. Back calls [onBack] - * (null: Back does nothing while the window shows). + * The window covers the whole screen (`decorFitsSystemWindows = false`) and the content is inset by + * the system bars and the display cutout, as MainActivity's `fitsSystemWindows` content is: the + * scrim starts at the bottom of the status bar and the sheet ends at the top of the system + * navigation, exactly where they are in the External Send. A decor-fitted dialog window is laid out + * by the platform instead, which left an un-dimmed band under the status bar. The status and + * navigation bars stay MainActivity's: the window draws no bar backgrounds of its own and copies + * the activity's light/dark bar icons. The window has no dim of its own: the overlay's scrim is the + * only one, so it looks as it does in the External Send. Back calls [onBack] (null: Back does + * nothing while the window shows). * * Only the selected pager page (RESUMED; ViewPager2 keeps the offscreen one at STARTED) opens the * window: an offscreen Internal page draws the overlay in place, where it is not seen. @@ -187,25 +204,56 @@ private fun AboveBottomNavigation(onBack: (() -> Unit)?, content: @Composable () content() return } + val hostWindow = LocalContext.current.getActivity()?.window Dialog( onDismissRequest = { onBack?.invoke() }, properties = DialogProperties( dismissOnBackPress = onBack != null, dismissOnClickOutside = false, - usePlatformDefaultWidth = false + usePlatformDefaultWidth = false, + decorFitsSystemWindows = false ) ) { val window = (LocalView.current.parent as? DialogWindowProvider)?.window SideEffect { - window?.setDimAmount(0f) - window?.setWindowAnimations(0) + window?.let { matchHostSystemBars(it, hostWindow) } } - Box(modifier = Modifier.fillMaxSize()) { + Box( + modifier = Modifier + .fillMaxSize() + .windowInsetsPadding(WindowInsets.systemBars.union(WindowInsets.displayCutout)) + ) { content() } } } +/** + * The overlay [window] leaves the system bars to the [hostWindow]: no dim, no animation, transparent + * bar backgrounds (MainActivity's show through) and the host's light/dark bar icons. + */ +private fun matchHostSystemBars(window: Window, hostWindow: Window?) { + window.setDimAmount(0f) + window.setWindowAnimations(0) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) { + // No-ops on API 35+, where the bar backgrounds are always transparent. + @Suppress("DEPRECATION") + window.statusBarColor = android.graphics.Color.TRANSPARENT + @Suppress("DEPRECATION") + window.navigationBarColor = android.graphics.Color.TRANSPARENT + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + window.isStatusBarContrastEnforced = false + window.isNavigationBarContrastEnforced = false + } + if (hostWindow != null) { + val host = WindowCompat.getInsetsController(hostWindow, hostWindow.decorView) + val overlay = WindowCompat.getInsetsController(window, window.decorView) + overlay.isAppearanceLightStatusBars = host.isAppearanceLightStatusBars + overlay.isAppearanceLightNavigationBars = host.isAppearanceLightNavigationBars + } +} + /** * The confirm notes (AC11/AC13, reusing the External Send's): out of Shielded the transfer is not * instant and its amount becomes public; Identity → Core is a withdrawal that takes some time. @@ -236,9 +284,11 @@ private fun AmountPage(uiState: InternalTransferUIState, actions: InternalTransf selectedCurrencyIndex = if (uiState.dashMode || fiatCode == null) 0 else 1, onKeyInput = actions.onKeyInput, // Figma 3342:12176: the content column starts 10dp under the tab picker. + // The bottom clears MainActivity's bottom navigation, drawn over the pager (as the other + // bottom-nav screens do, e.g. More): the keypad and Continue sit right above it. modifier = Modifier .fillMaxSize() - .padding(top = 10.dp), + .padding(top = 10.dp, bottom = dimensionResource(R.dimen.bottom_nav_bar_height)), secondaryAmount = uiState.secondaryAmountText, showPrimaryChevron = false, keypadEnabled = uiState.formEditable, From a967e1c8d383477ed85720c849fd69610b1e1315 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 9 Nov 2026 22:20:03 -0800 Subject: [PATCH 07/17] feat(payments): hide the Internal tab on the basic Payments screen Basic (non-Advanced) Payments shows only Receive | Send; Internal transfers live in Advanced mode. A saved Internal tab opens Receive. Co-Authored-By: Claude Opus 5.5 --- .../wallet/ui/payments/PaymentsFragment.kt | 24 +++++++------------ .../ui/payments/AdvancedPaymentsTabsTest.kt | 13 +++++++--- .../wallet/ui/payments/PaymentsTabsTest.kt | 5 ++++ 3 files changed, 24 insertions(+), 18 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsFragment.kt index 6803ced18e..1db63b2ef0 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/PaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/PaymentsFragment.kt @@ -29,7 +29,6 @@ import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.unit.dp import androidx.core.view.isVisible import androidx.fragment.app.Fragment -import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.transition.Fade import androidx.transition.Slide @@ -38,18 +37,14 @@ import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.transition.MaterialFadeThrough import dagger.hilt.android.AndroidEntryPoint -import de.schildbach.wallet.Constants -import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentPaymentsBinding -import kotlinx.coroutines.launch import org.dash.wallet.common.ui.observeOnDestroy import org.dash.wallet.common.ui.segmented_picker.SegmentedOption import org.dash.wallet.common.ui.viewBinding import androidx.core.content.edit import org.dash.wallet.common.ui.components.DashWalletTheme import org.dash.wallet.common.ui.segmented_picker.SegmentedPicker -import javax.inject.Inject @AndroidEntryPoint class PaymentsFragment : Fragment(R.layout.fragment_payments) { @@ -65,6 +60,9 @@ class PaymentsFragment : Fragment(R.layout.fragment_payments) { const val ACTIVE_TAB_PAY = 1 const val ACTIVE_TAB_INTERNAL = 2 + /** The Basic mode tabs: Receive | Send, never Internal. */ + val BASIC_TAB_IDS: List = tabIdsFor(showInternalTab = false) + /** * Tab ids in display order. With [showInternalTab] off this is exactly * the pre-shielded two-tab layout (Receive | Send); with it on, the @@ -77,8 +75,6 @@ class PaymentsFragment : Fragment(R.layout.fragment_payments) { } } - @Inject lateinit var dashPayConfig: DashPayConfig - private val binding by viewBinding(FragmentPaymentsBinding::bind) private var selectedTab by mutableIntStateOf(0) @@ -96,13 +92,10 @@ class PaymentsFragment : Fragment(R.layout.fragment_payments) { findNavController().popBackStack() } - // The shielded "Internal" tab is flag-gated; the flag is read once at - // screen build. Flags off ⇒ exactly the two pre-existing tabs. - viewLifecycleOwner.lifecycleScope.launch { - val showInternalTab = Constants.SUPPORTS_PLATFORM && - dashPayConfig.get(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) == true - setupTabs(tabIdsFor(showInternalTab)) - } + // Basic mode has only Receive | Send: transfers between the user's own balances are + // the Advanced payments screen's Internal tab. A stored or requested Internal tab + // falls back to Receive (activateTab). + setupTabs(BASIC_TAB_IDS) } private fun setupTabs(tabIds: List) { @@ -179,7 +172,8 @@ class PaymentsFragment : Fragment(R.layout.fragment_payments) { preferences.getInt(PREFS_RECENT_TAB, ACTIVE_TAB_RECEIVE) } - val position = tabIds.indexOf(activeTabId).takeIf { it >= 0 } ?: 0 + // A tab this screen does not show (Internal, stored before Basic mode dropped it) opens Receive. + val position = AdvancedPaymentsFragment.positionOf(tabIds, activeTabId) selectedTab = position binding.pager.setCurrentItem(position, false) } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt index d7f4e0f996..d3e708a9e6 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt @@ -41,12 +41,19 @@ class AdvancedPaymentsTabsTest { } @Test - fun `Basic mode keeps its shielded gating`() { - // PaymentsFragment shows Internal only with the shielded flag on; Advanced no longer reads it. - assertEquals(twoTabs, PaymentsFragment.tabIdsFor(showInternalTab = false)) + fun `Basic mode never shows Internal`() { + // PaymentsFragment shows Receive | Send whatever the flags; Internal is Advanced only. + assertEquals(twoTabs, PaymentsFragment.BASIC_TAB_IDS) assertEquals(threeTabs, PaymentsFragment.tabIdsFor(showInternalTab = true)) } + @Test + fun `a stored Internal tab opens Receive in Basic mode`() { + assertEquals(0, AdvancedPaymentsFragment.positionOf(PaymentsFragment.BASIC_TAB_IDS, ACTIVE_TAB_INTERNAL)) + assertEquals(ACTIVE_TAB_RECEIVE, PaymentsFragment.BASIC_TAB_IDS[0]) + assertEquals(1, AdvancedPaymentsFragment.positionOf(PaymentsFragment.BASIC_TAB_IDS, ACTIVE_TAB_PAY)) + } + @Test fun `initial state has no tabs`() { assertNull(AdvancedPaymentsUIState().tabIds) diff --git a/wallet/test/de/schildbach/wallet/ui/payments/PaymentsTabsTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsTabsTest.kt index e52012064b..be84a185d4 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/PaymentsTabsTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/PaymentsTabsTest.kt @@ -39,6 +39,11 @@ class PaymentsTabsTest { assertEquals(PaymentsFragment.ACTIVE_TAB_PAY, tabs.indexOf(PaymentsFragment.ACTIVE_TAB_PAY)) } + @Test + fun `Basic mode shows exactly the two legacy tabs`() { + assertEquals(PaymentsFragment.tabIdsFor(showInternalTab = false), PaymentsFragment.BASIC_TAB_IDS) + } + @Test fun `flags on - Internal tab sits between Receive and Send`() { assertEquals( From 925bd884fa6d522046ba635479975ccef9cf92ef Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 13:55:40 -0800 Subject: [PATCH 08/17] fix(payments): return Home after a finished Internal transfer Closing a Sent, "may have gone through" (including the one shown after a process restart) or other terminal outcome now pops back to Home, the way the External Send does since 5610dfcdd. Not sent stays on the Internal tab so the user can retry. The outcome is read before acknowledging, only the selected pager page navigates, and it falls back to a single pop when Home is not on the back stack. Co-Authored-By: Claude Opus 5.5 --- .../internal/InternalTransferFragment.kt | 38 ++++++++++++++++++- .../internal/InternalTransferViewModel.kt | 3 +- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt index e645bfbd37..87bfb035ad 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt @@ -32,7 +32,11 @@ import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.currentStateAsState import androidx.lifecycle.lifecycleScope +import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.ui.payments.send.ExternalSendStatus +import de.schildbach.wallet_test.R import kotlinx.coroutines.launch import org.dash.wallet.common.services.AuthenticationManager import org.dash.wallet.common.ui.components.DashWalletTheme @@ -45,7 +49,8 @@ import javax.inject.Inject * * Confirm captures the exact request, then asks for PIN/biometric (the External Send's auth * path), then hands it to the app-scoped [InternalTransferExecutor]: leaving the screen does not - * cancel the transfer. Back closes an open sheet; otherwise it belongs to the host. + * cancel the transfer. Back closes an open sheet; otherwise it belongs to the host. Closing a + * finished transfer's outcome returns Home, as the External Send does; Not sent stays here. */ @AndroidEntryPoint class InternalTransferFragment : Fragment() { @@ -86,13 +91,42 @@ class InternalTransferFragment : Fragment() { onDismissConfirm = viewModel::onDismissConfirm, onConfirm = ::authenticateAndTransfer, onHideSending = viewModel::onHideSending, - onResultClosed = viewModel::onResultAcknowledged + onResultClosed = ::onResultClosed ) ) } } } + /** + * A terminal outcome (sent, may have gone through — including the one shown after a process + * restart — or any other result but Not sent) returns Home. Not sent stays on this tab so the + * user can try again. The outcome is read before acknowledging, which clears it. + */ + private fun onResultClosed() { + val result = (viewModel.uiState.value.status as? ExternalSendStatus.Done)?.result + viewModel.onResultAcknowledged() + // Only the selected (RESUMED) pager page shows the outcome and may navigate. + val selectedPage = viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) + if (result != null && result !is ExternalSendResult.NotSent && selectedPage) { + leaveToHome() + } + } + + /** + * Pops back to Home (the bottom navigation follows the destination change). Falls back to a + * single pop when Home is not on the back stack so the user is never stranded here. + */ + private fun leaveToHome() { + val navController = findNavController() + // A second tap while the pop runs would act on the screen below. + if (navController.currentDestination?.id == R.id.advancedPaymentsFragment) { + if (!navController.popBackStack(R.id.walletFragment, false)) { + navController.popBackStack() + } + } + } + /** * Capture what the confirm sheet shows BEFORE authenticating, then transfer exactly that. * A failed or cancelled authentication transfers nothing. diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt index 6b74acdcf4..717e9e1d43 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -516,7 +516,8 @@ class InternalTransferViewModel @Inject constructor( /** * The user closed the outcome. Not sent → back to the same amount (Max chosen again - * deliberately); any other outcome clears the amount for a new transfer (the tab stays). + * deliberately); any other outcome clears the amount for a new transfer (the + * fragment then returns Home; the cleared amount is what a later visit finds). */ fun onResultAcknowledged() { val status = _uiState.value.status as? ExternalSendStatus.Done ?: return From 25f104905fb0f7a35d3955e091dab3c62ada609d Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 14:19:14 -0800 Subject: [PATCH 09/17] fix(payments): close Internal transfer overlays when the lock screen appears The From/To picker, the confirm sheet, the sending overlay and the outcome dialog are drawn in their own windows, which stayed above the lock screen (dismissDialogsForLockScreen only dismisses DialogFragments). InternalTransferFragment is now LockScreenAware: on lock the picker and the confirm sheet close (the amount is kept), and the sending overlay and the outcome are withheld, not acknowledged, until LockScreenActivity.walletLocked turns false. A running transfer continues on the app scope. Co-Authored-By: Claude Opus 5.5 --- .../internal/InternalTransferFragment.kt | 27 +++++- .../internal/InternalTransferScreen.kt | 8 +- .../internal/InternalTransferViewModel.kt | 28 +++++- .../internal/InternalTransferViewModelTest.kt | 93 +++++++++++++++++++ 4 files changed, 152 insertions(+), 4 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt index 87bfb035ad..ef6d5cae7a 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt @@ -32,13 +32,16 @@ import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.currentStateAsState import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.ui.LockScreenActivity import de.schildbach.wallet.ui.payments.send.ExternalSendStatus import de.schildbach.wallet_test.R import kotlinx.coroutines.launch import org.dash.wallet.common.services.AuthenticationManager +import org.dash.wallet.common.ui.LockScreenAware import org.dash.wallet.common.ui.components.DashWalletTheme import javax.inject.Inject @@ -51,9 +54,13 @@ import javax.inject.Inject * path), then hands it to the app-scoped [InternalTransferExecutor]: leaving the screen does not * cancel the transfer. Back closes an open sheet; otherwise it belongs to the host. Closing a * finished transfer's outcome returns Home, as the External Send does; Not sent stays here. + * + * The lock screen is drawn in MainActivity's content, under this page's overlay windows: on lock + * ([onLockScreenActivated]) the sheets close and the outcome is withheld until the wallet is + * unlocked ([LockScreenActivity.walletLocked] turns false). */ @AndroidEntryPoint -class InternalTransferFragment : Fragment() { +class InternalTransferFragment : Fragment(), LockScreenAware { companion object { fun newInstance() = InternalTransferFragment() @@ -98,6 +105,24 @@ class InternalTransferFragment : Fragment() { } } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + val walletLocked = (activity as? LockScreenActivity)?.walletLocked ?: return + viewLifecycleOwner.lifecycleScope.launch { + // The lock screen covers the activity in place, so this page stays RESUMED under it: + // the lock state, not the lifecycle, says when it is gone. A state, so a view + // recreated after the unlock still releases the withheld outcome. + viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { + walletLocked.collect { locked -> if (!locked) viewModel.onLockScreenDismissed() } + } + } + } + + /** Called (synchronously) by LockScreenActivity as the lock screen comes up. */ + override fun onLockScreenActivated() { + viewModel.onLockScreen() + } + /** * A terminal outcome (sent, may have gone through — including the one shown after a process * restart — or any other result but Not sent) returns Home. Not sent stays on this tab so the diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt index dae3d1b745..40bf0c06e0 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -165,12 +165,16 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr // A shielded leg's ~30 s proof can be left: Close hides the overlay (the form stays // disabled) and the outcome shows when it arrives. Back does what Close does, and // nothing while a Core / Platform transfer (seconds, not leavable) runs. - is ExternalSendStatus.Sending -> if (!uiState.sendingHidden) { + // Its own window would sit above the lock screen: withheld while it is up. + is ExternalSendStatus.Sending -> if (!uiState.sendingHidden && !uiState.lockScreenShown) { AboveBottomNavigation(onBack = if (status.shieldedLeg) actions.onHideSending else null) { SendingOverlay(status.shieldedLeg, actions.onHideSending) } } - is ExternalSendStatus.Done -> ResultDialog(status.result, status.afterRestart, actions.onResultClosed) + // Its own window would sit above the lock screen: withheld (not acknowledged) until unlock. + is ExternalSendStatus.Done -> if (!uiState.lockScreenShown) { + ResultDialog(status.result, status.afterRestart, actions.onResultClosed) + } ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt index 717e9e1d43..c4069b5154 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -91,6 +91,9 @@ data class InternalTransferConfirm( * @property confirmRefused Confirm was refused because the captured request no longer fits the * balance or pair (see [InternalTransferViewModel.confirmedRequest]); the sheet was closed and * the form says so until the user edits it or continues again. + * @property lockScreenShown the app's lock screen covers the activity: the sending overlay and the + * outcome dialog (their own windows, which would sit above the lock screen) are not shown until + * the wallet is unlocked; the outcome is not acknowledged (see [InternalTransferViewModel.onLockScreen]). */ data class InternalTransferUIState( val from: SendBalance = SendBalance.CORE, @@ -110,7 +113,8 @@ data class InternalTransferUIState( val confirm: InternalTransferConfirm? = null, val status: ExternalSendStatus = ExternalSendStatus.Idle, val sendingHidden: Boolean = false, - val confirmRefused: Boolean = false + val confirmRefused: Boolean = false, + val lockScreenShown: Boolean = false ) { val pair: InternalTransferPair get() = InternalTransferPair(from, to) @@ -535,6 +539,28 @@ class InternalTransferViewModel @Inject constructor( if (_uiState.value.status is ExternalSendStatus.Sending) _uiState.update { it.copy(sendingHidden = true) } } + /** + * The lock screen came up. The picker, confirm sheet, sending overlay and outcome are drawn in + * their own windows, which would stay above it: the picker and the confirm sheet are closed + * (the amount is kept; an authentication in progress is cancelled by the lock itself and + * transfers nothing). The sending overlay and the outcome are withheld until + * [onLockScreenDismissed]: a transfer still running (on the app scope) shows its overlay again + * after the unlock, and the outcome is not acknowledged. + * + * The confirm is closed whatever the status: while not Idle it is not on show and cannot be + * submitted ([stillValid]), so closing it cancels nothing but its fee estimate. + */ + fun onLockScreen() { + onDismissPicker() + onDismissConfirm() + _uiState.update { it.copy(lockScreenShown = true) } + } + + /** The wallet is unlocked: an outcome withheld by [onLockScreen] shows again. */ + fun onLockScreenDismissed() { + if (_uiState.value.lockScreenShown) _uiState.update { it.copy(lockScreenShown = false) } + } + /** Back closes an open sheet; false when there is nothing to close. */ fun onBack(): Boolean { val state = _uiState.value diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index b59d2bad1d..3a117978d4 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -396,6 +396,99 @@ class InternalTransferViewModelTest { assertTrue(service.transfers.isEmpty()) } + // ── lock screen ────────────────────────────────────────────────────────── + + @Test + fun `the lock screen closes the picker`() { + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.FROM) + viewModel.onLockScreen() + assertNull(viewModel.state.picker) + assertTrue(viewModel.state.lockScreenShown) + } + + @Test + fun `the lock screen closes the confirm and keeps the amount`() { + service.balances.getValue(CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + + viewModel.onLockScreen() + assertNull(viewModel.state.confirm) + assertEquals(oneDash, viewModel.state.amount) + assertEquals("1", viewModel.state.amountText) + // An authentication that completes after the lock transfers nothing. + assertFalse(viewModel.submit(request)) + assertTrue(service.transfers.isEmpty()) + + viewModel.onLockScreenDismissed() + assertFalse(viewModel.state.lockScreenShown) + assertTrue(viewModel.state.canContinue) + } + + @Test + fun `the lock screen withholds the sending overlay until the unlock and the transfer continues`() { + service.balances.getValue(CORE).value = twoDash + service.gate = CompletableDeferred() + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + assertTrue(viewModel.submit(request)) + + viewModel.onLockScreen() + assertFalse(viewModel.state.sendingHidden) + assertTrue(viewModel.state.lockScreenShown) + assertEquals(ExternalSendStatus.Sending(shieldedLeg = true), viewModel.state.status) + + // Unlocked while still running: the overlay shows again. + viewModel.onLockScreenDismissed() + assertFalse(viewModel.state.lockScreenShown) + assertFalse(viewModel.state.sendingHidden) + + viewModel.onLockScreen() + + // The outcome arrives while locked: kept, but withheld until the unlock. + service.gate?.complete(ExternalSendResult.Sent(null)) + assertEquals(ExternalSendStatus.Done(ExternalSendResult.Sent(null)), viewModel.state.status) + assertTrue(viewModel.state.lockScreenShown) + assertEquals(listOf(request), service.transfers) + } + + @Test + fun `the lock screen withholds the outcome without acknowledging it`() { + service.balances.getValue(CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.type("1") + viewModel.onContinue() + viewModel.submit(requireNotNull(viewModel.confirmedRequest())) + val done = ExternalSendStatus.Done(ExternalSendResult.Sent(null)) + assertEquals(done, viewModel.state.status) + + viewModel.onLockScreen() + assertTrue(viewModel.state.lockScreenShown) + assertEquals(done, viewModel.state.status) + assertTrue(executor.state.value is InternalTransferExecution.Finished) + + viewModel.onLockScreenDismissed() + assertFalse(viewModel.state.lockScreenShown) + assertEquals(done, viewModel.state.status) + + viewModel.onResultAcknowledged() + assertEquals(ExternalSendStatus.Idle, viewModel.state.status) + assertEquals("0", viewModel.state.amountText) + } + + @Test + fun `an unlock without a lock changes nothing`() { + val viewModel = buildViewModel() + val before = viewModel.state + viewModel.onLockScreenDismissed() + assertEquals(before, viewModel.state) + } + @Test fun `Not sent keeps the amount for a retry (AC14)`() { service.balances.getValue(CORE).value = twoDash From 83d47304ec9e2876a91a4e7d50a9edf4a5f56487 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 14:59:25 -0800 Subject: [PATCH 10/17] fix(payments): bottom navigation on Receive only; Internal sheets in place The Advanced payments screen now shows MainActivity's bottom navigation on the Receive tab only; Internal and Send hide it, re-applied after the destination listener when the screen becomes current again. Without the bar, the Internal transfer's picker, confirm sheet and sending overlay are drawn in place in the screen, as the External Send does, and AboveBottomNavigation (a separate dialog window) and the 60dp bottom padding are gone. The lock screen now covers those overlays, so on lock only the outcome dialog (its own window) is withheld until unlock. Verified on a testnet emulator: bar per tab, return from External Send, picker Back, confirm sheet above the system navigation. Co-Authored-By: Claude Opus 5.5 --- .../wallet/ui/main/MainActivityExt.kt | 9 + .../ui/payments/AdvancedPaymentsFragment.kt | 48 +++++- .../internal/InternalTransferFragment.kt | 16 +- .../internal/InternalTransferScreen.kt | 162 ++++-------------- .../internal/InternalTransferViewModel.kt | 24 +-- .../ui/payments/AdvancedPaymentsTabsTest.kt | 9 + .../internal/InternalTransferViewModelTest.kt | 27 +-- 7 files changed, 132 insertions(+), 163 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt b/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt index 047eb111a4..47a530ed78 100644 --- a/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt +++ b/wallet/src/de/schildbach/wallet/ui/main/MainActivityExt.kt @@ -83,6 +83,15 @@ object MainActivityExt { private const val EXPLORE_BUTTON_INDEX = 3 + /** + * Shows or hides the bottom navigation. The destination listener in [setupBottomNavigation] + * sets it from `ShowNavBar` on every destination change; a destination that varies it while + * current (the Advanced payments tabs) calls this after that listener has run. + */ + fun MainActivity.setBottomNavigationVisible(visible: Boolean) { + findViewById(R.id.bottom_navigation)?.isVisible = visible + } + fun MainActivity.setupBottomNavigation(viewModel: MainViewModel) { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt index 0c49274859..9f90be9361 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -44,9 +44,13 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle +import androidx.navigation.NavController +import androidx.navigation.fragment.findNavController import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.ui.main.MainActivity +import de.schildbach.wallet.ui.main.MainActivityExt.setBottomNavigationVisible 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 @@ -55,6 +59,7 @@ import de.schildbach.wallet.ui.payments.internal.InternalTransferFragment import de.schildbach.wallet.ui.payments.send.AdvancedSendFragment import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentAdvancedPaymentsBinding +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.map @@ -69,8 +74,9 @@ 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 / Internal / Send picker right under the status bar, over the payments pages. + * MainActivity's bottom navigation shows on the Receive tab only ([showsBottomNavigation]): + * the destination has `ShowNavBar`, and this screen hides the bar on the other tabs. * * Receive is [AdvancedReceiveFragment] (the Compose [ReceivePage]), Send is * [AdvancedSendFragment] (MO-1121) and Internal is [InternalTransferFragment] (MO-1125), shown @@ -93,6 +99,10 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { @VisibleForTesting fun positionOf(tabIds: List, tabId: Int): Int = tabIds.indexOf(tabId).takeIf { it >= 0 } ?: 0 + + /** MainActivity's bottom navigation shows on the Receive tab only. */ + @VisibleForTesting + fun showsBottomNavigation(tabId: Int): Boolean = tabId == ACTIVE_TAB_RECEIVE } private val binding by viewBinding(FragmentAdvancedPaymentsBinding::bind) @@ -145,6 +155,7 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { override fun onPageSelected(position: Int) { val tabId = adapter.tabIds.getOrNull(position) ?: return selectedTabId = tabId + applyBottomNavigation() if (arguments?.containsKey(ARG_ACTIVE_TAB) != true) { requireActivity().getPreferences(Context.MODE_PRIVATE) @@ -153,6 +164,22 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } }) + // MainActivity's destination listener sets the bottom navigation from `ShowNavBar` (true + // here) whenever this destination becomes current: on a return from a pushed destination + // or a dialog destination. It can be registered after this one (setupBottomNavigation runs + // again once the wallet is set up), so the tab's visibility is applied after every + // listener has run, from the main queue. Registering dispatches the current + // destination, so a recreated view (back from a fragment destination) applies it too. + val navController = findNavController() + val destinationListener = NavController.OnDestinationChangedListener { _, destination, _ -> + if (destination.id == R.id.advancedPaymentsFragment) { + // Dispatchers.Main (not immediate) always posts; cancelled with the view. + viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) { applyBottomNavigation() } + } + } + navController.addOnDestinationChangedListener(destinationListener) + viewLifecycleOwner.observeOnDestroy { navController.removeOnDestinationChangedListener(destinationListener) } + viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState @@ -164,6 +191,20 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } } + /** + * Shows the bottom navigation for the selected tab, only while this destination is current: + * once another destination is, its `ShowNavBar` (set by the destination listener) owns the bar, + * and a page selection during this screen's exit must not override it. + */ + private fun applyBottomNavigation() { + // Until showTabs picks a tab the bar stays as `ShowNavBar` set it. + val tabId = selectedTabId ?: return + if (!isAdded) return + val mainActivity = activity as? MainActivity ?: return + if (findNavController().currentDestination?.id != R.id.advancedPaymentsFragment) return + mainActivity.setBottomNavigationVisible(showsBottomNavigation(tabId)) + } + override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) selectedTabId?.let { outState.putInt(STATE_SELECTED_TAB, it) } @@ -185,6 +226,8 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } selectedTabId = newTabIds[position] binding.pager.setCurrentItem(position, false) + // setCurrentItem reports no selection when the position is unchanged. + applyBottomNavigation() } private fun initialTabId(): Int = @@ -235,6 +278,7 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { ) { _, index -> val tabId = ids.getOrNull(index) ?: return@SegmentedPicker selectedTabId = tabId + applyBottomNavigation() val pagerTabIds = (binding.pager.adapter as? TabsAdapter)?.tabIds.orEmpty() binding.pager.currentItem = positionOf(pagerTabIds, tabId) } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt index ef6d5cae7a..c48cb5846d 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt @@ -52,12 +52,13 @@ import javax.inject.Inject * * Confirm captures the exact request, then asks for PIN/biometric (the External Send's auth * path), then hands it to the app-scoped [InternalTransferExecutor]: leaving the screen does not - * cancel the transfer. Back closes an open sheet; otherwise it belongs to the host. Closing a - * finished transfer's outcome returns Home, as the External Send does; Not sent stays here. + * cancel the transfer. Back closes an open sheet; otherwise it belongs to the host (as in the + * External Send, Back while a transfer runs leaves it running). Closing a finished transfer's + * outcome returns Home, as the External Send does; Not sent stays here. * - * The lock screen is drawn in MainActivity's content, under this page's overlay windows: on lock - * ([onLockScreenActivated]) the sheets close and the outcome is withheld until the wallet is - * unlocked ([LockScreenActivity.walletLocked] turns false). + * The lock screen is drawn in MainActivity's content, over this page and its in-place sheets but + * under the outcome dialog's window: on lock ([onLockScreenActivated]) the outcome is withheld + * until the wallet is unlocked ([LockScreenActivity.walletLocked] turns false). */ @AndroidEntryPoint class InternalTransferFragment : Fragment(), LockScreenAware { @@ -78,10 +79,11 @@ class InternalTransferFragment : Fragment(), LockScreenAware { DashWalletTheme { val uiState by viewModel.uiState.collectAsStateWithLifecycle() // ViewPager2 lifts only the selected page to RESUMED: an offscreen Internal page - // must not take Back from the page on show. + // must not take Back from the page on show. Nor does a sheet the lock screen covers. val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() val selectedPage = lifecycleState.isAtLeast(Lifecycle.State.RESUMED) - BackHandler(enabled = selectedPage && (uiState.picker != null || uiState.confirm != null)) { + val sheetOpen = uiState.picker != null || uiState.confirm != null + BackHandler(enabled = selectedPage && !uiState.lockScreenShown && sheetOpen) { viewModel.onBack() } InternalTransferScreen( diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt index 40bf0c06e0..94fbb98786 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -17,8 +17,6 @@ package de.schildbach.wallet.ui.payments.internal -import android.os.Build -import android.view.Window import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.background @@ -29,39 +27,22 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.displayCutout import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.systemBars -import androidx.compose.foundation.layout.union -import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.getValue -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalView -import androidx.compose.ui.window.Dialog -import androidx.compose.ui.window.DialogProperties -import androidx.compose.ui.window.DialogWindowProvider -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.compose.LocalLifecycleOwner -import androidx.core.view.WindowCompat -import androidx.lifecycle.compose.currentStateAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout -import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -94,7 +75,6 @@ import org.dash.wallet.common.ui.components.Menu import org.dash.wallet.common.ui.components.MyImages import org.dash.wallet.common.ui.components.MyTheme import org.dash.wallet.common.ui.components.TopNavBase -import org.dash.wallet.common.ui.getActivity import org.dash.wallet.common.ui.enter_amount.AmountEntryPage import org.dash.wallet.common.ui.enter_amount.AmountEntryPrimaryButton @@ -121,7 +101,13 @@ private const val DISABLED_ROW_ALPHA = 0.4f * The Internal tab of the Advanced payments screen (MO-1125, Figma 3342:12176) under the * Receive / Internal / Send picker the host draws: the amount, the From / To cards with the swap * button, the keypad and Continue; the "Transfer from / to" picker (3342:12177); and the shared - * confirm sheet, sending overlay and outcome dialog of the External Send. + * confirm sheet, sending overlay and outcome dialog of the External Send, drawn as + * [de.schildbach.wallet.ui.payments.send.ExternalSendScreen] draws them. The host hides the + * bottom navigation on this tab, so the page reaches the bottom of MainActivity's content. + * + * The outcome dialog is its own window and would sit above the lock screen: it is withheld while + * the lock screen is up ([InternalTransferUIState.lockScreenShown]). The sheets and the sending + * overlay are drawn in the page, which the lock screen covers. */ @Composable fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTransferActions) { @@ -135,43 +121,21 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr val picker = uiState.picker if (picker != null && uiState.formEditable) { - AboveBottomNavigation(onBack = actions.onDismissPicker) { - PickerSheet(uiState, picker, actions) - } + PickerSheet(uiState, picker, actions) } val confirm = uiState.confirm if (confirm != null && uiState.status == ExternalSendStatus.Idle) { - val request = confirm.request - AboveBottomNavigation(onBack = actions.onDismissConfirm) { - SendConfirmSheet( - amount = request.amount, - rate = uiState.rate, - fiatCode = uiState.fiatCode, - fromValue = stringResource(balanceNameFor(request.from)), - toValue = stringResource(balanceNameFor(request.to)), - fee = confirm.fee, - feeLoading = confirm.feeLoading, - total = confirm.total, - feeIncluded = false, - notes = internalConfirmNotes(request.from, request.to), - onDismiss = actions.onDismissConfirm, - onConfirm = actions.onConfirm - ) - } + ConfirmSheet(uiState, confirm, actions) } when (val status = uiState.status) { // A shielded leg's ~30 s proof can be left: Close hides the overlay (the form stays - // disabled) and the outcome shows when it arrives. Back does what Close does, and - // nothing while a Core / Platform transfer (seconds, not leavable) runs. - // Its own window would sit above the lock screen: withheld while it is up. - is ExternalSendStatus.Sending -> if (!uiState.sendingHidden && !uiState.lockScreenShown) { - AboveBottomNavigation(onBack = if (status.shieldedLeg) actions.onHideSending else null) { - SendingOverlay(status.shieldedLeg, actions.onHideSending) - } + // disabled) and the outcome shows when it arrives. + is ExternalSendStatus.Sending -> if (!uiState.sendingHidden) { + SendingOverlay(status.shieldedLeg, actions.onHideSending) } - // Its own window would sit above the lock screen: withheld (not acknowledged) until unlock. + // Withheld (not acknowledged) while the lock screen is up. is ExternalSendStatus.Done -> if (!uiState.lockScreenShown) { ResultDialog(status.result, status.afterRestart, actions.onResultClosed) } @@ -180,82 +144,24 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr } } -/** - * Shows [content] (a full-screen scrim with a sheet or a card) in its own window, over the host's - * tab picker and the app's bottom navigation. The Internal page is a pager page of - * AdvancedPaymentsFragment, whose `nav_home` destination keeps MainActivity's bottom navigation - * drawn over the bottom of the nav host: drawn in the page, the sheet's lower rows would sit under - * it, and the scrim would leave the tab picker and the navigation tappable. The External Send has - * no bottom navigation, so it draws the same overlays in place. - * - * The window covers the whole screen (`decorFitsSystemWindows = false`) and the content is inset by - * the system bars and the display cutout, as MainActivity's `fitsSystemWindows` content is: the - * scrim starts at the bottom of the status bar and the sheet ends at the top of the system - * navigation, exactly where they are in the External Send. A decor-fitted dialog window is laid out - * by the platform instead, which left an un-dimmed band under the status bar. The status and - * navigation bars stay MainActivity's: the window draws no bar backgrounds of its own and copies - * the activity's light/dark bar icons. The window has no dim of its own: the overlay's scrim is the - * only one, so it looks as it does in the External Send. Back calls [onBack] (null: Back does - * nothing while the window shows). - * - * Only the selected pager page (RESUMED; ViewPager2 keeps the offscreen one at STARTED) opens the - * window: an offscreen Internal page draws the overlay in place, where it is not seen. - */ +/** Figma 3342:12176 confirm, through the shared [SendConfirmSheet]. */ @Composable -private fun AboveBottomNavigation(onBack: (() -> Unit)?, content: @Composable () -> Unit) { - val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() - if (!lifecycleState.isAtLeast(Lifecycle.State.RESUMED)) { - content() - return - } - val hostWindow = LocalContext.current.getActivity()?.window - Dialog( - onDismissRequest = { onBack?.invoke() }, - properties = DialogProperties( - dismissOnBackPress = onBack != null, - dismissOnClickOutside = false, - usePlatformDefaultWidth = false, - decorFitsSystemWindows = false - ) - ) { - val window = (LocalView.current.parent as? DialogWindowProvider)?.window - SideEffect { - window?.let { matchHostSystemBars(it, hostWindow) } - } - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding(WindowInsets.systemBars.union(WindowInsets.displayCutout)) - ) { - content() - } - } -} - -/** - * The overlay [window] leaves the system bars to the [hostWindow]: no dim, no animation, transparent - * bar backgrounds (MainActivity's show through) and the host's light/dark bar icons. - */ -private fun matchHostSystemBars(window: Window, hostWindow: Window?) { - window.setDimAmount(0f) - window.setWindowAnimations(0) - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) { - // No-ops on API 35+, where the bar backgrounds are always transparent. - @Suppress("DEPRECATION") - window.statusBarColor = android.graphics.Color.TRANSPARENT - @Suppress("DEPRECATION") - window.navigationBarColor = android.graphics.Color.TRANSPARENT - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - window.isStatusBarContrastEnforced = false - window.isNavigationBarContrastEnforced = false - } - if (hostWindow != null) { - val host = WindowCompat.getInsetsController(hostWindow, hostWindow.decorView) - val overlay = WindowCompat.getInsetsController(window, window.decorView) - overlay.isAppearanceLightStatusBars = host.isAppearanceLightStatusBars - overlay.isAppearanceLightNavigationBars = host.isAppearanceLightNavigationBars - } +private fun ConfirmSheet(uiState: InternalTransferUIState, confirm: InternalTransferConfirm, actions: InternalTransferActions) { + val request = confirm.request + SendConfirmSheet( + amount = request.amount, + rate = uiState.rate, + fiatCode = uiState.fiatCode, + fromValue = stringResource(balanceNameFor(request.from)), + toValue = stringResource(balanceNameFor(request.to)), + fee = confirm.fee, + feeLoading = confirm.feeLoading, + total = confirm.total, + feeIncluded = false, + notes = internalConfirmNotes(request.from, request.to), + onDismiss = actions.onDismissConfirm, + onConfirm = actions.onConfirm + ) } /** @@ -287,12 +193,12 @@ private fun AmountPage(uiState: InternalTransferUIState, actions: InternalTransf currencyCodes = codes, selectedCurrencyIndex = if (uiState.dashMode || fiatCode == null) 0 else 1, onKeyInput = actions.onKeyInput, - // Figma 3342:12176: the content column starts 10dp under the tab picker. - // The bottom clears MainActivity's bottom navigation, drawn over the pager (as the other - // bottom-nav screens do, e.g. More): the keypad and Continue sit right above it. + // Figma 3342:12176: the content column starts 10dp under the tab picker. No bottom + // navigation on this tab: Continue sits at the bottom of MainActivity's content, which + // (fitsSystemWindows) ends above the system navigation, as in the External Send. modifier = Modifier .fillMaxSize() - .padding(top = 10.dp, bottom = dimensionResource(R.dimen.bottom_nav_bar_height)), + .padding(top = 10.dp), secondaryAmount = uiState.secondaryAmountText, showPrimaryChevron = false, keypadEnabled = uiState.formEditable, diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt index c4069b5154..a0732a0a42 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -91,9 +91,9 @@ data class InternalTransferConfirm( * @property confirmRefused Confirm was refused because the captured request no longer fits the * balance or pair (see [InternalTransferViewModel.confirmedRequest]); the sheet was closed and * the form says so until the user edits it or continues again. - * @property lockScreenShown the app's lock screen covers the activity: the sending overlay and the - * outcome dialog (their own windows, which would sit above the lock screen) are not shown until - * the wallet is unlocked; the outcome is not acknowledged (see [InternalTransferViewModel.onLockScreen]). + * @property lockScreenShown the app's lock screen covers the activity: the outcome dialog (its own + * window, which would sit above the lock screen) is not shown, nor acknowledged, until the wallet + * is unlocked, and Back does not close the covered sheets (see [InternalTransferViewModel.onLockScreen]). */ data class InternalTransferUIState( val from: SendBalance = SendBalance.CORE, @@ -540,23 +540,17 @@ class InternalTransferViewModel @Inject constructor( } /** - * The lock screen came up. The picker, confirm sheet, sending overlay and outcome are drawn in - * their own windows, which would stay above it: the picker and the confirm sheet are closed - * (the amount is kept; an authentication in progress is cancelled by the lock itself and - * transfers nothing). The sending overlay and the outcome are withheld until - * [onLockScreenDismissed]: a transfer still running (on the app scope) shows its overlay again - * after the unlock, and the outcome is not acknowledged. - * - * The confirm is closed whatever the status: while not Idle it is not on show and cannot be - * submitted ([stillValid]), so closing it cancels nothing but its fee estimate. + * The lock screen came up. The picker, the confirm sheet and the sending overlay are drawn in + * the page, which the lock screen covers: they stay as they are and show again after the + * unlock (an authentication in progress is cancelled by the lock itself and transfers + * nothing). The outcome dialog is its own window and would sit above the lock screen: it is + * withheld, not acknowledged, until [onLockScreenDismissed]. */ fun onLockScreen() { - onDismissPicker() - onDismissConfirm() _uiState.update { it.copy(lockScreenShown = true) } } - /** The wallet is unlocked: an outcome withheld by [onLockScreen] shows again. */ + /** The wallet is unlocked: an outcome withheld by [onLockScreen] shows. */ fun onLockScreenDismissed() { if (_uiState.value.lockScreenShown) _uiState.update { it.copy(lockScreenShown = false) } } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt index d3e708a9e6..e5d49d4eb3 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt @@ -21,7 +21,9 @@ import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_IN import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_PAY import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_RECEIVE import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Test class AdvancedPaymentsTabsTest { @@ -66,4 +68,11 @@ class AdvancedPaymentsTabsTest { assertEquals(1, AdvancedPaymentsFragment.positionOf(twoTabs, ACTIVE_TAB_PAY)) assertEquals(0, AdvancedPaymentsFragment.positionOf(twoTabs, ACTIVE_TAB_INTERNAL)) } + + @Test + fun `the bottom navigation shows on the Receive tab only`() { + assertTrue(AdvancedPaymentsFragment.showsBottomNavigation(ACTIVE_TAB_RECEIVE)) + assertFalse(AdvancedPaymentsFragment.showsBottomNavigation(ACTIVE_TAB_INTERNAL)) + assertFalse(AdvancedPaymentsFragment.showsBottomNavigation(ACTIVE_TAB_PAY)) + } } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index 3a117978d4..4de6ce7ab8 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -399,37 +399,42 @@ class InternalTransferViewModelTest { // ── lock screen ────────────────────────────────────────────────────────── @Test - fun `the lock screen closes the picker`() { + fun `the picker stays open under the lock screen`() { val viewModel = buildViewModel() viewModel.onShowPicker(InternalTransferPicker.FROM) viewModel.onLockScreen() - assertNull(viewModel.state.picker) + // Drawn in the page, which the lock screen covers: it shows again as it was. + assertEquals(InternalTransferPicker.FROM, viewModel.state.picker) assertTrue(viewModel.state.lockScreenShown) + + viewModel.onLockScreenDismissed() + assertFalse(viewModel.state.lockScreenShown) + assertEquals(InternalTransferPicker.FROM, viewModel.state.picker) } @Test - fun `the lock screen closes the confirm and keeps the amount`() { + fun `the confirm stays open under the lock screen and transfers nothing by itself`() { service.balances.getValue(CORE).value = twoDash val viewModel = buildViewModel() viewModel.type("1") viewModel.onContinue() - val request = requireNotNull(viewModel.confirmedRequest()) + val confirm = requireNotNull(viewModel.state.confirm) viewModel.onLockScreen() - assertNull(viewModel.state.confirm) + // Drawn in the page, which the lock screen covers: it shows again as it was. The lock + // dismisses an authentication in progress, so nothing is submitted. + assertEquals(confirm, viewModel.state.confirm) assertEquals(oneDash, viewModel.state.amount) - assertEquals("1", viewModel.state.amountText) - // An authentication that completes after the lock transfers nothing. - assertFalse(viewModel.submit(request)) assertTrue(service.transfers.isEmpty()) viewModel.onLockScreenDismissed() assertFalse(viewModel.state.lockScreenShown) - assertTrue(viewModel.state.canContinue) + assertEquals(confirm, viewModel.state.confirm) + assertEquals(confirm.request, viewModel.confirmedRequest()) } @Test - fun `the lock screen withholds the sending overlay until the unlock and the transfer continues`() { + fun `the lock screen leaves a running transfer and its overlay as they are`() { service.balances.getValue(CORE).value = twoDash service.gate = CompletableDeferred() val viewModel = buildViewModel() @@ -439,11 +444,11 @@ class InternalTransferViewModelTest { assertTrue(viewModel.submit(request)) viewModel.onLockScreen() + // The overlay is drawn in the page, under the lock screen: not hidden. assertFalse(viewModel.state.sendingHidden) assertTrue(viewModel.state.lockScreenShown) assertEquals(ExternalSendStatus.Sending(shieldedLeg = true), viewModel.state.status) - // Unlocked while still running: the overlay shows again. viewModel.onLockScreenDismissed() assertFalse(viewModel.state.lockScreenShown) assertFalse(viewModel.state.sendingHidden) From 75ad19ec2ccb15fce4f9c41375e05f34b7acb808 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 12:22:50 -0800 Subject: [PATCH 11/17] fix(payments): forget Internal Transfer state on Reset Wallet InternalTransferExecutor now mirrors ExternalSendExecutor's wipe handling: a wallet-wipe listener plus a generation counter, so a finished, restarted or late-completing transfer of the wiped wallet is never shown to, and never touches the in-flight marker of, the next wallet. InternalTransferServiceImpl's own routes (Core -> Shielded, Shielded -> Platform, Platform -> Shielded) now submit under FundingSelectionLock.withSharedSubmission with the bound-wallet check inside the hold; delegated routes already take it in ExternalSendService.send. Co-Authored-By: Claude Opus 5.5 --- .../sdk/InternalTransferServiceImpl.kt | 77 ++++++++-- .../internal/InternalTransferExecutor.kt | 78 +++++++++- .../sdk/InternalTransferServiceImplTest.kt | 88 ++++++++++- .../internal/InternalTransferExecutorTest.kt | 139 ++++++++++++++++++ 4 files changed, 360 insertions(+), 22 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index 2cbf10e6a9..1d5f73291b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -19,6 +19,8 @@ package de.schildbach.wallet.service.platform.sdk import de.schildbach.wallet.data.WalletData import de.schildbach.wallet.database.entity.BlockchainIdentityConfig +import de.schildbach.wallet.payments.FundingSelectionLock +import de.schildbach.wallet.payments.SubmissionMark import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet.ui.shielded.shieldedMaxFeeAdjustment import kotlinx.coroutines.CancellationException @@ -145,13 +147,24 @@ internal class DashSdkInternalTransferSource( * captured at confirmation is the bound one; the own destination is resolved (fail closed); * the wallet is re-checked right before the write, which is pinned to it. Broadcast → Sent, * NotBroadcast → Not sent, Ambiguous or anything unclassified → may have gone through. + * + * Reset Wallet: the delegated routes hold the wallet-wipe barrier inside + * [ExternalSendService.send]; the self routes this class submits itself (Core → Shielded, + * Shielded → Platform, Platform → Shielded) hold it here ([submitUnderWipeBarrier]), with the + * final wallet re-check inside the hold. */ @Singleton class InternalTransferServiceImpl internal constructor( private val externalSendService: ExternalSendService, private val source: InternalTransferSource, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, - private val retryDelayMs: (Long) -> Long = ::readRetryDelayMs + private val retryDelayMs: (Long) -> Long = ::readRetryDelayMs, + /** + * The wallet-wipe barrier the self routes hold shared ([submitUnderWipeBarrier]): the app's + * one [FundingSelectionLock], the one Reset Wallet raises. No default: a private lock is one + * no wipe raises. + */ + private val fundingSelection: FundingSelectionLock ) : InternalTransferService { @Inject @@ -162,12 +175,14 @@ class InternalTransferServiceImpl internal constructor( shieldedBalanceService: ShieldedBalanceService, dashPayConfig: DashPayConfig, identityConfig: BlockchainIdentityConfig, - walletData: WalletData + walletData: WalletData, + fundingSelection: FundingSelectionLock ) : this( externalSendService, DashSdkInternalTransferSource( sdkService, sdkL1SendService, shieldedBalanceService, dashPayConfig, identityConfig, walletData - ) + ), + fundingSelection = fundingSelection ) private val inFlight = AtomicBoolean(false) @@ -293,15 +308,22 @@ class InternalTransferServiceImpl internal constructor( } SendBalance.SHIELDED -> when (from) { SendBalance.CORE -> shieldFromOwnCore(pair, walletIdHex, amount) - else -> { - if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) - mapWrite(pair, source.shieldFromCredits(amount, walletIdHex)) - } + else -> mapWrite( + pair, + submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + source.shieldFromCredits(amount, walletIdHex) + } + ) } } } - /** An existing External Send route to the resolved own [destination], after a wallet re-check. */ + /** + * An existing External Send route to the resolved own [destination], after a wallet re-check. + * Not under [submitUnderWipeBarrier]: [ExternalSendService.send] takes the wipe barrier itself + * around its write, with its own final wallet check inside it. + */ private suspend fun delegate( pair: String, walletIdHex: String, @@ -323,8 +345,9 @@ class InternalTransferServiceImpl internal constructor( } catch (e: ArithmeticException) { return notSent(pair, NotSentReason.GENERIC, "amount out of range") } - if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) - return when (val result = source.shieldFromWallet(lock, walletIdHex)) { + // The shield's own submission hold nests in this one and marks its submission point. + val result = submitUnderWipeBarrier(pair, walletIdHex) { source.shieldFromWallet(lock, walletIdHex) } + return when (result) { is SdkWriteResult.Broadcast -> when (result.value) { ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) ShieldFromWalletOutcome.SHIELD_PENDING_RETRY -> { @@ -343,9 +366,9 @@ class InternalTransferServiceImpl internal constructor( amount: Dash, isMax: Boolean ): ExternalSendResult { - suspend fun attempt(value: Dash): SdkWriteResult { - if (!stillBound(pair, walletIdHex)) return SdkWriteResult.NotBroadcast("the bound wallet changed") - return source.unshieldToCredits(value, walletIdHex) + suspend fun attempt(value: Dash): SdkWriteResult = submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + source.unshieldToCredits(value, walletIdHex) } var result = attempt(amount) val first = result @@ -375,6 +398,34 @@ class InternalTransferServiceImpl internal constructor( } } + /** + * [write] under the wallet-wipe barrier: a shared [FundingSelectionLock] submission hold, + * as every SDK broadcast takes ([FundingSelectionLock.withSharedSubmission]), with the final + * bound-wallet check ([stillBound]) INSIDE it, so a Reset Wallet either refuses the write + * before the check or waits for it to return. [write] calls [SubmissionMark.submitting] + * right before the call that may put something on the network (a nested submission hold + * marks it itself). + * - Refused (a wipe was under way): nothing ran, NotBroadcast (Not sent). + * - Cancelled by a wipe: NotBroadcast before the mark, Ambiguous after it + * ([wipeCancelledWriteResult]), never a cancellation that reads as "nothing happened". + * - Not the bound wallet: NotBroadcast, nothing called. + * Shared holds are reentrant, so a write whose own path holds the lock again nests in this one. + */ + private suspend fun submitUnderWipeBarrier( + pair: String, + walletIdHex: String, + write: suspend (SubmissionMark) -> SdkWriteResult + ): SdkWriteResult = fundingSelection.withSharedSubmission>( + refused = { e -> SdkWriteResult.NotBroadcast("a wallet wipe is under way", e) }, + cancelled = { e, submitted -> wipeCancelledWriteResult("internal transfer $pair", null, e, submitted) } + ) { mark -> + if (!stillBound(pair, walletIdHex)) { + SdkWriteResult.NotBroadcast("the bound wallet changed") + } else { + write(mark) + } + } + /** Re-read the bound SDK wallet: it must still be [walletIdHex]. */ private suspend fun stillBound(pair: String, walletIdHex: String): Boolean { val now = readOrNull("bound wallet") { source.boundWalletIdOrNull() } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt index bb67bd513d..cbc9359c3d 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt @@ -17,6 +17,7 @@ package de.schildbach.wallet.ui.payments.internal +import de.schildbach.wallet.data.WalletData import de.schildbach.wallet.service.platform.sdk.ExternalSendResult import de.schildbach.wallet.service.platform.sdk.InternalTransferService import de.schildbach.wallet.service.platform.sdk.NotSentReason @@ -35,6 +36,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.dash.wallet.common.money.Dash import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject import javax.inject.Singleton @@ -84,6 +86,11 @@ sealed class InternalTransferExecution { * A sibling rather than a generalized External Send executor: that executor's state type is * public API of the External Send screen and its tests, and sharing one instance would let one * flow's screen show (and acknowledge) the other's outcome. + * + * Reset Wallet: this singleton outlives the wallet, so a wipe listener ([forgetWalletState]) + * returns it to Idle and moves it to a new wallet generation. A transfer of the wiped wallet that + * completes afterwards publishes nothing and touches no marker: the next wallet never shows the + * old one's outcome, nor an interruption the old one left behind. */ @Singleton class InternalTransferExecutor internal constructor( @@ -95,12 +102,15 @@ class InternalTransferExecutor internal constructor( constructor( service: InternalTransferService, dashPayConfig: DashPayConfig, + walletData: WalletData, applicationScope: CoroutineScope ) : this( service, DashPayConfigInFlightMarker(dashPayConfig, DashPayConfig.INTERNAL_TRANSFER_IN_FLIGHT), applicationScope - ) + ) { + walletData.attachOnWalletWipedListener { forgetWalletState() } + } companion object { private val log = LoggerFactory.getLogger(InternalTransferExecutor::class.java) @@ -109,8 +119,16 @@ class InternalTransferExecutor internal constructor( private val _state = MutableStateFlow(InternalTransferExecution.Restoring) val state: StateFlow = _state.asStateFlow() + /** + * The wallet generation: bumped by every wipe ([forgetWalletState]). A transfer captures it + * when submitted and, once the wallet it was for is gone, neither publishes its outcome nor + * touches the in-flight marker (which may by then be the next wallet's). + */ + private val generation = AtomicLong(0) + init { applicationScope.launch { + val restoredIn = generation.get() val interrupted = try { marker.isSet() } catch (e: CancellationException) { @@ -121,7 +139,9 @@ class InternalTransferExecutor internal constructor( } if (interrupted) log.warn("internal transfer: a previous process may have left a transfer in flight") _state.update { - if (it is InternalTransferExecution.Restoring) { + // A wipe while the marker was read already returned the state to Idle (and the + // marker it read was the wiped wallet's): the read is not applied. + if (it is InternalTransferExecution.Restoring && generation.get() == restoredIn) { if (interrupted) InternalTransferExecution.InterruptedByRestart else InternalTransferExecution.Idle } else { it @@ -132,6 +152,11 @@ class InternalTransferExecutor internal constructor( /** Start [request]; refused (false) unless Idle. A terminal result is never silently replaced. */ fun submit(request: InternalTransferRequest): Boolean { + // Read BEFORE the state claim: a wipe that resets the state from here on is seen by + // [isCurrent], so this transfer can never publish into the next wallet's state. + val submittedIn = generation.get() + + fun isCurrent() = generation.get() == submittedIn var accepted = false _state.update { current -> if (current is InternalTransferExecution.Idle) { @@ -150,6 +175,11 @@ class InternalTransferExecutor internal constructor( var result: ExternalSendResult = ExternalSendResult.MayHaveGoneThrough var marked = false try { + if (!isCurrent()) { + // The wallet was wiped before anything was handed to the service. + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + return@launch + } try { marker.set() marked = true @@ -160,6 +190,13 @@ class InternalTransferExecutor internal constructor( log.warn("internal transfer: could not record the in-flight marker; not sent", e) result = ExternalSendResult.NotSent(NotSentReason.GENERIC) } + if (marked && !isCurrent()) { + // A wipe ran while the marker was written, possibly after it cleared the + // marker: this one belongs to the wiped wallet. Nothing is sent. + withContext(NonCancellable) { clearMarker() } + marked = false + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + } if (marked) { result = service.transfer( request.from, @@ -175,11 +212,20 @@ class InternalTransferExecutor internal constructor( log.error("internal transfer threw; outcome unknown", e) } finally { log.info("internal transfer {} → {} finished: {}", request.from, request.to, kindOf(result)) - // Cleared BEFORE the outcome is published, and only on Not sent. - if (marked && result is ExternalSendResult.NotSent) { - withContext(NonCancellable) { clearMarker() } + if (!isCurrent()) { + // The wallet it was for was wiped: its outcome is not the next wallet's to + // see, and the marker (cleared by the wipe) may already be the next one's. + log.warn("internal transfer: finished after a wallet wipe; outcome dropped") + } else { + // Cleared BEFORE the outcome is published, and only on Not sent. + if (marked && result is ExternalSendResult.NotSent) { + withContext(NonCancellable) { clearMarker() } + } + // Checked again in the update (after the clear's suspension): a wipe that + // bumped the generation, or already reset the state, wins. + val outcome = result + _state.update { if (isCurrent()) InternalTransferExecution.Finished(request, outcome) else it } } - _state.value = InternalTransferExecution.Finished(request, result) } } return true @@ -197,13 +243,31 @@ class InternalTransferExecutor internal constructor( _state.compareAndSet(current, InternalTransferExecution.Idle) return } + val acknowledgedIn = generation.get() if (!_state.compareAndSet(current, InternalTransferExecution.Acknowledging)) return applicationScope.launch { - clearMarker() + // After a wipe the marker is the wipe's (cleared) or the next wallet's: left alone. + if (generation.get() == acknowledgedIn) clearMarker() _state.compareAndSet(InternalTransferExecution.Acknowledging, InternalTransferExecution.Idle) } } + /** + * Reset Wallet (a wallet-wipe listener, run after the wipe drained every payment hold and + * cleared the configs): forgets every outcome of the wiped wallet, an interruption by restart + * included. Bumps [generation] first, so a transfer of that wallet still finishing (or a + * restore still reading the marker) publishes nothing, then clears the in-flight marker + * (again: [DashPayConfig] is cleared by the wipe too, but a transfer may have written it + * after that) and returns to Idle. + */ + internal suspend fun forgetWalletState() { + generation.incrementAndGet() + // Cleared before Idle, so no transfer of the next wallet can have set it yet. + clearMarker() + _state.value = InternalTransferExecution.Idle + log.info("internal transfer: state reset for a wallet wipe") + } + private suspend fun clearMarker() { try { marker.clear() diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt index 2ff0b28aaa..d773c70686 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -17,6 +17,7 @@ package de.schildbach.wallet.service.platform.sdk +import de.schildbach.wallet.payments.FundingSelectionLock import de.schildbach.wallet.service.platform.sdk.SendBalance.CORE import de.schildbach.wallet.service.platform.sdk.SendBalance.IDENTITY import de.schildbach.wallet.service.platform.sdk.SendBalance.PLATFORM @@ -31,6 +32,7 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.yield import org.dash.wallet.common.money.Dash import org.dash.wallet.common.payments.parsers.AddressNetwork import org.dash.wallet.common.payments.parsers.Base58 @@ -108,12 +110,19 @@ class InternalTransferServiceImplTest { var creditsResult: SdkWriteResult = SdkWriteResult.Broadcast(Unit) val unshieldResults = ArrayDeque>() val writes = mutableListOf() + var boundReads = 0 + + /** Runs inside every self-route write, after it is recorded (e.g. a wipe mid-call). */ + var duringWrite: suspend () -> Unit = {} var flag: Flow = flowOf(true) override suspend fun cutoverCommittedOrThrow(): Boolean = committed ?: throw IOException("unreadable") override suspend fun shieldedEnabledOrThrow(): Boolean = shielded ?: throw IOException("unreadable") override fun observeShieldedFlag(): Flow = flag - override suspend fun boundWalletIdOrNull(): String? = boundWallets.removeFirstOrNull() ?: defaultBound + override suspend fun boundWalletIdOrNull(): String? { + boundReads++ + return boundWallets.removeFirstOrNull() ?: defaultBound + } override suspend fun ownIdentityIdOrThrow(): String? = identity.getOrThrow() override fun unadvertisedCoreAddress(): String = coreAddress() val platformAddressReads = mutableListOf() @@ -126,23 +135,33 @@ class InternalTransferServiceImplTest { override suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult { shieldFromWalletThrows?.let { throw it } writes += "shieldFromWallet(${amount.duffs}, $walletIdHex)" + duringWrite() return shieldFromWalletResult } override suspend fun shieldFromCredits(amount: Dash, walletIdHex: String): SdkWriteResult { writes += "shieldFromCredits(${amount.duffs}, $walletIdHex)" + duringWrite() return creditsResult } override suspend fun unshieldToCredits(amount: Dash, walletIdHex: String): SdkWriteResult { writes += "unshieldToCredits(${amount.duffs}, $walletIdHex)" + duringWrite() return unshieldResults.removeFirstOrNull() ?: creditsResult } } private val external = FakeExternal() private val source = FakeSource() - private val service = InternalTransferServiceImpl(external, source, Dispatchers.Unconfined, retryDelayMs = { 0L }) + private val fundingSelection = FundingSelectionLock() + private val service = InternalTransferServiceImpl( + external, + source, + Dispatchers.Unconfined, + retryDelayMs = { 0L }, + fundingSelection = fundingSelection + ) private fun transfer(from: SendBalance, to: SendBalance, isMax: Boolean = false, wallet: String? = WALLET_A) = runBlocking { service.transfer(from, to, amount, isMax, wallet) } @@ -352,6 +371,71 @@ class InternalTransferServiceImplTest { assertEquals(ExternalSendResult.MayHaveGoneThrough, transfer(CORE, SHIELDED)) } + // ── Reset Wallet: the wipe barrier ─────────────────────────────────────── + + /** The self routes this service submits itself (the rest hold the barrier in the External Send). */ + private val selfRoutes = listOf(CORE to SHIELDED, SHIELDED to PLATFORM, PLATFORM to SHIELDED) + + @Test + fun `a wipe under way refuses every self route with nothing called`() { + for ((from, to) in selfRoutes) { + fundingSelection.raiseWipeBarrier() + assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(from, to)) + assertNothingSubmitted() + + // The next wallet's transfers go through once the wipe is done. + fundingSelection.lowerWipeBarrier() + assertEquals("$from → $to", ExternalSendResult.Sent(null), transfer(from, to)) + source.writes.clear() + } + } + + @Test + fun `the final wallet check runs inside the hold, so a refusal comes before it`() { + for ((from, to) in selfRoutes) { + // One bound read before the hold (transferInner) and none inside it: the wipe refuses first. + fundingSelection.raiseWipeBarrier() + source.boundReads = 0 + assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(from, to)) + assertEquals("$from → $to", 1, source.boundReads) + + fundingSelection.lowerWipeBarrier() + source.boundReads = 0 + assertEquals("$from → $to", ExternalSendResult.Sent(null), transfer(from, to)) + assertEquals("$from → $to", 2, source.boundReads) + } + } + + @Test + fun `delegated routes do not take the barrier here`() { + // The External Send holds it around its own write; a raised barrier is its to refuse. + fundingSelection.raiseWipeBarrier() + assertEquals(ExternalSendResult.Sent("txid"), transfer(SHIELDED, CORE)) + assertEquals(1, external.sends.size) + fundingSelection.lowerWipeBarrier() + } + + @Test + fun `a wipe that cancels a credits write after its submission may have gone through, never a cancellation`() { + for ((from, to) in listOf(SHIELDED to PLATFORM, PLATFORM to SHIELDED)) { + val lock = FundingSelectionLock() + val gated = InternalTransferServiceImpl( + external, + source, + Dispatchers.Unconfined, + retryDelayMs = { 0L }, + fundingSelection = lock + ) + source.duringWrite = { + // Reset Wallet starts while the SDK call runs; the call then notices the cancel. + lock.raiseWipeBarrier() + yield() + } + val result = runBlocking { gated.transfer(from, to, amount, false, WALLET_A) } + assertEquals("$from → $to", ExternalSendResult.MayHaveGoneThrough, result) + } + } + // ── fee, max and reads ─────────────────────────────────────────────────── @Test diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt index 1f7efac273..07eb13d204 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt @@ -28,6 +28,9 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestCoroutineScheduler import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.dash.wallet.common.money.Dash import org.junit.Assert.assertEquals @@ -70,6 +73,7 @@ class InternalTransferExecutorTest { var failReads = false var failWrites = false var readGate: CompletableDeferred? = null + var setGate: CompletableDeferred? = null var clearGate: CompletableDeferred? = null var clearCalls = 0 val log = mutableListOf() @@ -81,6 +85,7 @@ class InternalTransferExecutorTest { } override suspend fun set() { + setGate?.await() if (failWrites) throw java.io.IOException("datastore") log += "set" value = true @@ -207,4 +212,138 @@ class InternalTransferExecutorTest { gate.complete(ExternalSendResult.MayHaveGoneThrough) assertTrue(marker.value) } + + // ── Reset Wallet ───────────────────────────────────────────────────────── + + @Test + fun `a wallet wipe forgets an unacknowledged outcome and clears the marker`() { + val executor = newExecutor() + assertTrue(executor.submit(request)) + assertTrue(executor.state.value is InternalTransferExecution.Finished) + assertTrue(marker.value) + + runBlocking { executor.forgetWalletState() } + + assertEquals(InternalTransferExecution.Idle, executor.state.value) + assertFalse(marker.value) + // The executor is free for the next wallet. + assertTrue(executor.submit(request)) + } + + @Test + fun `a wallet wipe forgets an interruption by restart`() { + marker.value = true + val executor = newExecutor() + assertEquals(InternalTransferExecution.InterruptedByRestart, executor.state.value) + + runBlocking { executor.forgetWalletState() } + + assertEquals(InternalTransferExecution.Idle, executor.state.value) + assertFalse(marker.value) + assertTrue(executor.submit(request)) + } + + @Test + fun `a wipe while the startup marker is read leaves the next wallet Idle`() { + val readGate = CompletableDeferred() + marker.readGate = readGate + marker.value = true // the wiped wallet's + val executor = newExecutor() + assertEquals(InternalTransferExecution.Restoring, executor.state.value) + + runBlocking { executor.forgetWalletState() } + assertEquals(InternalTransferExecution.Idle, executor.state.value) + marker.value = true // as read before the wipe cleared it + readGate.complete(Unit) + + assertEquals(InternalTransferExecution.Idle, executor.state.value) + } + + @Test + fun `a transfer of the wiped wallet completing late never publishes nor touches the next wallet's marker`() { + val lateResults = listOf( + ExternalSendResult.Sent(null), + ExternalSendResult.NotSent(NotSentReason.GENERIC), + ExternalSendResult.MayHaveGoneThrough + ) + for (late in lateResults) { + marker.value = false + val executor = newExecutor() + val gate = CompletableDeferred() + service.gate = gate + assertTrue(executor.submit(request)) + assertTrue(executor.state.value is InternalTransferExecution.Sending) + + runBlocking { executor.forgetWalletState() } + assertEquals(InternalTransferExecution.Idle, executor.state.value) + assertFalse(marker.value) + // The next wallet's transfer has written its own marker by the time the old one returns. + marker.value = true + val clearsBefore = marker.clearCalls + + gate.complete(late) + assertEquals("$late", InternalTransferExecution.Idle, executor.state.value) + assertTrue("$late", marker.value) + assertEquals("$late", clearsBefore, marker.clearCalls) + service.gate = null + } + } + + @Test + fun `a wipe while the marker is written sends nothing and clears the marker it wrote`() { + val executor = newExecutor() + val setGate = CompletableDeferred() + marker.setGate = setGate + assertTrue(executor.submit(request)) + assertEquals(InternalTransferExecution.Sending(request), executor.state.value) + + runBlocking { executor.forgetWalletState() } + assertEquals(InternalTransferExecution.Idle, executor.state.value) + // The write lands after the wipe cleared the marker. + setGate.complete(Unit) + + assertTrue(service.transfers.isEmpty()) + assertFalse(marker.value) + assertEquals(InternalTransferExecution.Idle, executor.state.value) + } + + @Test + fun `a wipe before the transfer starts sends nothing and leaves the marker alone`() { + val scheduler = TestCoroutineScheduler() + val executor = InternalTransferExecutor(service, marker, CoroutineScope(StandardTestDispatcher(scheduler))) + scheduler.runCurrent() + assertEquals(InternalTransferExecution.Idle, executor.state.value) + assertTrue(executor.submit(request)) + + runBlocking { executor.forgetWalletState() } + val clearsBefore = marker.clearCalls + scheduler.runCurrent() + + assertTrue(service.transfers.isEmpty()) + assertFalse("set" in marker.log) + assertEquals(clearsBefore, marker.clearCalls) + assertEquals(InternalTransferExecution.Idle, executor.state.value) + } + + @Test + fun `an acknowledgement after a wipe leaves the next wallet's marker alone`() { + val scheduler = TestCoroutineScheduler() + val executor = InternalTransferExecutor(service, marker, CoroutineScope(StandardTestDispatcher(scheduler))) + scheduler.runCurrent() + assertTrue(executor.submit(request)) + scheduler.runCurrent() + assertEquals(InternalTransferExecution.Finished(request, ExternalSendResult.Sent(null)), executor.state.value) + + executor.acknowledge() + assertEquals(InternalTransferExecution.Acknowledging, executor.state.value) + // The wipe runs before the acknowledgement's clear does. + runBlocking { executor.forgetWalletState() } + marker.value = true // the next wallet's + val clearsBefore = marker.clearCalls + scheduler.runCurrent() + + assertTrue(marker.value) + assertEquals(clearsBefore, marker.clearCalls) + assertEquals(InternalTransferExecution.Idle, executor.state.value) + } } From 484273a933695ee36e052a6188e8ef355e8e0b81 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 13:01:55 -0800 Subject: [PATCH 12/17] fix(ui): keep screen Back handlers above the activity after a restart LockScreenActivity registered its Back callback with the activity as LifecycleOwner. Such a callback is removed at ON_STOP and re-added at ON_START, which the activity reaches after its fragments, so after any screen-off it sat above every fragment and Compose BackHandler and took Back from them (Advanced Payments: Back left the screen instead of closing the balance picker or confirm sheet, and skipped acknowledging an outcome). The activity's Back is now added once without a LifecycleOwner, so it stays the lowest priority, and removed in onDestroy. A second callback, enabled only while the lock screen is displayed and re-added on top when it comes up, keeps Back from reaching the screens it covers. Co-Authored-By: Claude Opus 5.5 --- .../wallet/ui/LockScreenActivity.kt | 49 +++++++++++++++++-- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/LockScreenActivity.kt b/wallet/src/de/schildbach/wallet/ui/LockScreenActivity.kt index c285417f8c..9a7940e797 100644 --- a/wallet/src/de/schildbach/wallet/ui/LockScreenActivity.kt +++ b/wallet/src/de/schildbach/wallet/ui/LockScreenActivity.kt @@ -25,7 +25,7 @@ import android.security.keystore.KeyPermanentlyInvalidatedException import android.view.View import android.view.animation.AnimationUtils import android.view.inputmethod.InputMethodManager -import androidx.activity.addCallback +import androidx.activity.OnBackPressedCallback import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible @@ -148,6 +148,36 @@ open class LockScreenActivity : SecureActivity(), LockScreenHost { _walletLocked.value = true } + /** + * Back for the activity itself, at the LOWEST priority for its whole life: added once in + * [onCreate] without a LifecycleOwner, so every fragment, NavController and Compose + * `BackHandler` callback is above it, and removed in [onDestroy]. + * + * It used to be added with the activity as LifecycleOwner. Such a callback is removed at + * ON_STOP and re-added at ON_START, and the activity's ON_START comes after its fragments + * have started, so after any screen-off it was re-added above every fragment's callback and + * took Back from them (a Compose sheet or outcome on Advanced Payments: Back left the screen + * instead of closing it). + */ + private val backNavigationCallback = object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() = handleBackNavigation() + } + + /** + * Swallows Back while the lock screen covers the content, which the fragments under it must + * not get. Enabled only then ([syncLockScreenBackCallback]), and kept at the TOP: it has the + * activity as LifecycleOwner, so each ON_START (after the fragments') re-adds it above them, + * and [setLockState] re-adds it when the lock screen comes up over callbacks added since. + * It calls [handleBackNavigation], which ignores Back while [lockScreenDisplayed]. + */ + private val lockScreenBackCallback = object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() = handleBackNavigation() + } + + private fun syncLockScreenBackCallback() { + lockScreenBackCallback.isEnabled = lockScreenDisplayed + } + private val temporaryLockCheckHandler = Handler() private val temporaryLockCheckInterval = TimeUnit.SECONDS.toMillis(10) private val temporaryLockCheckRunnable = Runnable { @@ -231,9 +261,9 @@ open class LockScreenActivity : SecureActivity(), LockScreenHost { binding = ActivityLockScreenRootBinding.inflate(layoutInflater) super.setContentView(binding.root) isLocked = autoLogout.shouldLogout() - onBackPressedDispatcher.addCallback(this) { - handleBackNavigation() - } + onBackPressedDispatcher.addCallback(backNavigationCallback) + syncLockScreenBackCallback() + onBackPressedDispatcher.addCallback(this, lockScreenBackCallback) initView() initViewModel() @@ -369,6 +399,7 @@ open class LockScreenActivity : SecureActivity(), LockScreenHost { handleLockScreenActivated() } else { binding.rootViewSwitcher.displayedChild = 1 + syncLockScreenBackCallback() _walletLocked.value = false if (!keepUnlocked) { autoLogout.maybeStartAutoLogoutTimer() @@ -558,6 +589,7 @@ open class LockScreenActivity : SecureActivity(), LockScreenHost { overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } else { binding.rootViewSwitcher.displayedChild = 1 + syncLockScreenBackCallback() _walletLocked.value = false // After the content is shown again: a listener may now re-show what the lock dismissed. lockScreenBroadcaster.notifyUnlocked() @@ -662,6 +694,12 @@ open class LockScreenActivity : SecureActivity(), LockScreenHost { if (!lockScreenDisplayed) { binding.rootViewSwitcher.displayedChild = 0 + syncLockScreenBackCallback() + // Back to the top, above any callback a screen added while the content showed. A + // callback with a LifecycleOwner is added at once while STARTED, at the next + // ON_START while stopped, and not at all once destroyed. + lockScreenBackCallback.remove() + onBackPressedDispatcher.addCallback(this, lockScreenBackCallback) } } @@ -691,6 +729,9 @@ open class LockScreenActivity : SecureActivity(), LockScreenHost { override fun onDestroy() { super.onDestroy() + // Never added after an early-finished onCreate; remove() is a no-op then. The lock + // screen's callback goes with the lifecycle (ON_DESTROY). + backNavigationCallback.remove() temporaryLockCheckHandler.removeCallbacks(temporaryLockCheckRunnable) lockScreenDeactivatedListeners.clear() } From 6f7c73534c259f3f73678c3414246bcd71a34697 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 13:23:48 -0800 Subject: [PATCH 13/17] feat(payments): allow Core -> Platform as an Internal Transfer External Send (#1680) now funds a Platform address from Core (fundFromAssetLockExternal), so the Internal pair matrix allows Core -> Platform. The route already delegated to External Send with the wallet's own Platform address; fee (paid on top), Max, pending-funding resume and the wipe barrier all come from External Send. Identity -> Shielded is now the only pair not supported yet. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/InternalTransferModels.kt | 9 ++- .../sdk/InternalTransferServiceImpl.kt | 15 +++-- .../sdk/InternalTransferModelsTest.kt | 11 ++-- .../sdk/InternalTransferServiceImplTest.kt | 55 ++++++++++++++++++- .../internal/InternalTransferViewModelTest.kt | 29 +++++++++- 5 files changed, 101 insertions(+), 18 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt index 146a54c417..d7e9e5e751 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt @@ -43,12 +43,15 @@ enum class InternalTransferSupport { * * | From \ To | Core | Shielded | Platform | Identity | * |---|---|---|---|---| - * | Core | — | yes | no (1) | yes | + * | Core | — | yes | yes (1) | yes | * | Shielded | yes | — | yes | yes | * | Platform | yes (2) | yes | — | yes | * | Identity | yes | no (3) | yes | — | * - * 1. The Platform-address funding from an asset lock is not wired for this flow yet. + * 1. The External Send's Core → Platform (`fundFromAssetLockExternal`) to the wallet's own + * Platform address: the fee (L1 lock reserve plus the Platform-fee margin, whose unused + * part lands on another own Platform address) is paid on top; an interrupted lock is + * resumed by the External Send's pending-funding sweep. * 2. The External Send's partial Platform → Core withdrawal (`withdrawCredits` with the * inputs the wallet selects) to the wallet's own unadvertised Core address. * 3. `shieldedShieldFromIdentity` (Type 21) is not bound in the wallet yet. @@ -74,7 +77,7 @@ fun internalTransferSupport( /** The bare matrix of [internalTransferSupport]: whether the wallet can move [from] → [to] at all. */ fun internalTransferPairSupported(from: SendBalance, to: SendBalance): Boolean = when (from) { - SendBalance.CORE -> to == SendBalance.SHIELDED || to == SendBalance.IDENTITY + SendBalance.CORE -> to != SendBalance.CORE SendBalance.SHIELDED -> to != SendBalance.SHIELDED SendBalance.PLATFORM -> to != SendBalance.PLATFORM SendBalance.IDENTITY -> to == SendBalance.CORE || to == SendBalance.PLATFORM diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index 1d5f73291b..e40cf1f888 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -124,7 +124,7 @@ internal class DashSdkInternalTransferSource( * [ExternalSendService.send] to the resolved OWN destination (that route's gating, pinning and * classification apply unchanged) or one of [ShieldedBalanceService]'s pinned self routes. * - * Routes (the 10 supported pairs of [internalTransferSupport]): + * Routes (the 11 supported pairs of [internalTransferSupport]): * - Core → Shielded: [ShieldedBalanceService.shieldFromWallet] (pinned) of `amount + pool fee` * ([shieldPoolFeeDuffs]), so the own shielded balance receives the confirmed amount (the * External Send's Core → Shielded convention). A lock that went out with the shield still @@ -139,8 +139,12 @@ internal class DashSdkInternalTransferSource( * - Shielded → Platform: [ShieldedBalanceService.unshieldToCredits] (pinned; own Platform address), * with the shielded Max fee retry. * - Platform → Shielded: [ShieldedBalanceService.shieldFromCredits] (pinned). - * - Identity → Platform: [ExternalSendService.send] to the confirmed wallet's own Platform address - * ([ShieldedBalanceService.ownPlatformAddressOf], no shielded flag needed); unavailable = Not sent. + * - Core → Platform, Identity → Platform: [ExternalSendService.send] to the confirmed wallet's own + * Platform address ([ShieldedBalanceService.ownPlatformAddressOf], no shielded flag needed); + * unavailable = Not sent. Core → Platform is the External Send's `fundFromAssetLockExternal`: + * the own address receives [amount] exactly, the fee is paid on top, the Platform-fee margin's + * remainder goes to another own Platform address, and an earlier lock still pending refuses it + * ([NotSentReason.PAYMENT_STILL_CONFIRMING]). * * Funds safety, in order, for every [transfer]: single-flight; positive amount; the pair matrix; * cutover committed and (for a shielded leg) the shielded flag, error-preserving; the wallet @@ -204,8 +208,9 @@ class InternalTransferServiceImpl internal constructor( /** * Every supported pair's figure depends only on the pair, so the External Send's per-pair * estimate applies ([ExternalSendService.estimateFee]): Core → Shielded the shield - * pool fee (on top), Shielded → * the flat single-note pool fee; Core → Identity, - * Platform → * and Identity → * are metered by Rust at execution, so null. + * pool fee (on top), Core → Platform the L1 lock reserve plus the Platform-fee margin (on + * top), Shielded → * the flat single-note pool fee; Core → Identity, Platform → * and + * Identity → * are metered by Rust at execution, so null. */ override suspend fun estimateFee(from: SendBalance, to: SendBalance): FeeEstimate? = if (internalTransferPairSupported(from, to)) externalSendService.estimateFee(from, to) else null diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt index 591e983b0a..b104641222 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt @@ -29,7 +29,7 @@ import org.junit.Test class InternalTransferModelsTest { private val supported = setOf( - CORE to SHIELDED, CORE to IDENTITY, + CORE to SHIELDED, CORE to PLATFORM, CORE to IDENTITY, SHIELDED to CORE, SHIELDED to PLATFORM, SHIELDED to IDENTITY, PLATFORM to CORE, PLATFORM to SHIELDED, PLATFORM to IDENTITY, IDENTITY to CORE, IDENTITY to PLATFORM @@ -48,11 +48,11 @@ class InternalTransferModelsTest { assertEquals("$from → $to", (from to to) in supported, internalTransferPairSupported(from, to)) } } - // Exactly the two pairs the SDK cannot do yet are disabled. + // Exactly the one pair the SDK cannot do yet is disabled. val notYet = SendBalance.entries.flatMap { f -> SendBalance.entries.map { f to it } } .filter { internalTransferSupport(it.first, it.second, true, true) == InternalTransferSupport.NOT_SUPPORTED_YET } .toSet() - assertEquals(setOf(CORE to PLATFORM, IDENTITY to SHIELDED), notYet) + assertEquals(setOf(IDENTITY to SHIELDED), notYet) } @Test @@ -63,8 +63,9 @@ class InternalTransferModelsTest { assertEquals(InternalTransferSupport.NO_IDENTITY, internalTransferSupport(IDENTITY, PLATFORM, true, false)) assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(IDENTITY, CORE, false, true)) // The matrix wins over the flags: an unsupported pair is "not yet", whatever they say. - assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, internalTransferSupport(CORE, PLATFORM, false, false)) - // Platform → Core needs neither the shielded feature nor an identity. + assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, internalTransferSupport(IDENTITY, SHIELDED, true, true)) + // Platform → Core and Core → Platform need neither the shielded feature nor an identity. + assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(CORE, PLATFORM, false, false)) assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(PLATFORM, CORE, false, false)) } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt index d773c70686..943a10de82 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -103,6 +103,7 @@ class InternalTransferServiceImplTest { var defaultBound: String? = WALLET_A var coreAddress: () -> String = { unadvertised } var platformAddress: String? = ownPlatform + var platformAddressThrows: Throwable? = null var feeCredits: Long? = POOL_FEE_CREDITS var shieldFromWalletResult: SdkWriteResult = SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) @@ -128,6 +129,7 @@ class InternalTransferServiceImplTest { val platformAddressReads = mutableListOf() override suspend fun ownPlatformAddress(walletIdHex: String): String? { platformAddressReads += walletIdHex + platformAddressThrows?.let { throw it } return platformAddress } override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = feeCredits @@ -236,6 +238,47 @@ class InternalTransferServiceImplTest { assertEquals(listOf(Send(IDENTITY, SendDestination.Platform(ownPlatform), amount, false, WALLET_A)), external.sends) } + @Test + fun `Core to Platform funds the own Platform address through the External Send, pinned, isMax passed through`() { + source.shielded = null // no shielded leg: never read + source.identity = Result.failure(IOException("unreadable")) // nor the identity record + assertEquals(ExternalSendResult.Sent("txid"), transfer(CORE, PLATFORM)) + assertEquals(ExternalSendResult.Sent("txid"), transfer(CORE, PLATFORM, isMax = true)) + assertEquals(listOf(WALLET_A, WALLET_A), source.platformAddressReads) + assertEquals( + listOf( + Send(CORE, SendDestination.Platform(ownPlatform), amount, false, WALLET_A), + Send(CORE, SendDestination.Platform(ownPlatform), amount, true, WALLET_A) + ), + external.sends + ) + // The External Send's own route (fundFromAssetLockExternal) does the write, not a self route. + assertEquals(emptyList(), source.writes) + } + + @Test + fun `Core to Platform with no own Platform address, or an unreadable one, fails closed`() { + source.platformAddress = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(CORE, PLATFORM)) + source.platformAddress = ownPlatform + source.platformAddressThrows = IOException("address store unreadable") + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(CORE, PLATFORM, isMax = true)) + assertNothingSubmitted() + } + + @Test + fun `Core to Platform passes the External Send's outcomes through unchanged`() { + for (outcome in listOf( + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), + ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), + ExternalSendResult.NotSent(NotSentReason.GENERIC), + ExternalSendResult.MayHaveGoneThrough + )) { + external.result = outcome + assertEquals(outcome, transfer(CORE, PLATFORM)) + } + } + @Test fun `identity destinations are the own identity`() { transfer(CORE, IDENTITY) @@ -301,7 +344,7 @@ class InternalTransferServiceImplTest { @Test fun `the matrix is enforced by the service`() { - for ((from, to) in listOf(CORE to PLATFORM, IDENTITY to SHIELDED, CORE to CORE)) { + for ((from, to) in listOf(IDENTITY to SHIELDED, CORE to CORE)) { assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(from, to)) } assertNothingSubmitted() @@ -447,8 +490,14 @@ class InternalTransferServiceImplTest { external.pairMax[CORE to PLATFORM] = Dash(5000) assertEquals(fee, service.estimateFee(SHIELDED, CORE)) assertEquals(Dash(5000), service.maxSendable(SHIELDED, CORE)) - assertNull(service.estimateFee(CORE, PLATFORM)) - assertNull(service.maxSendable(CORE, PLATFORM)) + // Core → Platform: the External Send's lock reserve + margin fee and its Max. + assertEquals(fee, service.estimateFee(CORE, PLATFORM)) + assertEquals(Dash(5000), service.maxSendable(CORE, PLATFORM)) + // An unsupported pair never asks the External Send. + external.pairFees[IDENTITY to SHIELDED] = fee + external.pairMax[IDENTITY to SHIELDED] = Dash(5000) + assertNull(service.estimateFee(IDENTITY, SHIELDED)) + assertNull(service.maxSendable(IDENTITY, SHIELDED)) assertNull(service.estimateFee(PLATFORM, SHIELDED)) // Platform → Core asks the External Send's own figures (null today: metered by Rust). assertNull(service.estimateFee(PLATFORM, CORE)) diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index 78e86dee41..c7de9e4798 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -185,11 +185,36 @@ class InternalTransferViewModelTest { @Test fun `a pick that leads to an unsupported pair is refused`() { + val viewModel = buildViewModel() + // Identity → Shielded is not available yet. + viewModel.onShowPicker(InternalTransferPicker.FROM) + assertFalse(viewModel.state.pickable(InternalTransferPicker.FROM, IDENTITY)) + viewModel.onBalancePicked(IDENTITY) + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + } + + @Test + fun `Core to Platform is pickable, offers Max and confirms with the fee on top`() { + service.balances.getValue(CORE).value = twoDash + service.max[CORE to PLATFORM] = oneDash + service.fee = FeeEstimate(Dash(1000), exact = false) val viewModel = buildViewModel() viewModel.onShowPicker(InternalTransferPicker.TO) - assertFalse(viewModel.state.pickable(InternalTransferPicker.TO, PLATFORM)) + assertTrue(viewModel.state.pickable(InternalTransferPicker.TO, PLATFORM)) viewModel.onBalancePicked(PLATFORM) - assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + assertEquals(CORE to PLATFORM, viewModel.state.from to viewModel.state.to) + assertEquals(InternalTransferSupport.SUPPORTED, viewModel.state.support) + + viewModel.onMaxClick() + assertTrue(viewModel.state.isMax) + assertEquals(oneDash, viewModel.state.amount) + assertTrue(viewModel.state.canContinue) + viewModel.onContinue() + val confirm = requireNotNull(viewModel.state.confirm) + assertEquals(InternalTransferRequest(CORE, PLATFORM, oneDash, true, WALLET_A), confirm.request) + // The own Platform address receives the amount; the lock fee is paid on top (not exact). + assertEquals(oneDash + Dash(1000), confirm.total) + assertFalse(requireNotNull(confirm.fee).exact) } @Test From b0fb1af09e71043f5b76612c0af7315a4ae2b40c Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 13:40:56 -0800 Subject: [PATCH 14/17] feat(payments): allow Identity -> Shielded as an Internal Transfer External Send supports Identity -> Shielded (identityShieldTo, Type 21), so the Internal pair matrix now allows every pair of two different balances; NOT_SUPPORTED_YET and internalTransferPairSupported are gone. The Shielded-destination routing used to send every non-Core source to the Platform-credits self-shield. Identity now delegates to External Send with the wallet's own default shielded address, read by the new ShieldedBalanceService.ownShieldedAddressOf, which is pinned to the confirmed wallet and fails closed (Not sent, nothing called). Platform -> Shielded keeps its self route. As in External Send, an identity source has no fee estimate and no Max. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/InternalTransferModels.kt | 20 ++---- .../sdk/InternalTransferServiceImpl.kt | 37 +++++++--- .../platform/sdk/ShieldedBalanceService.kt | 9 +++ .../sdk/ShieldedBalanceServiceImpl.kt | 15 ++++ .../sdk/InternalTransferModelsTest.kt | 27 ++----- .../sdk/InternalTransferServiceImplTest.kt | 70 +++++++++++++++++-- .../sdk/ShieldedBalanceServiceTest.kt | 20 ++++++ .../internal/InternalTransferViewModelTest.kt | 44 ++++++++---- 8 files changed, 180 insertions(+), 62 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt index d7e9e5e751..d5a8daebee 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt @@ -27,9 +27,6 @@ enum class InternalTransferSupport { /** From and To are the same balance: never allowed. */ SAME_BALANCE, - /** The SDK (or the wallet) cannot do this pair yet: shown disabled, "not available yet". */ - NOT_SUPPORTED_YET, - /** One side is the Shielded balance and the shielded feature is off (or unreadable). */ SHIELDED_OFF, @@ -39,14 +36,15 @@ enum class InternalTransferSupport { /** * The one pair matrix of the internal transfer, enforced by the UI AND by - * [InternalTransferService.transfer]: + * [InternalTransferService.transfer]: every pair of two different own balances is supported, + * gated only by the shielded feature and the user's identity. * * | From \ To | Core | Shielded | Platform | Identity | * |---|---|---|---|---| * | Core | — | yes | yes (1) | yes | * | Shielded | yes | — | yes | yes | * | Platform | yes (2) | yes | — | yes | - * | Identity | yes | no (3) | yes | — | + * | Identity | yes | yes (3) | yes | — | * * 1. The External Send's Core → Platform (`fundFromAssetLockExternal`) to the wallet's own * Platform address: the fee (L1 lock reserve plus the Platform-fee margin, whose unused @@ -54,7 +52,8 @@ enum class InternalTransferSupport { * resumed by the External Send's pending-funding sweep. * 2. The External Send's partial Platform → Core withdrawal (`withdrawCredits` with the * inputs the wallet selects) to the wallet's own unadvertised Core address. - * 3. `shieldedShieldFromIdentity` (Type 21) is not bound in the wallet yet. + * 3. The External Send's Identity → Shielded (`shieldFromIdentityToAddress`, Type 21) to the + * wallet's own default shielded address; the fee is metered by Rust at execution. * * [shieldedEnabled] and [hasIdentity] are the error-preserving reads: unknown is false. */ @@ -65,7 +64,6 @@ fun internalTransferSupport( hasIdentity: Boolean ): InternalTransferSupport { if (from == to) return InternalTransferSupport.SAME_BALANCE - if (!internalTransferPairSupported(from, to)) return InternalTransferSupport.NOT_SUPPORTED_YET if ((from == SendBalance.SHIELDED || to == SendBalance.SHIELDED) && !shieldedEnabled) { return InternalTransferSupport.SHIELDED_OFF } @@ -75,14 +73,6 @@ fun internalTransferSupport( return InternalTransferSupport.SUPPORTED } -/** The bare matrix of [internalTransferSupport]: whether the wallet can move [from] → [to] at all. */ -fun internalTransferPairSupported(from: SendBalance, to: SendBalance): Boolean = when (from) { - SendBalance.CORE -> to != SendBalance.CORE - SendBalance.SHIELDED -> to != SendBalance.SHIELDED - SendBalance.PLATFORM -> to != SendBalance.PLATFORM - SendBalance.IDENTITY -> to == SendBalance.CORE || to == SendBalance.PLATFORM -} - /** An ordered pair of own balances; [from] != [to] always. [toString] carries no amounts or ids. */ data class InternalTransferPair(val from: SendBalance, val to: SendBalance) { init { diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index e40cf1f888..afc11a5dbb 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -73,6 +73,13 @@ internal interface InternalTransferSource { */ suspend fun ownPlatformAddress(walletIdHex: String): String? + /** + * [ShieldedBalanceService.ownShieldedAddressOf]: the default shielded (Orchard) address of + * [walletIdHex], pinned to that wallet, or null (not ready, another wallet bound, no + * shielded sub-wallet, or the derivation failed). + */ + suspend fun ownShieldedAddress(walletIdHex: String): String? + suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult @@ -106,6 +113,9 @@ internal class DashSdkInternalTransferSource( override suspend fun ownPlatformAddress(walletIdHex: String): String? = shieldedBalanceService.ownPlatformAddressOf(walletIdHex) + override suspend fun ownShieldedAddress(walletIdHex: String): String? = + shieldedBalanceService.ownShieldedAddressOf(walletIdHex) + override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = shieldedBalanceService.estimateShieldedFeeCredits(kind) @@ -124,7 +134,7 @@ internal class DashSdkInternalTransferSource( * [ExternalSendService.send] to the resolved OWN destination (that route's gating, pinning and * classification apply unchanged) or one of [ShieldedBalanceService]'s pinned self routes. * - * Routes (the 11 supported pairs of [internalTransferSupport]): + * Routes (all 12 pairs of [internalTransferSupport]): * - Core → Shielded: [ShieldedBalanceService.shieldFromWallet] (pinned) of `amount + pool fee` * ([shieldPoolFeeDuffs]), so the own shielded balance receives the confirmed amount (the * External Send's Core → Shielded convention). A lock that went out with the shield still @@ -139,6 +149,9 @@ internal class DashSdkInternalTransferSource( * - Shielded → Platform: [ShieldedBalanceService.unshieldToCredits] (pinned; own Platform address), * with the shielded Max fee retry. * - Platform → Shielded: [ShieldedBalanceService.shieldFromCredits] (pinned). + * - Identity → Shielded: [ExternalSendService.send] to the confirmed wallet's own default + * shielded address ([ShieldedBalanceService.ownShieldedAddressOf], pinned to the wallet); + * unavailable = Not sent. The External Send's Type 21 (`shieldFromIdentityToAddress`). * - Core → Platform, Identity → Platform: [ExternalSendService.send] to the confirmed wallet's own * Platform address ([ShieldedBalanceService.ownPlatformAddressOf], no shielded flag needed); * unavailable = Not sent. Core → Platform is the External Send's `fundFromAssetLockExternal`: @@ -210,14 +223,14 @@ class InternalTransferServiceImpl internal constructor( * estimate applies ([ExternalSendService.estimateFee]): Core → Shielded the shield * pool fee (on top), Core → Platform the L1 lock reserve plus the Platform-fee margin (on * top), Shielded → * the flat single-note pool fee; Core → Identity, Platform → * and - * Identity → * are metered by Rust at execution, so null. + * Identity → * (Identity → Shielded included) are metered by Rust at execution, so null. */ override suspend fun estimateFee(from: SendBalance, to: SendBalance): FeeEstimate? = - if (internalTransferPairSupported(from, to)) externalSendService.estimateFee(from, to) else null + if (from != to) externalSendService.estimateFee(from, to) else null - /** [ExternalSendService.maxSendable] for a supported pair (null for metered pairs). */ + /** [ExternalSendService.maxSendable] for two different balances (null for metered pairs). */ override suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? = - if (internalTransferPairSupported(from, to)) externalSendService.maxSendable(from, to) else null + if (from != to) externalSendService.maxSendable(from, to) else null // ── Transfer ────────────────────────────────────────────────────── @@ -255,9 +268,7 @@ class InternalTransferServiceImpl internal constructor( ): ExternalSendResult { val pair = "$from → $to" if (!amount.isPositive) return notSent(pair, NotSentReason.GENERIC, "non-positive amount") - if (from == to || !internalTransferPairSupported(from, to)) { - return notSent(pair, NotSentReason.NOT_SUPPORTED, "pair not supported") - } + if (from == to) return notSent(pair, NotSentReason.NOT_SUPPORTED, "same balance") // Engine ownership / flags, error-preserving. val committed = readOrNull("cutover state") { source.cutoverCommittedOrThrow() } @@ -313,13 +324,21 @@ class InternalTransferServiceImpl internal constructor( } SendBalance.SHIELDED -> when (from) { SendBalance.CORE -> shieldFromOwnCore(pair, walletIdHex, amount) - else -> mapWrite( + SendBalance.PLATFORM -> mapWrite( pair, submitUnderWipeBarrier(pair, walletIdHex) { mark -> mark.submitting() source.shieldFromCredits(amount, walletIdHex) } ) + SendBalance.IDENTITY -> { + // Type 21 has no self-shield form: the External Send's to-address route, to + // the confirmed wallet's own default shielded address. + val address = readOrNull("own shielded address") { source.ownShieldedAddress(walletIdHex) } + ?: return notSent(pair, NotSentReason.GENERIC, "own shielded address unavailable") + delegate(pair, walletIdHex, from, SendDestination.Shielded(address), amount, isMax) + } + SendBalance.SHIELDED -> notSent(pair, NotSentReason.NOT_SUPPORTED, "same balance") } } } 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 2476f01882..2d6999ea9d 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -384,6 +384,15 @@ interface ShieldedBalanceService { */ suspend fun ownPlatformAddressOf(walletIdHex: String): String? + /** + * The default shielded (Orchard) receive address of the SDK wallet [walletIdHex] — the same + * address [shieldedReceiveAddress] shows — pinned to that wallet: null unless the shielded + * runtime is ready AND bound to [walletIdHex], and null when [walletIdHex] is malformed, the + * wallet has no shielded sub-wallet or the derivation fails (fail closed). Never throws + * (except cancellation); the address is never logged. + */ + suspend fun ownShieldedAddressOf(walletIdHex: String): 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 e9b8756864..8c283955f6 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -2160,6 +2160,21 @@ class ShieldedBalanceServiceImpl internal constructor( } } + override suspend fun ownShieldedAddressOf(walletIdHex: String): String? { + val walletId = walletIdFromHex(walletIdHex) ?: return null + if (!ensureShieldedReady()) return null + // Pinned: the runtime must be bound to the wallet the caller confirmed with. + if (!walletIdHex.equals(readyWalletIdHex.value, ignoreCase = true)) return null + return try { + source.shieldedDefaultAddress(walletId) + ?.let { raw -> encodeOrchardAddress(raw, displayHrp()) } + } catch (t: Throwable) { + if (t is CancellationException) throw t + log.warn("failed to derive the wallet's own shielded address", t) + null + } + } + override suspend fun ownPlatformAddressOf(walletIdHex: String): String? { val walletId = walletIdFromHex(walletIdHex) ?: return null return try { diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt index b104641222..9de71b557f 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt @@ -28,31 +28,15 @@ import org.junit.Test class InternalTransferModelsTest { - private val supported = setOf( - CORE to SHIELDED, CORE to PLATFORM, CORE to IDENTITY, - SHIELDED to CORE, SHIELDED to PLATFORM, SHIELDED to IDENTITY, - PLATFORM to CORE, PLATFORM to SHIELDED, PLATFORM to IDENTITY, - IDENTITY to CORE, IDENTITY to PLATFORM - ) - @Test - fun `the full 4x4 matrix`() { + fun `the full 4x4 matrix - every pair of two different balances is supported`() { for (from in SendBalance.entries) { for (to in SendBalance.entries) { - val expected = when { - from == to -> InternalTransferSupport.SAME_BALANCE - (from to to) in supported -> InternalTransferSupport.SUPPORTED - else -> InternalTransferSupport.NOT_SUPPORTED_YET - } + val expected = if (from == to) InternalTransferSupport.SAME_BALANCE else InternalTransferSupport.SUPPORTED assertEquals("$from → $to", expected, internalTransferSupport(from, to, true, true)) - assertEquals("$from → $to", (from to to) in supported, internalTransferPairSupported(from, to)) } } - // Exactly the one pair the SDK cannot do yet is disabled. - val notYet = SendBalance.entries.flatMap { f -> SendBalance.entries.map { f to it } } - .filter { internalTransferSupport(it.first, it.second, true, true) == InternalTransferSupport.NOT_SUPPORTED_YET } - .toSet() - assertEquals(setOf(IDENTITY to SHIELDED), notYet) + assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(IDENTITY, SHIELDED, true, true)) } @Test @@ -62,8 +46,9 @@ class InternalTransferModelsTest { assertEquals(InternalTransferSupport.NO_IDENTITY, internalTransferSupport(CORE, IDENTITY, true, false)) assertEquals(InternalTransferSupport.NO_IDENTITY, internalTransferSupport(IDENTITY, PLATFORM, true, false)) assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(IDENTITY, CORE, false, true)) - // The matrix wins over the flags: an unsupported pair is "not yet", whatever they say. - assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, internalTransferSupport(IDENTITY, SHIELDED, true, true)) + // Identity → Shielded needs both. + assertEquals(InternalTransferSupport.SHIELDED_OFF, internalTransferSupport(IDENTITY, SHIELDED, false, true)) + assertEquals(InternalTransferSupport.NO_IDENTITY, internalTransferSupport(IDENTITY, SHIELDED, true, false)) // Platform → Core and Core → Platform need neither the shielded feature nor an identity. assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(CORE, PLATFORM, false, false)) assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(PLATFORM, CORE, false, false)) diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt index 943a10de82..8d3af087c2 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -54,6 +54,7 @@ class InternalTransferServiceImplTest { private val network = AddressNetwork.DASH_TESTNET private val unadvertised = Base58.encodeChecked(network.addressHeader, ByteArray(20) { (it + 1).toByte() }) private val ownPlatform = "tdash1k-own-platform" + private val ownShielded = "tdash1z-own-shielded" private val ownIdentity = Base58.encode(ByteArray(32) { (255 - it).toByte() }) private val amount = Dash.COIN @@ -132,6 +133,14 @@ class InternalTransferServiceImplTest { platformAddressThrows?.let { throw it } return platformAddress } + var shieldedAddress: String? = ownShielded + var shieldedAddressThrows: Throwable? = null + val shieldedAddressReads = mutableListOf() + override suspend fun ownShieldedAddress(walletIdHex: String): String? { + shieldedAddressReads += walletIdHex + shieldedAddressThrows?.let { throw it } + return shieldedAddress + } override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = feeCredits override suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult { @@ -291,6 +300,48 @@ class InternalTransferServiceImplTest { assertEquals(emptyList(), source.writes) } + @Test + fun `identity to Shielded pays the own shielded address through the External Send, pinned`() { + assertEquals(ExternalSendResult.Sent("txid"), transfer(IDENTITY, SHIELDED)) + assertEquals(listOf(WALLET_A), source.shieldedAddressReads) + assertEquals(listOf(Send(IDENTITY, SendDestination.Shielded(ownShielded), amount, false, WALLET_A)), external.sends) + // Never the Platform-credits self-shield. + assertEquals(emptyList(), source.writes) + } + + @Test + fun `identity to Shielded with no own shielded address, or an unreadable one, fails closed`() { + source.shieldedAddress = null + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) + source.shieldedAddress = ownShielded + source.shieldedAddressThrows = IOException("runtime not ready") + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) + assertNothingSubmitted() + } + + @Test + fun `identity to Shielded passes the External Send's outcomes through unchanged`() { + for (outcome in listOf( + ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + ExternalSendResult.MayHaveGoneThrough + )) { + external.result = outcome + assertEquals(outcome, transfer(IDENTITY, SHIELDED)) + } + } + + @Test + fun `identity to Shielded needs the shielded flag and an identity`() { + source.shielded = false + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) + source.shielded = true + source.identity = Result.success(null) + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) + assertEquals(emptyList(), source.shieldedAddressReads) + assertNothingSubmitted() + } + // ── self routes ────────────────────────────────────────────────────────── @Test @@ -328,6 +379,8 @@ class InternalTransferServiceImplTest { source.writes ) assertEquals(emptyList(), external.sends) + // The shielded address is the External Send's concern only; the self route never reads it. + assertEquals(emptyList(), source.shieldedAddressReads) } @Test @@ -344,7 +397,7 @@ class InternalTransferServiceImplTest { @Test fun `the matrix is enforced by the service`() { - for ((from, to) in listOf(IDENTITY to SHIELDED, CORE to CORE)) { + for ((from, to) in SendBalance.entries.map { it to it }) { assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(from, to)) } assertNothingSubmitted() @@ -482,7 +535,7 @@ class InternalTransferServiceImplTest { // ── fee, max and reads ─────────────────────────────────────────────────── @Test - fun `fee and max come from the per-pair estimate, null for unsupported pairs`() = runBlocking { + fun `fee and max come from the per-pair estimate, null for the same balance`() = runBlocking { val fee = FeeEstimate(Dash(1000), exact = false) external.pairFees[SHIELDED to CORE] = fee external.pairMax[SHIELDED to CORE] = Dash(5000) @@ -493,11 +546,18 @@ class InternalTransferServiceImplTest { // Core → Platform: the External Send's lock reserve + margin fee and its Max. assertEquals(fee, service.estimateFee(CORE, PLATFORM)) assertEquals(Dash(5000), service.maxSendable(CORE, PLATFORM)) - // An unsupported pair never asks the External Send. - external.pairFees[IDENTITY to SHIELDED] = fee - external.pairMax[IDENTITY to SHIELDED] = Dash(5000) + // Identity → Shielded: the External Send's figures (null today: metered by Rust). assertNull(service.estimateFee(IDENTITY, SHIELDED)) assertNull(service.maxSendable(IDENTITY, SHIELDED)) + external.pairFees[IDENTITY to SHIELDED] = fee + external.pairMax[IDENTITY to SHIELDED] = Dash(5000) + assertEquals(fee, service.estimateFee(IDENTITY, SHIELDED)) + assertEquals(Dash(5000), service.maxSendable(IDENTITY, SHIELDED)) + // The same balance never asks the External Send. + external.pairFees[CORE to CORE] = fee + external.pairMax[CORE to CORE] = Dash(5000) + assertNull(service.estimateFee(CORE, CORE)) + assertNull(service.maxSendable(CORE, CORE)) assertNull(service.estimateFee(PLATFORM, SHIELDED)) // Platform → Core asks the External Send's own figures (null today: metered by Rust). assertNull(service.estimateFee(PLATFORM, CORE)) 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 39800691e1..c5c03a95b1 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -1493,6 +1493,26 @@ class ShieldedBalanceServiceTest { assertNull(service(source).shieldedReceiveAddress()) } + @Test + fun ownShieldedAddressOf_isTheReceiveAddress_pinnedToTheBoundWallet() = runBlocking { + val source = readySource().apply { defaultAddress = recipientRaw43 } + val service = service(source) + val address = service.ownShieldedAddressOf(walletIdHex) + assertEquals(service.shieldedReceiveAddress(), address) + assertArrayEquals(recipientRaw43, decodeOrchardAddress(checkNotNull(address), hrp)) + assertEquals(address, service.ownShieldedAddressOf(walletIdHex.uppercase())) + // Another wallet, or a malformed id: null, never this wallet's address. + assertNull(service.ownShieldedAddressOf("cd".repeat(32))) + assertNull(service.ownShieldedAddressOf("not-hex")) + } + + @Test + fun ownShieldedAddressOf_nullWhenNotReadyOrFlagOff() = runBlocking { + assertNull(service(FakeSource(hasSupport = true, boundWalletId = { null })).ownShieldedAddressOf(walletIdHex)) + val source = readySource().apply { defaultAddress = recipientRaw43 } + assertNull(service(source, enabled = false).ownShieldedAddressOf(walletIdHex)) + } + @Test fun platformReceiveAddress_isTheSourcesUnusedPlatformAddress() = runBlocking { val source = readySource().apply { diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index c7de9e4798..cd6ee33cb2 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -185,12 +185,35 @@ class InternalTransferViewModelTest { @Test fun `a pick that leads to an unsupported pair is refused`() { + service.shielded.value = false val viewModel = buildViewModel() - // Identity → Shielded is not available yet. + assertEquals(CORE to IDENTITY, viewModel.state.from to viewModel.state.to) + // The shielded feature is off: Shielded is shown but cannot be picked. + viewModel.onShowPicker(InternalTransferPicker.TO) + assertFalse(viewModel.state.pickable(InternalTransferPicker.TO, SHIELDED)) + viewModel.onBalancePicked(SHIELDED) + assertEquals(CORE to IDENTITY, viewModel.state.from to viewModel.state.to) + } + + @Test + fun `Identity is pickable as From with To Shielded, with no Max and a metered fee`() { + service.balances.getValue(IDENTITY).value = twoDash + val viewModel = buildViewModel() + assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) viewModel.onShowPicker(InternalTransferPicker.FROM) - assertFalse(viewModel.state.pickable(InternalTransferPicker.FROM, IDENTITY)) + assertTrue(viewModel.state.pickable(InternalTransferPicker.FROM, IDENTITY)) viewModel.onBalancePicked(IDENTITY) - assertEquals(CORE to SHIELDED, viewModel.state.from to viewModel.state.to) + assertEquals(IDENTITY to SHIELDED, viewModel.state.from to viewModel.state.to) + assertEquals(InternalTransferSupport.SUPPORTED, viewModel.state.support) + // As in the External Send: no pre-send Max or fee for an identity source. + assertNull(viewModel.state.maxSendable) + viewModel.type("1") + assertTrue(viewModel.state.canContinue) + viewModel.onContinue() + val confirm = requireNotNull(viewModel.state.confirm) + assertEquals(InternalTransferRequest(IDENTITY, SHIELDED, oneDash, false, WALLET_A), confirm.request) + assertFalse(confirm.feeLoading) + assertNull(confirm.fee) } @Test @@ -338,16 +361,13 @@ class InternalTransferViewModelTest { } @Test - fun `an unsupported pair (reached by a swap) blocks Continue`() { - service.balances.getValue(IDENTITY).value = twoDash + fun `an unsupported pair (a chosen Shielded pair with the flag unknown) blocks Continue`() { + service.balances.getValue(SHIELDED).value = twoDash val viewModel = buildViewModel() - viewModel.onShowPicker(InternalTransferPicker.FROM) - viewModel.onBalancePicked(SHIELDED) // Shielded → Core - viewModel.onShowPicker(InternalTransferPicker.TO) - viewModel.onBalancePicked(IDENTITY) // Shielded → Identity - viewModel.onSwap() - assertEquals(IDENTITY to SHIELDED, viewModel.state.from to viewModel.state.to) - assertEquals(InternalTransferSupport.NOT_SUPPORTED_YET, viewModel.state.support) + viewModel.onSwap() // Shielded → Core, chosen + service.shielded.value = null + assertEquals(SHIELDED to CORE, viewModel.state.from to viewModel.state.to) + assertEquals(InternalTransferSupport.SHIELDED_OFF, viewModel.state.support) viewModel.type("1") assertFalse(viewModel.state.canContinue) viewModel.onContinue() From 307081540f1a8b75da71d5c549046fe972736f8c Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 16:10:30 -0800 Subject: [PATCH 15/17] fix(payments): Internal Identity -> Shielded uses the identity self-shield The SDK refuses shieldedShieldFromIdentityToRecipient when the recipient belongs to the wallet's own shielded account ("use the self-shield entry point"), so the External Send delegate added in the previous commit was Not sent on a device. Wrap shieldedShieldFromIdentity (Type 21, no recipient) as ShieldedBalanceService.shieldFromIdentity, mirroring shieldFromIdentityToAddress through runShieldedWrite, and route Internal Identity -> Shielded to it as a self route under the wipe barrier, with the own identity checked as SDK-managed first. ownShieldedAddressOf is removed. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/InternalTransferModels.kt | 6 +- .../sdk/InternalTransferServiceImpl.kt | 76 +++++++--- .../platform/sdk/ShieldedBalanceService.kt | 27 ++-- .../sdk/ShieldedBalanceServiceImpl.kt | 50 +++++-- .../sdk/InternalTransferServiceImplTest.kt | 134 ++++++++++-------- .../sdk/ShieldedBalanceServiceTest.kt | 94 +++++++++--- 6 files changed, 262 insertions(+), 125 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt index d5a8daebee..1c9ba4d8f6 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt @@ -52,8 +52,10 @@ enum class InternalTransferSupport { * resumed by the External Send's pending-funding sweep. * 2. The External Send's partial Platform → Core withdrawal (`withdrawCredits` with the * inputs the wallet selects) to the wallet's own unadvertised Core address. - * 3. The External Send's Identity → Shielded (`shieldFromIdentityToAddress`, Type 21) to the - * wallet's own default shielded address; the fee is metered by Rust at execution. + * 3. The Type 21 self-shield (`shieldedShieldFromIdentity`, no recipient: Rust targets the + * wallet's own default shielded address) from the user's own identity, not the External + * Send's to-recipient Type 21, which refuses an own address; the fee is metered by Rust at + * execution. * * [shieldedEnabled] and [hasIdentity] are the error-preserving reads: unknown is false. */ diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index afc11a5dbb..9f65b6a984 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -74,16 +74,18 @@ internal interface InternalTransferSource { suspend fun ownPlatformAddress(walletIdHex: String): String? /** - * [ShieldedBalanceService.ownShieldedAddressOf]: the default shielded (Orchard) address of - * [walletIdHex], pinned to that wallet, or null (not ready, another wallet bound, no - * shielded sub-wallet, or the derivation failed). + * The identity ids (32 bytes each) the SDK wallet [walletIdHex] manages (not watched-only): + * the ones it can sign for. Throws when unreadable (the wallet not loaded included). */ - suspend fun ownShieldedAddress(walletIdHex: String): String? + suspend fun managedIdentityIds(walletIdHex: String): List suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? suspend fun shieldFromWallet(amount: Dash, walletIdHex: String): SdkWriteResult suspend fun shieldFromCredits(amount: Dash, walletIdHex: String): SdkWriteResult + + /** [ShieldedBalanceService.shieldFromIdentity]: the Type 21 self-shield from [identityId]. */ + suspend fun shieldFromIdentity(identityId: ByteArray, amount: Dash, walletIdHex: String): SdkWriteResult suspend fun unshieldToCredits(amount: Dash, walletIdHex: String): SdkWriteResult } @@ -113,8 +115,13 @@ internal class DashSdkInternalTransferSource( override suspend fun ownPlatformAddress(walletIdHex: String): String? = shieldedBalanceService.ownPlatformAddressOf(walletIdHex) - override suspend fun ownShieldedAddress(walletIdHex: String): String? = - shieldedBalanceService.ownShieldedAddressOf(walletIdHex) + override suspend fun managedIdentityIds(walletIdHex: String): List { + // The PINNED wallet, never "whichever is current" (as the External Send's source). + val wallet = checkNotNull(sdkService.startedWalletManager().wallets.value[walletIdHex]) { + "SDK wallet not loaded" + } + return wallet.inMemoryIdentityStates().filter { !it.watched }.map { it.identityId } + } override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = shieldedBalanceService.estimateShieldedFeeCredits(kind) @@ -125,6 +132,9 @@ internal class DashSdkInternalTransferSource( override suspend fun shieldFromCredits(amount: Dash, walletIdHex: String) = shieldedBalanceService.shieldFromCredits(amount, walletIdHex) + override suspend fun shieldFromIdentity(identityId: ByteArray, amount: Dash, walletIdHex: String) = + shieldedBalanceService.shieldFromIdentity(identityId, amount, walletIdHex) + override suspend fun unshieldToCredits(amount: Dash, walletIdHex: String) = shieldedBalanceService.unshieldToCredits(amount, walletIdHex) } @@ -149,9 +159,11 @@ internal class DashSdkInternalTransferSource( * - Shielded → Platform: [ShieldedBalanceService.unshieldToCredits] (pinned; own Platform address), * with the shielded Max fee retry. * - Platform → Shielded: [ShieldedBalanceService.shieldFromCredits] (pinned). - * - Identity → Shielded: [ExternalSendService.send] to the confirmed wallet's own default - * shielded address ([ShieldedBalanceService.ownShieldedAddressOf], pinned to the wallet); - * unavailable = Not sent. The External Send's Type 21 (`shieldFromIdentityToAddress`). + * - Identity → Shielded: [ShieldedBalanceService.shieldFromIdentity] (pinned), the Type 21 + * self-shield (`shieldedShieldFromIdentity`) from the user's own identity, which must be one + * the confirmed wallet manages; the SDK refuses the wallet's own shielded address on the + * External Send's to-recipient Type 21. The fee is metered by Rust at execution (no estimate, + * no Max). * - Core → Platform, Identity → Platform: [ExternalSendService.send] to the confirmed wallet's own * Platform address ([ShieldedBalanceService.ownPlatformAddressOf], no shielded flag needed); * unavailable = Not sent. Core → Platform is the External Send's `fundFromAssetLockExternal`: @@ -167,7 +179,7 @@ internal class DashSdkInternalTransferSource( * * Reset Wallet: the delegated routes hold the wallet-wipe barrier inside * [ExternalSendService.send]; the self routes this class submits itself (Core → Shielded, - * Shielded → Platform, Platform → Shielded) hold it here ([submitUnderWipeBarrier]), with the + * Shielded → Platform, Platform → Shielded, Identity → Shielded) hold it here ([submitUnderWipeBarrier]), with the * final wallet re-check inside the hold. */ @Singleton @@ -223,14 +235,18 @@ class InternalTransferServiceImpl internal constructor( * estimate applies ([ExternalSendService.estimateFee]): Core → Shielded the shield * pool fee (on top), Core → Platform the L1 lock reserve plus the Platform-fee margin (on * top), Shielded → * the flat single-note pool fee; Core → Identity, Platform → * and - * Identity → * (Identity → Shielded included) are metered by Rust at execution, so null. + * Identity → * are metered by Rust at execution, so null. Identity → Shielded is this + * class's own self route (no External Send pair), so null here, like every identity source. */ override suspend fun estimateFee(from: SendBalance, to: SendBalance): FeeEstimate? = - if (from != to) externalSendService.estimateFee(from, to) else null + if (from != to && !isIdentitySelfShield(from, to)) externalSendService.estimateFee(from, to) else null /** [ExternalSendService.maxSendable] for two different balances (null for metered pairs). */ override suspend fun maxSendable(from: SendBalance, to: SendBalance): Dash? = - if (from != to) externalSendService.maxSendable(from, to) else null + if (from != to && !isIdentitySelfShield(from, to)) externalSendService.maxSendable(from, to) else null + + private fun isIdentitySelfShield(from: SendBalance, to: SendBalance): Boolean = + from == SendBalance.IDENTITY && to == SendBalance.SHIELDED // ── Transfer ────────────────────────────────────────────────────── @@ -331,13 +347,7 @@ class InternalTransferServiceImpl internal constructor( source.shieldFromCredits(amount, walletIdHex) } ) - SendBalance.IDENTITY -> { - // Type 21 has no self-shield form: the External Send's to-address route, to - // the confirmed wallet's own default shielded address. - val address = readOrNull("own shielded address") { source.ownShieldedAddress(walletIdHex) } - ?: return notSent(pair, NotSentReason.GENERIC, "own shielded address unavailable") - delegate(pair, walletIdHex, from, SendDestination.Shielded(address), amount, isMax) - } + SendBalance.IDENTITY -> shieldFromOwnIdentity(pair, walletIdHex, ownIdentityId, amount) SendBalance.SHIELDED -> notSent(pair, NotSentReason.NOT_SUPPORTED, "same balance") } } @@ -383,6 +393,32 @@ class InternalTransferServiceImpl internal constructor( } } + /** + * The Type 21 self-shield from the user's own identity: the SDK refuses the wallet's own + * shielded address on the to-recipient Type 21, so this is not the External Send's route. As + * that route, the identity must be one the confirmed wallet manages (it signs with its keys). + */ + private suspend fun shieldFromOwnIdentity( + pair: String, + walletIdHex: String, + ownIdentityId: String?, + amount: Dash + ): ExternalSendResult { + val identityId = ownIdentityId?.let(::decodeIdentityId) + ?: return notSent(pair, NotSentReason.GENERIC, "no own identity") + val managed = readOrNull("managed identities") { + source.managedIdentityIds(walletIdHex).any { it.contentEquals(identityId) } + } ?: return notSent(pair, NotSentReason.GENERIC, "managed identities unreadable") + if (!managed) return notSent(pair, NotSentReason.NOT_SUPPORTED, "own identity not managed by the SDK wallet") + return mapWrite( + pair, + submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + source.shieldFromIdentity(identityId, amount, walletIdHex) + } + ) + } + /** Unshield to the own Platform address; a Max retries once with the reported fee deficit. */ private suspend fun unshieldToOwnPlatform( pair: String, 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 2d6999ea9d..d3cb797194 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -384,15 +384,6 @@ interface ShieldedBalanceService { */ suspend fun ownPlatformAddressOf(walletIdHex: String): String? - /** - * The default shielded (Orchard) receive address of the SDK wallet [walletIdHex] — the same - * address [shieldedReceiveAddress] shows — pinned to that wallet: null unless the shielded - * runtime is ready AND bound to [walletIdHex], and null when [walletIdHex] is malformed, the - * wallet has no shielded sub-wallet or the derivation fails (fail closed). Never throws - * (except cancellation); the address is never logged. - */ - suspend fun ownShieldedAddressOf(walletIdHex: String): String? - /** * Shield [amount] from the wallet's own Platform credit balance into * its own shielded pool (Type 15). Self-shield only — Rust always @@ -654,6 +645,24 @@ interface ShieldedBalanceService { expectedWalletIdHex: String ): SdkWriteResult + /** + * Shield [amount] credits from the wallet's managed identity [identityId] (32 bytes) into + * the wallet's OWN shielded pool (Type 21 self-shield, `shieldedShieldFromIdentity`: Rust + * always targets the default Orchard address of account 0, so there is no recipient — the + * SDK refuses this wallet's own address on [shieldFromIdentityToAddress]). Otherwise as + * [shieldFromIdentityToAddress]: the identity pays [amount] plus the metered transition fee + * and the shielded compute fee, signed with the identity's transfer key by the SDK's + * Keystore signer; the ready runtime must be bound to [expectedWalletIdHex]; an earlier + * identity shield that is still unresolved is a [SdkWriteResult.NotBroadcast] (the SDK built + * nothing); a spend that may have been submitted is [SdkWriteResult.Ambiguous] (never + * retried). Blocks for the ~30s proof; the note arrives on the next shielded sync pass. + */ + suspend fun shieldFromIdentity( + identityId: ByteArray, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + /** * [shieldFromWallet] to an EXTERNAL Orchard recipient [toShieldedAddress]: one fresh * L1 asset lock + Type 18 paying that address. 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 8c283955f6..3fe09d4bb3 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -725,6 +725,16 @@ interface ShieldedSource { amountCredits: Long ): Unit = throw UnsupportedOperationException("identity shield to a recipient not supported by this source") + /** + * Type 21 self-shield: shield credits from the managed identity [identityId] (32 bytes) + * into this wallet's OWN shielded pool (account 0's default Orchard address; the SDK has no + * recipient parameter here and refuses an own address on the to-recipient entry point). + * Blocks for the proof. Default throws: only the production source (and fakes that + * exercise it) need it. + */ + suspend fun shieldFromIdentity(walletId: ByteArray, identityId: ByteArray, amountCredits: Long): Unit = + throw UnsupportedOperationException("identity self-shield not supported by this source") + /** * Type 18: build an L1 asset lock of [amountDuffs] from the SDK * wallet's OWN Core UTXOs, broadcast it over the SDK's SPV peers, @@ -924,6 +934,17 @@ internal class DashSdkShieldedSource( ) } + override suspend fun shieldFromIdentity(walletId: ByteArray, identityId: ByteArray, amountCredits: Long) { + // As [shieldFromIdentityToRecipient]: the proven post-debit identity balance is not + // needed, the identity balance reads re-fetch it. Account 0 (the SDK default), the + // account [shieldedDefaultAddress] and every other shielded write here use. + manager().shieldedShieldFromIdentity( + walletId = walletId, + identityId = identityId, + amount = amountCredits + ) + } + override suspend fun fundFromAssetLock( walletId: ByteArray, recipientRaw43: ByteArray, @@ -2160,21 +2181,6 @@ class ShieldedBalanceServiceImpl internal constructor( } } - override suspend fun ownShieldedAddressOf(walletIdHex: String): String? { - val walletId = walletIdFromHex(walletIdHex) ?: return null - if (!ensureShieldedReady()) return null - // Pinned: the runtime must be bound to the wallet the caller confirmed with. - if (!walletIdHex.equals(readyWalletIdHex.value, ignoreCase = true)) return null - return try { - source.shieldedDefaultAddress(walletId) - ?.let { raw -> encodeOrchardAddress(raw, displayHrp()) } - } catch (t: Throwable) { - if (t is CancellationException) throw t - log.warn("failed to derive the wallet's own shielded address", t) - null - } - } - override suspend fun ownPlatformAddressOf(walletIdHex: String): String? { val walletId = walletIdFromHex(walletIdHex) ?: return null return try { @@ -2841,6 +2847,20 @@ class ShieldedBalanceServiceImpl internal constructor( } } + override suspend fun shieldFromIdentity( + identityId: ByteArray, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + if (identityId.size != IDENTITY_ID_LENGTH) { + return notBroadcast("shieldFromIdentity", "identity id is not 32 bytes", null) + } + val fromId = identityId.copyOf() + return runShieldedWrite("shieldFromIdentity", amount, expectedWalletIdHex) { walletId, credits -> + source.shieldFromIdentity(walletId, fromId, credits) + } + } + override suspend fun shieldFromWalletToAddress( toShieldedAddress: String, amount: Dash, diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt index 8d3af087c2..a690feb92b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -54,7 +54,6 @@ class InternalTransferServiceImplTest { private val network = AddressNetwork.DASH_TESTNET private val unadvertised = Base58.encodeChecked(network.addressHeader, ByteArray(20) { (it + 1).toByte() }) private val ownPlatform = "tdash1k-own-platform" - private val ownShielded = "tdash1z-own-shielded" private val ownIdentity = Base58.encode(ByteArray(32) { (255 - it).toByte() }) private val amount = Dash.COIN @@ -133,13 +132,13 @@ class InternalTransferServiceImplTest { platformAddressThrows?.let { throw it } return platformAddress } - var shieldedAddress: String? = ownShielded - var shieldedAddressThrows: Throwable? = null - val shieldedAddressReads = mutableListOf() - override suspend fun ownShieldedAddress(walletIdHex: String): String? { - shieldedAddressReads += walletIdHex - shieldedAddressThrows?.let { throw it } - return shieldedAddress + var managedIdentities: List = listOf(checkNotNull(decodeIdentityId(ownIdentity))) + var managedIdentitiesThrows: Throwable? = null + val managedIdentityReads = mutableListOf() + override suspend fun managedIdentityIds(walletIdHex: String): List { + managedIdentityReads += walletIdHex + managedIdentitiesThrows?.let { throw it } + return managedIdentities } override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = feeCredits @@ -156,6 +155,18 @@ class InternalTransferServiceImplTest { return creditsResult } + var identityShieldResult: SdkWriteResult = SdkWriteResult.Broadcast(Unit) + + override suspend fun shieldFromIdentity( + identityId: ByteArray, + amount: Dash, + walletIdHex: String + ): SdkWriteResult { + writes += "shieldFromIdentity(${Base58.encode(identityId)}, ${amount.duffs}, $walletIdHex)" + duringWrite() + return identityShieldResult + } + override suspend fun unshieldToCredits(amount: Dash, walletIdHex: String): SdkWriteResult { writes += "unshieldToCredits(${amount.duffs}, $walletIdHex)" duringWrite() @@ -300,48 +311,6 @@ class InternalTransferServiceImplTest { assertEquals(emptyList(), source.writes) } - @Test - fun `identity to Shielded pays the own shielded address through the External Send, pinned`() { - assertEquals(ExternalSendResult.Sent("txid"), transfer(IDENTITY, SHIELDED)) - assertEquals(listOf(WALLET_A), source.shieldedAddressReads) - assertEquals(listOf(Send(IDENTITY, SendDestination.Shielded(ownShielded), amount, false, WALLET_A)), external.sends) - // Never the Platform-credits self-shield. - assertEquals(emptyList(), source.writes) - } - - @Test - fun `identity to Shielded with no own shielded address, or an unreadable one, fails closed`() { - source.shieldedAddress = null - assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) - source.shieldedAddress = ownShielded - source.shieldedAddressThrows = IOException("runtime not ready") - assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) - assertNothingSubmitted() - } - - @Test - fun `identity to Shielded passes the External Send's outcomes through unchanged`() { - for (outcome in listOf( - ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), - ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), - ExternalSendResult.MayHaveGoneThrough - )) { - external.result = outcome - assertEquals(outcome, transfer(IDENTITY, SHIELDED)) - } - } - - @Test - fun `identity to Shielded needs the shielded flag and an identity`() { - source.shielded = false - assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) - source.shielded = true - source.identity = Result.success(null) - assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) - assertEquals(emptyList(), source.shieldedAddressReads) - assertNothingSubmitted() - } - // ── self routes ────────────────────────────────────────────────────────── @Test @@ -379,8 +348,56 @@ class InternalTransferServiceImplTest { source.writes ) assertEquals(emptyList(), external.sends) - // The shielded address is the External Send's concern only; the self route never reads it. - assertEquals(emptyList(), source.shieldedAddressReads) + // The identity self-shield's managed-identity check is its own; no other self route reads it. + assertEquals(emptyList(), source.managedIdentityReads) + } + + @Test + fun `identity to Shielded is the Type 21 self-shield from the own identity, pinned`() { + assertEquals(ExternalSendResult.Sent(null), transfer(IDENTITY, SHIELDED)) + assertEquals(listOf("shieldFromIdentity($ownIdentity, ${amount.duffs}, $WALLET_A)"), source.writes) + assertEquals(listOf(WALLET_A), source.managedIdentityReads) + // Never the External Send's to-recipient Type 21, never the Platform-credits self-shield. + assertEquals(emptyList(), external.sends) + } + + @Test + fun `identity to Shielded outcomes map without a retry`() { + source.identityShieldResult = SdkWriteResult.NotBroadcast(REASON_SHIELDED_IDENTITY_DEBIT_PENDING) + assertEquals(ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), transfer(IDENTITY, SHIELDED)) + source.identityShieldResult = SdkWriteResult.NotBroadcast("shielded runtime not ready") + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), transfer(IDENTITY, SHIELDED)) + source.identityShieldResult = SdkWriteResult.Ambiguous(IllegalStateException("unconfirmed")) + assertEquals(ExternalSendResult.MayHaveGoneThrough, transfer(IDENTITY, SHIELDED)) + assertEquals(3, source.writes.size) + assertEquals(emptyList(), external.sends) + } + + @Test + fun `identity to Shielded needs the shielded flag and an identity`() { + source.shielded = false + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) + source.shielded = true + source.identity = Result.success(null) + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) + source.identity = Result.failure(IOException("unreadable")) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) + assertEquals(emptyList(), source.managedIdentityReads) + assertNothingSubmitted() + } + + @Test + fun `identity to Shielded from an identity the wallet does not manage, or an unreadable list, fails closed`() { + source.managedIdentities = listOf(ByteArray(32) { 7 }) + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) + source.managedIdentities = emptyList() + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), transfer(IDENTITY, SHIELDED)) + source.managedIdentitiesThrows = IllegalStateException("SDK wallet not loaded") + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) + source.managedIdentitiesThrows = null + source.identity = Result.success("not-base58-0OIl") + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), transfer(IDENTITY, SHIELDED)) + assertNothingSubmitted() } @Test @@ -470,7 +487,7 @@ class InternalTransferServiceImplTest { // ── Reset Wallet: the wipe barrier ─────────────────────────────────────── /** The self routes this service submits itself (the rest hold the barrier in the External Send). */ - private val selfRoutes = listOf(CORE to SHIELDED, SHIELDED to PLATFORM, PLATFORM to SHIELDED) + private val selfRoutes = listOf(CORE to SHIELDED, SHIELDED to PLATFORM, PLATFORM to SHIELDED, IDENTITY to SHIELDED) @Test fun `a wipe under way refuses every self route with nothing called`() { @@ -513,7 +530,7 @@ class InternalTransferServiceImplTest { @Test fun `a wipe that cancels a credits write after its submission may have gone through, never a cancellation`() { - for ((from, to) in listOf(SHIELDED to PLATFORM, PLATFORM to SHIELDED)) { + for ((from, to) in listOf(SHIELDED to PLATFORM, PLATFORM to SHIELDED, IDENTITY to SHIELDED)) { val lock = FundingSelectionLock() val gated = InternalTransferServiceImpl( external, @@ -546,13 +563,12 @@ class InternalTransferServiceImplTest { // Core → Platform: the External Send's lock reserve + margin fee and its Max. assertEquals(fee, service.estimateFee(CORE, PLATFORM)) assertEquals(Dash(5000), service.maxSendable(CORE, PLATFORM)) - // Identity → Shielded: the External Send's figures (null today: metered by Rust). - assertNull(service.estimateFee(IDENTITY, SHIELDED)) - assertNull(service.maxSendable(IDENTITY, SHIELDED)) + // Identity → Shielded is the own self-shield, metered by Rust: never the External Send's + // figures, so null like every identity source. external.pairFees[IDENTITY to SHIELDED] = fee external.pairMax[IDENTITY to SHIELDED] = Dash(5000) - assertEquals(fee, service.estimateFee(IDENTITY, SHIELDED)) - assertEquals(Dash(5000), service.maxSendable(IDENTITY, SHIELDED)) + assertNull(service.estimateFee(IDENTITY, SHIELDED)) + assertNull(service.maxSendable(IDENTITY, SHIELDED)) // The same balance never asks the External Send. external.pairFees[CORE to CORE] = fee external.pairMax[CORE to CORE] = Dash(5000) 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 c5c03a95b1..3050ffb631 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -99,6 +99,7 @@ class ShieldedBalanceServiceTest { var lastBoundAccounts: List? = null var lastAmountCredits: Long? = null var lastRecipientRaw43: ByteArray? = null + var lastWalletId: ByteArray? = null var lastMemo: String? = null var lastPlatformTarget: String? = null var lastCoreAddress: String? = null @@ -307,6 +308,15 @@ class ShieldedBalanceServiceTest { onShield() } + override suspend fun shieldFromIdentity(walletId: ByteArray, identityId: ByteArray, amountCredits: Long) { + broadcastCalls++ + shieldToCalls += "identity-self" + lastWalletId = walletId + lastIdentityId = identityId + lastAmountCredits = amountCredits + onShield() + } + override suspend fun transfer( walletId: ByteArray, recipientRaw43: ByteArray, @@ -1493,26 +1503,6 @@ class ShieldedBalanceServiceTest { assertNull(service(source).shieldedReceiveAddress()) } - @Test - fun ownShieldedAddressOf_isTheReceiveAddress_pinnedToTheBoundWallet() = runBlocking { - val source = readySource().apply { defaultAddress = recipientRaw43 } - val service = service(source) - val address = service.ownShieldedAddressOf(walletIdHex) - assertEquals(service.shieldedReceiveAddress(), address) - assertArrayEquals(recipientRaw43, decodeOrchardAddress(checkNotNull(address), hrp)) - assertEquals(address, service.ownShieldedAddressOf(walletIdHex.uppercase())) - // Another wallet, or a malformed id: null, never this wallet's address. - assertNull(service.ownShieldedAddressOf("cd".repeat(32))) - assertNull(service.ownShieldedAddressOf("not-hex")) - } - - @Test - fun ownShieldedAddressOf_nullWhenNotReadyOrFlagOff() = runBlocking { - assertNull(service(FakeSource(hasSupport = true, boundWalletId = { null })).ownShieldedAddressOf(walletIdHex)) - val source = readySource().apply { defaultAddress = recipientRaw43 } - assertNull(service(source, enabled = false).ownShieldedAddressOf(walletIdHex)) - } - @Test fun platformReceiveAddress_isTheSourcesUnusedPlatformAddress() = runBlocking { val source = readySource().apply { @@ -1892,6 +1882,70 @@ class ShieldedBalanceServiceTest { } } + // ── Identity (Type 21) self-shield: no recipient ── + + @Test + fun shieldFromIdentity_selfShieldsFromTheIdentity_pinned_noRecipient() = runBlocking { + val source = readySource() + val result = service(source).shieldFromIdentity(identity32, Dash(250), walletIdHex.uppercase()) + + assertTrue(result is SdkWriteResult.Broadcast) + assertEquals(listOf("identity-self"), source.shieldToCalls) + assertArrayEquals(identity32, source.lastIdentityId) + assertArrayEquals(walletIdFromHex(walletIdHex), source.lastWalletId) + assertEquals(250_000L, source.lastAmountCredits) + // Never the to-recipient entry point: no recipient was passed anywhere. + assertNull(source.lastRecipientRaw43) + } + + @Test + fun shieldFromIdentity_preflightRefusals_areNotBroadcast_withNoBroadcastAttempt() = runBlocking { + val source = readySource() + val service = service(source) + assertTrue(service.shieldFromIdentity(identity32, Dash.ZERO, walletIdHex) is SdkWriteResult.NotBroadcast) + assertTrue(service.shieldFromIdentity(ByteArray(31), Dash(250), walletIdHex) is SdkWriteResult.NotBroadcast) + // The runtime is bound to another wallet than the one the user confirmed with. + assertTrue(service.shieldFromIdentity(identity32, Dash(250), "cd".repeat(32)) is SdkWriteResult.NotBroadcast) + assertTrue( + service(FakeSource(hasSupport = true, boundWalletId = { null })) + .shieldFromIdentity(identity32, Dash(250), walletIdHex) is SdkWriteResult.NotBroadcast + ) + assertTrue( + service(source, enabled = false).shieldFromIdentity(identity32, Dash(250), walletIdHex) + is SdkWriteResult.NotBroadcast + ) + assertEquals(0, source.broadcastCalls) + } + + @Test + fun shieldFromIdentity_sdkOutcomes_debitPendingIsNotBroadcast_unconfirmedIsAmbiguous() = runBlocking { + val cases = listOf Unit, Boolean>>( + { throw DashSdkError.PlatformWallet.ShieldedIdentityDebitPending("earlier debit unresolved") } to true, + { throw DashSdkError.PlatformWallet.ShieldedBroadcastFailed("relay rejected") } to true, + { throw DashSdkError.InvalidParameter("bad amount") } to true, + { throw DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed("broadcast accepted") } to false, + { throw DashSdkError.NetworkError("conn dropped mid-submit") } to false, + { throw RuntimeException("JNI blew up") } to false + ) + for ((outcome, notBroadcast) in cases) { + val source = readySource().apply { onShield = outcome } + val result = service(source).shieldFromIdentity(identity32, Dash(250), walletIdHex) + if (notBroadcast) { + assertTrue(result is SdkWriteResult.NotBroadcast) + } else { + assertTrue(result is SdkWriteResult.Ambiguous) + } + // One attempt, never retried. + assertEquals(1, source.broadcastCalls) + } + // The debit-pending refusal keeps the reason the send screens map to "still confirming". + val pending = readySource().apply { + onShield = { throw DashSdkError.PlatformWallet.ShieldedIdentityDebitPending("earlier debit unresolved") } + } + val result = service(pending).shieldFromIdentity(identity32, Dash(250), walletIdHex) + assertEquals(REASON_SHIELDED_IDENTITY_DEBIT_PENDING, (result as SdkWriteResult.NotBroadcast).reason) + } + // ── Pure mapping: sync status ───────────────────────────────────────── @Test From 3e1f3dfe752a14aabd7b6acee242fcb1152bc2b7 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 21:14:46 -0800 Subject: [PATCH 16/17] fix(payments): keep SDK messages out of Internal Transfer logs As d4a6e580c did for External Send: every Throwable-passing log in InternalTransferExecutor and InternalTransferServiceImpl now logs only safeErrorSummary (error class names and a native code), never an exception message or stack trace, which can name a recipient or identity. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/InternalTransferServiceImpl.kt | 10 +++++----- .../ui/payments/internal/InternalTransferExecutor.kt | 9 +++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt index 9f65b6a984..372bc03e95 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -268,7 +268,7 @@ class InternalTransferServiceImpl internal constructor( } catch (e: Exception) { // Every pre-submission step returns its own NotSent; an exception escaping here came // from a write path and may have submitted. - log.error("internal transfer {} → {} failed unclassified; outcome unknown", from, to, e) + log.error("internal transfer {} → {} failed unclassified; outcome unknown ({})", from, to, safeErrorSummary(e)) ExternalSendResult.MayHaveGoneThrough } finally { inFlight.set(false) @@ -321,7 +321,7 @@ class InternalTransferServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("internal transfer {}: no unadvertised Core address; not sent", pair, e) + log.warn("internal transfer {}: no unadvertised Core address; not sent ({})", pair, safeErrorSummary(e)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) } delegate(pair, walletIdHex, from, SendDestination.Core(address), amount, isMax) @@ -449,11 +449,11 @@ class InternalTransferServiceImpl internal constructor( } is SdkWriteResult.NotBroadcast -> { val reason = notSentReasonFor(result) - log.warn("internal transfer {}: not sent ({})", pair, reason, result.cause) + log.warn("internal transfer {}: not sent ({}; {})", pair, reason, safeErrorSummary(result.cause)) ExternalSendResult.NotSent(reason) } is SdkWriteResult.Ambiguous -> { - log.error("internal transfer {}: outcome unconfirmed — may have gone through; do NOT retry", pair, result.cause) + log.error("internal transfer {}: outcome unconfirmed — may have gone through; do NOT retry ({})", pair, safeErrorSummary(result.cause)) ExternalSendResult.MayHaveGoneThrough } } @@ -499,7 +499,7 @@ class InternalTransferServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("internal transfer: {} unreadable", what, e) + log.warn("internal transfer: {} unreadable ({})", what, safeErrorSummary(e)) null } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt index cbc9359c3d..ae3b48e084 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt @@ -22,6 +22,7 @@ import de.schildbach.wallet.service.platform.sdk.ExternalSendResult import de.schildbach.wallet.service.platform.sdk.InternalTransferService import de.schildbach.wallet.service.platform.sdk.NotSentReason import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.safeErrorSummary import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet.ui.payments.send.DashPayConfigInFlightMarker import de.schildbach.wallet.ui.payments.send.ExternalSendInFlightMarker @@ -134,7 +135,7 @@ class InternalTransferExecutor internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("internal transfer in-flight marker unreadable; assuming a transfer may have gone through", e) + log.warn("internal transfer in-flight marker unreadable; assuming a transfer may have gone through ({})", safeErrorSummary(e)) true } if (interrupted) log.warn("internal transfer: a previous process may have left a transfer in flight") @@ -187,7 +188,7 @@ class InternalTransferExecutor internal constructor( throw e } catch (e: Exception) { // Nothing handed to the service: provably nothing spent. - log.warn("internal transfer: could not record the in-flight marker; not sent", e) + log.warn("internal transfer: could not record the in-flight marker; not sent ({})", safeErrorSummary(e)) result = ExternalSendResult.NotSent(NotSentReason.GENERIC) } if (marked && !isCurrent()) { @@ -209,7 +210,7 @@ class InternalTransferExecutor internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.error("internal transfer threw; outcome unknown", e) + log.error("internal transfer threw; outcome unknown ({})", safeErrorSummary(e)) } finally { log.info("internal transfer {} → {} finished: {}", request.from, request.to, kindOf(result)) if (!isCurrent()) { @@ -275,7 +276,7 @@ class InternalTransferExecutor internal constructor( throw e } catch (e: Exception) { // Left set: the next process warns once more (conservative). - log.warn("internal transfer: could not clear the in-flight marker", e) + log.warn("internal transfer: could not clear the in-flight marker ({})", safeErrorSummary(e)) } } From 64e6c6e3a251b07f0b961c64e858619c30e89774 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 13 Nov 2026 20:58:46 -0800 Subject: [PATCH 17/17] fix(payments): show the Internal Shielded -> Core Max as received A Shielded -> Core Max withdraws the Max itself and the asset unlock's Core fee comes out of it, so the own Core balance receives the Max minus WITHDRAWAL_CORE_FEE_DUFFS. Internal's confirm sheet showed the full Max as received and a total of Max + fee (the Core fee counted twice). It now uses External Send's rule, shared as withdrawalCoreFeeIncluded / amountAfterWithdrawalCoreFee: amount shown = Max - Core fee, total = that + fee. The send was already right and is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../internal/InternalTransferScreen.kt | 3 +- .../internal/InternalTransferViewModel.kt | 22 +++++++- .../ui/payments/send/ExternalSendViewModel.kt | 17 +++++- .../internal/InternalTransferViewModelTest.kt | 55 +++++++++++++++++++ 4 files changed, 92 insertions(+), 5 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt index 5e3bdd264c..e88bf5b498 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -153,7 +153,8 @@ fun InternalTransferScreen(uiState: InternalTransferUIState, actions: InternalTr private fun ConfirmSheet(uiState: InternalTransferUIState, confirm: InternalTransferConfirm, actions: InternalTransferActions) { val request = confirm.request SendConfirmSheet( - amount = request.amount, + // What the To balance receives (a Shielded → Core Max: the amount minus the Core fee). + amount = confirm.recipientAmount, rate = uiState.rate, fiatCode = uiState.fiatCode, fromValue = stringResource(balanceNameFor(request.from)), diff --git a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt index a35070bea5..667c612516 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -33,7 +33,10 @@ import de.schildbach.wallet.service.platform.sdk.hasShieldedLeg import de.schildbach.wallet.service.platform.sdk.internalTransferSupport import de.schildbach.wallet.service.platform.sdk.maxBoundsAmount import de.schildbach.wallet.service.platform.sdk.pickerBalances +import de.schildbach.wallet.ui.payments.send.ExternalSendConfirm import de.schildbach.wallet.ui.payments.send.ExternalSendStatus +import de.schildbach.wallet.ui.payments.send.amountAfterWithdrawalCoreFee +import de.schildbach.wallet.ui.payments.send.withdrawalCoreFeeIncluded import de.schildbach.wallet.ui.shielded.parseDashOrNull import de.schildbach.wallet.ui.shielded.parseDecimalOrNull import de.schildbach.wallet.ui.shielded.toDashAt @@ -73,8 +76,23 @@ data class InternalTransferConfirm( val fee: FeeEstimate? = null, val feeLoading: Boolean = true ) { - /** What leaves the From balance: amount plus fee, null while the fee is unknown. */ - val total: Dash? get() = fee?.let { request.amount + it.fee } + /** + * A Shielded → Core Max withdraws [InternalTransferRequest.amount] itself and DPP takes the + * asset unlock's Core fee out of it (as the External Send's [ExternalSendConfirm.coreFeeIncluded]): + * the own Core balance receives the amount minus that fee. + */ + val coreFeeIncluded: Boolean + get() = withdrawalCoreFeeIncluded(request.from, request.to == SendBalance.CORE, request.isMax) + + /** What the To balance receives: the amount, or for [coreFeeIncluded] the amount minus the Core fee. */ + val recipientAmount: Dash + get() = if (coreFeeIncluded) amountAfterWithdrawalCoreFee(request.amount) else request.amount + + /** + * What leaves the From balance: what the To balance receives plus the fee (for Shielded → Core + * the estimate includes the Core fee), null while the fee is unknown. + */ + val total: Dash? get() = fee?.let { recipientAmount + it.fee } } /** diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index c96f698072..da7a5a6e26 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -92,6 +92,19 @@ sealed class ExternalSendStatus { data class Done(val result: ExternalSendResult, val afterRestart: Boolean = false) : ExternalSendStatus() } +/** + * Whether a send from [source] to a Core address withdraws [amount][ExternalSendRequest.amount] + * itself, with DPP taking the asset unlock's Core fee ([WITHDRAWAL_CORE_FEE_DUFFS]) out of it: + * a Shielded → Core Max. Every other withdrawal to Core withdraws the fee on top of the amount + * (`ExternalSendServiceImpl.sendFromShielded`). Shared by the External Send and Internal + * Transfer confirm sheets. + */ +internal fun withdrawalCoreFeeIncluded(source: SendBalance, toCore: Boolean, isMax: Boolean): Boolean = + isMax && toCore && source == SendBalance.SHIELDED + +/** What the recipient of a [withdrawalCoreFeeIncluded] withdrawal of [amount] receives. */ +internal fun amountAfterWithdrawalCoreFee(amount: Dash): Dash = amount - Dash(WITHDRAWAL_CORE_FEE_DUFFS) + /** * The confirm sheet: [request] is exactly what Confirm sends. [fee] null with [feeLoading] false * means the fee cannot be known before the send (never fabricated). @@ -114,7 +127,7 @@ data class ExternalSendConfirm( * minus that fee. Every other withdrawal to Core withdraws the fee on top of the amount. */ val coreFeeIncluded: Boolean - get() = request.isMax && request.source == SendBalance.SHIELDED && request.destination is SendDestination.Core + get() = withdrawalCoreFeeIncluded(request.source, request.destination is SendDestination.Core, request.isMax) /** * What the recipient receives: the amount; for a drain the amount minus the fee (null while @@ -124,7 +137,7 @@ data class ExternalSendConfirm( val recipientAmount: Dash? get() = when { feeIncluded -> fee?.let { request.amount - it.fee } - coreFeeIncluded -> request.amount - Dash(WITHDRAWAL_CORE_FEE_DUFFS) + coreFeeIncluded -> amountAfterWithdrawalCoreFee(request.amount) else -> request.amount } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt index 9ceecf97ad..d42eab9754 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -29,6 +29,7 @@ import de.schildbach.wallet.service.platform.sdk.SendBalance.CORE import de.schildbach.wallet.service.platform.sdk.SendBalance.IDENTITY import de.schildbach.wallet.service.platform.sdk.SendBalance.PLATFORM import de.schildbach.wallet.service.platform.sdk.SendBalance.SHIELDED +import de.schildbach.wallet.service.platform.sdk.WITHDRAWAL_CORE_FEE_DUFFS import de.schildbach.wallet.ui.payments.send.ConfirmNote import de.schildbach.wallet.ui.payments.send.ExternalSendInFlightMarker import de.schildbach.wallet.ui.payments.send.ExternalSendStatus @@ -431,6 +432,60 @@ class InternalTransferViewModelTest { assertEquals(confirm.request, viewModel.confirmedRequest()) } + @Test + fun `a Shielded to Core Max confirms the amount minus the Core fee, and sends the Max itself`() { + service.balances.getValue(SHIELDED).value = twoDash + service.max[SHIELDED to CORE] = oneDash + val fee = Dash(1000 + WITHDRAWAL_CORE_FEE_DUFFS) + service.fee = FeeEstimate(fee, exact = false) + service.gate = CompletableDeferred() + val viewModel = buildViewModel() + viewModel.onSwap() // Shielded → Core + viewModel.onMaxClick() + viewModel.onContinue() + val confirm = requireNotNull(viewModel.state.confirm) + assertEquals(InternalTransferRequest(SHIELDED, CORE, oneDash, true, WALLET_A), confirm.request) + assertTrue(confirm.coreFeeIncluded) + val recipient = oneDash - Dash(WITHDRAWAL_CORE_FEE_DUFFS) + assertEquals(recipient, confirm.recipientAmount) + assertEquals(recipient + fee, confirm.total) + // Unknown while the fee is loading or unknown, as in the External Send. + assertNull(confirm.copy(fee = null, feeLoading = true).total) + assertNull(confirm.copy(fee = null, feeLoading = false).total) + + assertTrue(viewModel.submit(confirm.request)) + assertEquals(listOf(InternalTransferRequest(SHIELDED, CORE, oneDash, true, WALLET_A)), service.transfers) + } + + @Test + fun `a typed Shielded to Core amount is received in full, with the fee on top`() { + service.balances.getValue(SHIELDED).value = twoDash + service.max[SHIELDED to CORE] = twoDash - Dash(2000) + val fee = Dash(1000 + WITHDRAWAL_CORE_FEE_DUFFS) + service.fee = FeeEstimate(fee, exact = false) + val viewModel = buildViewModel() + viewModel.onSwap() // Shielded → Core + viewModel.type("1") + viewModel.onContinue() + val confirm = requireNotNull(viewModel.state.confirm) + assertEquals(InternalTransferRequest(SHIELDED, CORE, oneDash, false, WALLET_A), confirm.request) + assertFalse(confirm.coreFeeIncluded) + assertEquals(oneDash, confirm.recipientAmount) + assertEquals(oneDash + fee, confirm.total) + } + + @Test + fun `only a Shielded to Core Max has the Core fee included`() { + for (from in SendBalance.entries) { + for (to in SendBalance.entries) { + if (from == to) continue + val confirm = InternalTransferConfirm(InternalTransferRequest(from, to, oneDash, true, WALLET_A)) + assertEquals("$from → $to", from == SHIELDED && to == CORE, confirm.coreFeeIncluded) + if (!confirm.coreFeeIncluded) assertEquals(oneDash, confirm.recipientAmount) + } + } + } + @Test fun `submit runs exactly the confirmed request and mirrors the executor`() { service.balances.getValue(CORE).value = twoDash