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 e3d33516c5..486a708876 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -587,6 +587,18 @@ 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 + 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. This address is not available right now Revoke access 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 7d38a422f0..9dd5bfe573 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -71,6 +71,18 @@ fun balanceKindOf(destination: SendDestination): SendBalance = when (destination is SendDestination.Identity -> SendBalance.IDENTITY } +/** + * The balances a source / From / To picker lists, in order: Identity only for a user known to + * have an identity ([hasIdentity] true; unknown hides it). Shielded is always listed (it shows + * disabled when the feature is off). Shared by the External Send and the internal transfer. + */ +fun pickerBalances(hasIdentity: Boolean?): List = + SendBalance.entries.filter { it != SendBalance.IDENTITY || hasIdentity == true } + +/** Whether a send from [source] into a [destinationKind] balance involves a ~30 s shielded proof. */ +fun hasShieldedLeg(source: SendBalance, destinationKind: SendBalance): Boolean = + source == SendBalance.SHIELDED || destinationKind == SendBalance.SHIELDED + /** The result of [detectSendDestination]. */ sealed class DestinationParse { /** 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 b84107ed61..dafb3811e6 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -90,6 +90,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() } /** 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 e37b932f85..67068bc12e 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -408,6 +408,38 @@ internal fun logReadRetry( retryLog.warn("external send: {} unreadable; unknown, retrying in {} ms ({})", what, retryDelayMs(attempt), safeErrorSummary(cause)) } +/** + * 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 } +} + +/** + * [ownRegisteredIdentity] of the stored identity record, error-preserving: throws when it is + * unreadable. Shared by the External Send and the internal transfer sources. + */ +internal suspend fun BlockchainIdentityConfig.ownIdentityIdOrThrow(): String? = ownRegisteredIdentity( + getPreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), + getPreservingErrors(BlockchainIdentityConfig.CREATION_STATE) +) + +/** `USE_KOTLIN_SDK_SHIELDED`, error-preserving (absent = off): throws when unreadable. */ +internal suspend fun DashPayConfig.shieldedEnabledOrThrow(): Boolean = + getPreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) == true + +/** The started SDK's wallet manager (starts the SDK first); throws when it is missing. */ +internal suspend fun DashSdkService.startedWalletManager(): org.dashfoundation.dashsdk.wallet.PlatformWalletManager { + ensureStarted() + return checkNotNull(walletManagerOrNull()) { "SDK wallet manager missing after ensureStarted()" } +} + +/** The SDK wallet bound now: the single loaded one, null when none (or not exactly one) is. */ +internal suspend fun DashSdkService.boundWalletIdOrNull(): String? = + startedWalletManager().wallets.value.keys.singleOrNull() + private val retryLog = LoggerFactory.getLogger("de.schildbach.wallet.service.platform.sdk.ExternalSendRetry") /** @@ -618,10 +650,8 @@ internal class DashSdkExternalSendSource( private val fundingGate: PendingPaymentFundingGate ) : ExternalSendSource { - private suspend fun manager(): org.dashfoundation.dashsdk.wallet.PlatformWalletManager { - sdkService.ensureStarted() - return checkNotNull(sdkService.walletManagerOrNull()) { "SDK wallet manager missing after ensureStarted()" } - } + private suspend fun manager(): org.dashfoundation.dashsdk.wallet.PlatformWalletManager = + sdkService.startedWalletManager() /** The PINNED wallet — never "whichever is current". */ private suspend fun wallet(walletIdHex: String): org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet = @@ -629,36 +659,26 @@ internal class DashSdkExternalSendSource( override fun currentCoreSession(): WalletSession? = sendPaymentService.currentWalletSession() - override suspend fun boundWalletIdOrNull(): String? = manager().wallets.value.keys.singleOrNull() + override suspend fun boundWalletIdOrNull(): String? = sdkService.boundWalletIdOrNull() override fun currentBoundWalletIdOrNull(): String? = sdkService.loadedWalletIds().singleOrNull() override suspend fun cutoverCommittedOrThrow(): Boolean = sdkL1SendService.cutoverCommittedOrThrow() - override suspend fun shieldedEnabledOrThrow(): Boolean = - dashPayConfig.getPreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) == true + override suspend fun shieldedEnabledOrThrow(): Boolean = dashPayConfig.shieldedEnabledOrThrow() - override suspend fun ownIdentityIdOrThrow(): String? = ownIdentity( - identityConfig.getPreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), - identityConfig.getPreservingErrors(BlockchainIdentityConfig.CREATION_STATE) - ) + override suspend fun ownIdentityIdOrThrow(): String? = identityConfig.ownIdentityIdOrThrow() override fun observeOwnIdentityId(): Flow> = combine( identityConfig.observePreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), identityConfig.observePreservingErrors(BlockchainIdentityConfig.CREATION_STATE) - ) { id, state -> Result.success(ownIdentity(id, state)) } + ) { id, state -> Result.success(ownRegisteredIdentity(id, state)) } .retryReadErrors( Result.failure(IllegalStateException("identity record unreadable")), onError = logReadRetry("identity record") ) - /** 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 } - } - override suspend fun managedIdentityIds(walletIdHex: String): List = wallet(walletIdHex).inMemoryIdentityStates().filter { !it.watched }.map { it.identityId } 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..1c9ba4d8f6 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferModels.kt @@ -0,0 +1,114 @@ +/* + * 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, + + /** 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]: 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 | 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 + * 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. 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. + */ +fun internalTransferSupport( + from: SendBalance, + to: SendBalance, + shieldedEnabled: Boolean, + hasIdentity: Boolean +): InternalTransferSupport { + if (from == to) return InternalTransferSupport.SAME_BALANCE + 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 +} + +/** 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 + } + ) 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..6221c10e3b --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferService.kt @@ -0,0 +1,73 @@ +/* + * 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: 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 + + /** [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): 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..372bc03e95 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImpl.kt @@ -0,0 +1,514 @@ +/* + * 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.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 +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.dash.wallet.common.util.retryReadErrors +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.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? + + /** + * 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 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 +} + +/** 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.shieldedEnabledOrThrow() + + override fun observeShieldedFlag(): Flow = + flow { emitAll(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) } + + override suspend fun boundWalletIdOrNull(): String? = sdkService.boundWalletIdOrNull() + + override suspend fun ownIdentityIdOrThrow(): String? = identityConfig.ownIdentityIdOrThrow() + + override fun unadvertisedCoreAddress(): String = walletData.unadvertisedDestinationLive().toBase58() + + override suspend fun ownPlatformAddress(walletIdHex: String): String? = + shieldedBalanceService.ownPlatformAddressOf(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) + + override suspend fun shieldFromWallet(amount: Dash, walletIdHex: String) = + shieldedBalanceService.shieldFromWallet(amount, walletIdHex) + + 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) +} + +/** + * 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 (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 + * pending is [ExternalSendResult.CompletesAutomatically]. + * - Core → Identity, Shielded → Identity, Platform → Identity: [ExternalSendService.send] to + * the user's own identity id. + * - 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.unshieldToCredits] (pinned; own Platform address), + * with the shielded Max fee retry. + * - Platform → Shielded: [ShieldedBalanceService.shieldFromCredits] (pinned). + * - 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`: + * 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 + * 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, Identity → 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, + /** + * 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 + constructor( + externalSendService: ExternalSendService, + sdkService: DashSdkService, + sdkL1SendService: SdkL1SendService, + shieldedBalanceService: ShieldedBalanceService, + dashPayConfig: DashPayConfig, + identityConfig: BlockchainIdentityConfig, + walletData: WalletData, + fundingSelection: FundingSelectionLock + ) : this( + externalSendService, + DashSdkInternalTransferSource( + sdkService, sdkL1SendService, shieldedBalanceService, dashPayConfig, identityConfig, walletData + ), + fundingSelection = fundingSelection + ) + + 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(null, retryDelayMs, logReadRetry("shielded flag", 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.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 → 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 && !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 && !isIdentitySelfShield(from, to)) externalSendService.maxSendable(from, to) else null + + private fun isIdentitySelfShield(from: SendBalance, to: SendBalance): Boolean = + from == SendBalance.IDENTITY && to == SendBalance.SHIELDED + + // ── 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, safeErrorSummary(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) return notSent(pair, NotSentReason.NOT_SUPPORTED, "same balance") + + // 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 (hasShieldedLeg(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, safeErrorSummary(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(walletIdHex) } + ?: 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) + SendBalance.PLATFORM -> mapWrite( + pair, + submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + source.shieldFromCredits(amount, walletIdHex) + } + ) + SendBalance.IDENTITY -> shieldFromOwnIdentity(pair, walletIdHex, ownIdentityId, amount) + SendBalance.SHIELDED -> notSent(pair, NotSentReason.NOT_SUPPORTED, "same balance") + } + } + } + + /** + * 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, + 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") + } + // 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 -> { + log.warn("internal transfer {}: lock out, shield pending — the sweep completes it", pair) + ExternalSendResult.CompletesAutomatically + } + } + else -> mapWrite(pair, result) + } + } + + /** + * 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, + walletIdHex: String, + amount: Dash, + isMax: Boolean + ): ExternalSendResult { + suspend fun attempt(value: Dash): SdkWriteResult = submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + 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, safeErrorSummary(result.cause)) + ExternalSendResult.NotSent(reason) + } + is SdkWriteResult.Ambiguous -> { + log.error("internal transfer {}: outcome unconfirmed — may have gone through; do NOT retry ({})", pair, safeErrorSummary(result.cause)) + ExternalSendResult.MayHaveGoneThrough + } + } + + /** + * [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() } + 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, safeErrorSummary(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 377ea7ac74..d3cb797194 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -374,13 +374,26 @@ 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 * targets this wallet's default Orchard address. Blocks for the ~30s - * proof; the note arrives on the next shielded sync pass. + * proof; the note arrives on the next shielded sync pass. With [expectedWalletIdHex] (the SDK wallet the + * caller captured before its first suspension) the write is pinned to it: a runtime + * bound to another wallet is a [SdkWriteResult.NotBroadcast] before anything is + * submitted. Null (the default) uses whichever wallet is bound. */ - suspend fun shieldFromCredits(amount: Dash): SdkWriteResult + suspend fun shieldFromCredits(amount: Dash, expectedWalletIdHex: String? = null): SdkWriteResult /** * Shield [amount] of the wallet's L1 (Core) balance into its own @@ -420,9 +433,15 @@ interface ShieldedBalanceService { * * The recipient receives `amount − pool fee` (the flat shielded fee * plus the protocol's asset-lock base cost come out of the locked - * amount). Blocks for the ~30s Halo 2 proof. + * amount). Blocks for the ~30s Halo 2 proof. With [expectedWalletIdHex] (the SDK wallet the + * caller captured before its first suspension) the write is pinned to it: a runtime + * bound to another wallet is a [SdkWriteResult.NotBroadcast] before anything is + * submitted. Null (the default) uses whichever wallet is bound. */ - suspend fun shieldFromWallet(amount: Dash): SdkWriteResult + suspend fun shieldFromWallet( + amount: Dash, + expectedWalletIdHex: String? = null + ): SdkWriteResult /** * [shieldFromWallet], but funded STRICTLY from the single funds account @@ -534,9 +553,12 @@ interface ShieldedBalanceService { * (Type 17) — the target is the wallet's lowest-index unused DIP-17 * Platform receive address from the SDK's address store; no address * available yet is a [SdkWriteResult.NotBroadcast]. Blocks for the - * ~30s proof. + * ~30s proof. With [expectedWalletIdHex] (the SDK wallet the + * caller captured before its first suspension) the write is pinned to it: a runtime + * bound to another wallet is a [SdkWriteResult.NotBroadcast] before anything is + * submitted. Null (the default) uses whichever wallet is bound. */ - suspend fun unshieldToCredits(amount: Dash): SdkWriteResult + suspend fun unshieldToCredits(amount: Dash, expectedWalletIdHex: String? = null): SdkWriteResult /** * Withdraw [amount] from the shielded pool to the Core L1 address @@ -623,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 e45ae3a58b..65514b62a8 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,8 +2181,22 @@ class ShieldedBalanceServiceImpl internal constructor( } } - override suspend fun shieldFromCredits(amount: Dash): SdkWriteResult = - runShieldedWrite("shieldFromCredits", amount) { walletId, credits -> + 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, 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) } @@ -2203,8 +2238,11 @@ class ShieldedBalanceServiceImpl internal constructor( } .distinctUntilChanged() - override suspend fun shieldFromWallet(amount: Dash): SdkWriteResult = - shieldFromWalletInternal(amount, fundingPath = null) + override suspend fun shieldFromWallet( + 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 { @@ -2775,7 +2813,7 @@ class ShieldedBalanceServiceImpl internal constructor( amount: Dash, expectedWalletIdHex: String ): SdkWriteResult { - if (identityId.size != 32) { + if (identityId.size != IDENTITY_ID_LENGTH) { return notBroadcast("topUpIdentityFromShielded", "identity id is not 32 bytes", null) } val target = identityId.copyOf() @@ -2802,7 +2840,7 @@ class ShieldedBalanceServiceImpl internal constructor( amount: Dash, expectedWalletIdHex: String ): SdkWriteResult { - if (identityId.size != 32) { + if (identityId.size != IDENTITY_ID_LENGTH) { return notBroadcast("shieldFromIdentityToAddress", "identity id is not 32 bytes", null) } val recipientRaw43 = decodeOrchardAddress(toShieldedAddress, displayHrpSafe()) @@ -2813,6 +2851,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, @@ -2870,8 +2922,11 @@ class ShieldedBalanceServiceImpl internal constructor( } } - override suspend fun unshieldToCredits(amount: Dash): SdkWriteResult = - runShieldedWrite("unshieldToCredits", amount) { walletId, credits -> + override suspend fun unshieldToCredits(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/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() } 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 0bc4a17b3e..64fe33a139 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt @@ -320,6 +320,13 @@ open class DashPayConfig @Inject constructor( */ val EXTERNAL_PLATFORM_FUNDING_UNCONFIRMED = stringSetPreferencesKey("external_platform_funding_unconfirmed") + /** + * [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/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 cdb05545af..f330feaa29 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -17,7 +17,6 @@ package de.schildbach.wallet.ui.payments -import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.view.View @@ -39,24 +38,24 @@ import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.fragment.app.Fragment -import androidx.fragment.app.viewModels -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope -import androidx.lifecycle.repeatOnLifecycle +import androidx.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.Constants +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 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 -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.filterNotNull -import kotlinx.coroutines.flow.map +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.dash.wallet.common.ui.components.DashWalletTheme import org.dash.wallet.common.ui.components.LocalDashColors @@ -68,11 +67,13 @@ 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); 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. * @@ -87,25 +88,33 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { private const val PREFS_RECENT_TAB = "advanced_payments_recent_tab" private const val STATE_SELECTED_TAB = "selected_tab" + /** The tabs on show, in display order: fixed for the build ([advancedPaymentsTabIds]). */ + private val TAB_IDS: List = advancedPaymentsTabIds(Constants.SUPPORTS_PLATFORM) + /** The pager position of [tabId] in [tabIds]; the first page if it is not shown. */ @VisibleForTesting fun positionOf(tabIds: List, tabId: Int): Int = tabIds.indexOf(tabId).takeIf { it >= 0 } ?: 0 + + /** 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) - private val viewModel by viewModels() /** * The logical tab the user is on, and the only selection state: the picker and the pager - * positions follow from it ([positionOf]). Kept across view recreation and tab-set changes. + * positions follow from it ([positionOf]). Set in [onCreate]; kept across view recreation. */ - private var selectedTabId by mutableStateOf(null) + private var selectedTabId by mutableStateOf(ACTIVE_TAB_RECEIVE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - if (savedInstanceState?.containsKey(STATE_SELECTED_TAB) == true) { - selectedTabId = savedInstanceState.getInt(STATE_SELECTED_TAB) + selectedTabId = if (savedInstanceState?.containsKey(STATE_SELECTED_TAB) == true) { + savedInstanceState.getInt(STATE_SELECTED_TAB) + } else { + initialTabId() } } @@ -133,16 +142,16 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } } - // Attached by showTabs once the first tab set is in, not here: see there. - val adapter = TabsAdapter(this, source = arguments?.getString(ARG_SOURCE) ?: "") + val adapter = TabsAdapter(this, TAB_IDS, source = arguments?.getString(ARG_SOURCE) ?: "") // Only the top picker changes tabs: a sideways drag belongs to the page's own // content (the Receive balance switch scrolls sideways), never to the pager. binding.pager.isUserInputEnabled = false viewLifecycleOwner.observeOnDestroy { binding.pager.adapter = null } binding.pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { - val tabId = adapter.tabIds.getOrNull(position) ?: return + val tabId = TAB_IDS.getOrNull(position) ?: return selectedTabId = tabId + applyBottomNavigation() if (arguments?.containsKey(ARG_ACTIVE_TAB) != true) { requireActivity().getPreferences(Context.MODE_PRIVATE) @@ -151,38 +160,50 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { } }) - viewLifecycleOwner.lifecycleScope.launch { - viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { - viewModel.uiState - .map { it.tabIds } - .filterNotNull() - .distinctUntilChanged() - .collect { showTabs(adapter, it) } + // Decide the tab before attaching: attaching can report a page selection of its own. + val position = positionOf(TAB_IDS, selectedTabId) + // Attached populated (the tab set is fixed), as PaymentsFragment does: ViewPager2 hands + // the adapter its saved pages when it is attached, so after a rotation the retained + // Receive child and its ViewModel are reused and the selected balance is kept. + binding.pager.adapter = adapter + selectedTabId = TAB_IDS[position] + binding.pager.setCurrentItem(position, false) + // setCurrentItem reports no selection when the position is unchanged. + applyBottomNavigation() + + // 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) } } - override fun onSaveInstanceState(outState: Bundle) { - super.onSaveInstanceState(outState) - selectedTabId?.let { outState.putInt(STATE_SELECTED_TAB, it) } + /** + * 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() { + val tabId = selectedTabId + if (!isAdded) return + val mainActivity = activity as? MainActivity ?: return + if (findNavController().currentDestination?.id != R.id.advancedPaymentsFragment) return + mainActivity.setBottomNavigationVisible(showsBottomNavigation(tabId)) } - private fun showTabs(adapter: TabsAdapter, newTabIds: List) { - // Decide the tab before the adapter changes: a data-set change can report a - // page selection of its own. - val wanted = selectedTabId ?: initialTabId() - val position = positionOf(newTabIds, wanted) - adapter.submit(newTabIds) - // Attach only once populated, as PaymentsFragment does. ViewPager2 hands the adapter - // its saved pages when it is attached (or, if already attached, when the view state is - // restored), and FragmentStateAdapter drops every restored page that containsItem() - // rejects. Attached empty, that is every page: after a rotation the retained Receive - // child and its ViewModel would be recreated and the selected balance reset to Core. - if (binding.pager.adapter == null) { - binding.pager.adapter = adapter - } - selectedTabId = newTabIds[position] - binding.pager.setCurrentItem(position, false) + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putInt(STATE_SELECTED_TAB, selectedTabId) } private fun initialTabId(): Int = @@ -196,10 +217,8 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { @Composable private fun Header() { val colors = LocalDashColors.current - val ids = viewModel.uiState.collectAsStateWithLifecycle().value.tabIds - // Null until showTabs has picked a tab for this tab set. + val ids = TAB_IDS val selected = selectedTabId - if (ids.isNullOrEmpty() || selected == null) return val receiveLabel = stringResource(R.string.payments_tab_receive_label) val internalLabel = stringResource(R.string.shielded_tab_internal) @@ -233,40 +252,30 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { ) { _, index -> val tabId = ids.getOrNull(index) ?: return@SegmentedPicker selectedTabId = tabId - val pagerTabIds = (binding.pager.adapter as? TabsAdapter)?.tabIds.orEmpty() - binding.pager.currentItem = positionOf(pagerTabIds, tabId) + applyBottomNavigation() + binding.pager.currentItem = positionOf(ids, tabId) } } - /** - * Pages keyed by logical tab id (stable ids), so a change of tab set — the - * shielded flag flipping — keeps the pages that remain and drops only the - * one that went away. - */ + /** One page per tab of the fixed [tabIds] (default positional ids: the set never changes). */ private class TabsAdapter( fragment: Fragment, + private val tabIds: List, private val source: String ) : FragmentStateAdapter(fragment) { - var tabIds: List = emptyList() - private set - - @SuppressLint("NotifyDataSetChanged") - fun submit(newTabIds: List) { - if (newTabIds == tabIds) return - tabIds = newTabIds - notifyDataSetChanged() - } - override fun getItemCount(): Int = tabIds.size - override fun getItemId(position: Int): Long = tabIds[position].toLong() - - override fun containsItem(itemId: Long): Boolean = tabIds.any { it.toLong() == itemId } - override fun createFragment(position: Int): Fragment = when (tabIds[position]) { ACTIVE_TAB_RECEIVE -> AdvancedReceiveFragment.newInstance() - ACTIVE_TAB_INTERNAL -> PaymentsInternalFragment.newInstance() + ACTIVE_TAB_INTERNAL -> InternalTransferFragment.newInstance() else -> AdvancedSendFragment.newInstance(source = source) } } } + +/** + * 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) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt deleted file mode 100644 index eb33b9b6ee..0000000000 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsViewModel.kt +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2026 Dash Core Group. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package de.schildbach.wallet.ui.payments - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import dagger.hilt.android.lifecycle.HiltViewModel -import de.schildbach.wallet.Constants -import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import org.dash.wallet.common.util.readRetryDelayMs -import org.dash.wallet.common.util.retryReadErrors -import org.slf4j.LoggerFactory -import javax.inject.Inject - -/** - * @property tabIds the logical tab ids in display order (see [PaymentsFragment.tabIdsFor]), - * or null until the shielded flag has been read: the screen builds no pages until then. - */ -data class AdvancedPaymentsUIState( - val tabIds: List? = null -) - -@HiltViewModel -class AdvancedPaymentsViewModel @Inject constructor( - dashPayConfig: DashPayConfig -) : ViewModel() { - companion object { - private val log = LoggerFactory.getLogger(AdvancedPaymentsViewModel::class.java) - } - - private val _uiState = MutableStateFlow(AdvancedPaymentsUIState()) - val uiState: StateFlow = _uiState.asStateFlow() - - init { - viewModelScope.launch { - advancedPaymentsTabsFlow( - shieldedFlag = dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED), - supportsPlatform = Constants.SUPPORTS_PLATFORM, - onError = { e, attempt -> log.warn("shielded flag read failed (attempt {})", attempt, e) } - ).collect { tabIds -> - _uiState.update { it.copy(tabIds = tabIds) } - } - } - } -} - -/** - * The shielded flag as a never-failing flow: a failed read counts as off (as - * [DashPayConfig.get] reading absent does for [PaymentsFragment]), is reported to - * [onError] and is retried, so the flow never completes on an [Exception] (see - * [retryReadErrors]: a cancellation or an [Error] still propagates). Shared by the - * Advanced payments tabs ([advancedPaymentsTabsFlow]) and the Receive balance tabs. - */ -internal fun shieldedEnabledFlow( - shieldedFlag: Flow, - onError: (Throwable, Long) -> Unit = { _, _ -> }, - retryDelayMs: (Long) -> Long = ::readRetryDelayMs -): Flow = shieldedFlag - .map { it == true } - .retryReadErrors(false, retryDelayMs, onError) - .distinctUntilChanged() - -/** - * The tab set for the Advanced payments screen. Same gating as [PaymentsFragment]: the - * "Internal" tab needs `SUPPORTS_PLATFORM` and `USE_KOTLIN_SDK_SHIELDED`; a failed read - * hides it (see [shieldedEnabledFlow]). - */ -internal fun advancedPaymentsTabsFlow( - shieldedFlag: Flow, - supportsPlatform: Boolean, - onError: (Throwable, Long) -> Unit = { _, _ -> }, - retryDelayMs: (Long) -> Long = ::readRetryDelayMs -): Flow> = shieldedEnabledFlow(shieldedFlag, onError, retryDelayMs) - .map { PaymentsFragment.tabIdsFor(supportsPlatform && it) } - .distinctUntilChanged() diff --git a/wallet/src/de/schildbach/wallet/ui/payments/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/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt index de61af0cd9..d755d4fab3 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/ReceiveViewModel.kt @@ -347,3 +347,19 @@ class ReceiveViewModel internal constructor( } } } + +/** + * The shielded flag as a never-failing flow: a failed read counts as off (as + * [DashPayConfig.get] reading absent does for [PaymentsFragment]), is reported to + * [onError] and is retried, so the flow never completes on an [Exception] (see + * [retryReadErrors]: a cancellation or an [Error] still propagates). Used by the Receive + * balance tabs. + */ +internal fun shieldedEnabledFlow( + shieldedFlag: Flow, + onError: (Throwable, Long) -> Unit = { _, _ -> }, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +): Flow = shieldedFlag + .map { it == true } + .retryReadErrors(false, retryDelayMs, onError) + .distinctUntilChanged() 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..ae3b48e084 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutor.kt @@ -0,0 +1,290 @@ +/* + * 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.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 +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 +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 java.util.concurrent.atomic.AtomicLong +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. + * + * 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( + private val service: InternalTransferService, + private val marker: ExternalSendInFlightMarker, + private val applicationScope: CoroutineScope +) { + @Inject + 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) + } + + 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) { + throw e + } catch (e: Exception) { + 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") + _state.update { + // 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 + } + } + } + } + + /** 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) { + 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 { + 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 + } 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 ({})", safeErrorSummary(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, + request.to, + request.amount, + request.isMax, + request.expectedWalletIdHex + ) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.error("internal transfer threw; outcome unknown ({})", safeErrorSummary(e)) + } finally { + log.info("internal transfer {} → {} finished: {}", request.from, request.to, kindOf(result)) + 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 } + } + } + } + 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 + } + val acknowledgedIn = generation.get() + if (!_state.compareAndSet(current, InternalTransferExecution.Acknowledging)) return + applicationScope.launch { + // 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() + } 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 ({})", safeErrorSummary(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..18e6d4999a --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferFragment.kt @@ -0,0 +1,180 @@ +/* + * 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.runtime.remember +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 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 + +/** + * 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, or acknowledges a shown outcome (as the + * External Send does); 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, over this page and its in-place sheets and + * outcome overlay: on lock ([onLockScreenActivated]) the outcome is withheld, and Back is left to + * the lock screen, until the wallet is unlocked ([LockScreenActivity.walletLocked] turns false). + */ +@AndroidEntryPoint +class InternalTransferFragment : Fragment(), LockScreenAware { + + 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() + // ViewPager2 lifts only the selected page to RESUMED: an offscreen Internal page + // must not take Back from the page on show. Nor does a sheet or an outcome the + // lock screen covers. + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + val selectedPage = lifecycleState.isAtLeast(Lifecycle.State.RESUMED) + val sheetOpen = uiState.picker != null || uiState.confirm != null + // The outcome overlay replaced a dialog whose dismiss-on-back acknowledged it. + val resultShown = uiState.status is ExternalSendStatus.Done + BackHandler(enabled = selectedPage && !uiState.lockScreenShown && (sheetOpen || resultShown)) { + if (viewModel.uiState.value.status is ExternalSendStatus.Done) { + onResultClosed() + } else { + viewModel.onBack() + } + } + // Built once: a new instance per uiState emission (every key press) would + // make every child taking it recompose. + val actions = remember { + 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 = ::onResultClosed + ) + } + InternalTransferScreen(uiState = uiState, actions = actions) + } + } + } + + 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 + * 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. + */ + 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..e88bf5b498 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferScreen.kt @@ -0,0 +1,528 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.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.runtime.remember +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.ConfirmNote +import de.schildbach.wallet.ui.payments.send.ExternalSendStatus +import de.schildbach.wallet.ui.payments.send.ResultOverlay +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.currencyCodesFor +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.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 overlay 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 sheets, the sending overlay and the outcome overlay are drawn in the page, which the lock + * screen covers; the outcome is also withheld while the lock screen is up + * ([InternalTransferUIState.lockScreenShown]). Back while it shows is the fragment's: it + * acknowledges the outcome. + */ +@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) { + 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. + is ExternalSendStatus.Sending -> if (!uiState.sendingHidden) { + SendingOverlay(status.shieldedLeg, actions.onHideSending) + } + // Drawn in the page, so the lock screen covers it; also withheld (not acknowledged) + // while the lock screen is up. + is ExternalSendStatus.Done -> if (!uiState.lockScreenShown) { + ResultOverlay(status.result, status.afterRestart, actions.onResultClosed) + } + ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} + } + } +} + +/** Figma 3342:12176 confirm, through the shared [SendConfirmSheet]. */ +@Composable +private fun ConfirmSheet(uiState: InternalTransferUIState, confirm: InternalTransferConfirm, actions: InternalTransferActions) { + val request = confirm.request + SendConfirmSheet( + // 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)), + 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 + ) +} + +/** + * 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(ConfirmNote.notInstant(R.string.external_send_shielded_not_instant)) + add( + ConfirmNote.becomesPublic( + 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(ConfirmNote.notInstant(R.string.internal_transfer_withdrawal_not_instant)) + } +} + +@Composable +private fun AmountPage(uiState: InternalTransferUIState, actions: InternalTransferActions) { + val fiatCode = uiState.fiatCode + val codes = remember(fiatCode) { currencyCodesFor(fiatCode) } + 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. 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), + 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.confirmRefused -> + StatusText(stringResource(R.string.internal_transfer_confirm_refused), colors.red) + 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..667c612516 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModel.kt @@ -0,0 +1,627 @@ +/* + * 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.ExternalSendServiceImpl +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.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 +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.delay +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.onEach +import kotlinx.coroutines.flow.transformLatest +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 +) { + /** + * 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 } +} + +/** + * Single UI state of the Advanced-mode Internal tab (MO-1125). + * + * @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. + * @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, except + * for a pair whose Max is its bound ([maxBoundsAmount]: Platform → Core / Identity), where + * unknown blocks Continue. + * @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`). + * @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 outcome is not shown, + * nor acknowledged, until the wallet is unlocked, and Back does not close the covered sheets or + * outcome (see [InternalTransferViewModel.onLockScreen]). + */ +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 confirmRefused: Boolean = false, + val lockScreenShown: 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() = pickerBalances(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; for a + * pair whose Max is its bound ([maxBoundsAmount]) Max only (null blocks): the balance would + * overstate what the send accepts. + */ + val limit: Dash? get() = if (maxBoundsAmount(from, to)) maxSendable else 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 && + limit != 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 -> onRateChanged(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( + hasShieldedLeg(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 (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 + 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(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) { + 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, + 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, + 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) } + } + .transformLatest { balance -> + if (balance == null) { + emit(null) + return@transformLatest + } + var max = service.maxSendable(from, to) + emit(max) + // For a pair whose Max is its bound, an unknown Max blocks Continue, and an + // unchanged balance never re-reads it (as in the External Send). So a failed + // read is retried on the balance poll cadence until it is known. + while (max == null && maxBoundsAmount(from, to)) { + delay(ExternalSendServiceImpl.BALANCE_POLL_MS) + max = service.maxSendable(from, to) + if (max != null) emit(max) + } + } + .onEach { max: Dash? -> + 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, confirmRefused = false) } + 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, + confirmRefused = false + ) + } + 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), + confirmRefused = false + ) + } + 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, confirmRefused = false) } + feeJob?.cancel() + feeJob = viewModelScope.launch { + val fee = service.estimateFee(request.from, request.to) + _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. + * + * 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 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 + * fragment then returns Home; the cleared amount is what a later visit finds). + */ + 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) } + } + + /** + * 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 overlay is drawn in the page too, and is also withheld, not + * acknowledged, until [onLockScreenDismissed]. + */ + fun onLockScreen() { + _uiState.update { it.copy(lockScreenShown = true) } + } + + /** The wallet is unlocked: an outcome withheld by [onLockScreen] shows. */ + 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 + 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 7d35611112..8438f6b94b 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.data.WalletData import de.schildbach.wallet.service.platform.sdk.ExternalSendResult import de.schildbach.wallet.service.platform.sdk.ExternalSendService @@ -96,11 +97,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) } /** @@ -358,5 +366,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 b115daa416..fe04796544 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 @@ -33,17 +32,12 @@ 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.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.statusBarsPadding 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.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -52,10 +46,8 @@ 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 @@ -66,7 +58,6 @@ 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.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 @@ -76,30 +67,20 @@ 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.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.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( @@ -269,10 +250,6 @@ private fun ClipboardEntries(entries: List, onSelected: (String) -> Unit // ── Amount page ───────────────────────────────────────────────────────────── -/** The amount bar's currencies: Dash, then the fiat currency when there is one. */ -private fun currencyCodesFor(fiatCode: String?): List = - if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE) - @Composable private fun AmountPage(uiState: ExternalSendUIState, actions: ExternalSendActions) { val fiatCode = uiState.fiatCode @@ -509,43 +486,6 @@ private fun StatusText(text: String, color: Color) { // ── Sheets ────────────────────────────────────────────────────────────────── -/** - * Dimmed backdrop and a bottom sheet with a grabber, as in the shielded flows. - * - * The sheet keeps clear of the system bars like the app's other Compose sheets - * ([org.dash.wallet.common.ui.dialogs.ComposeBottomSheet]): its background runs under the - * navigation bar (Figma's home indicator), its content stops above it. Under MainActivity's - * fitsSystemWindows root these insets arrive already consumed (zero), so nothing is doubled; - * the padding only matters if the screen is ever hosted edge-to-edge (targetSdk 35+). - */ -@Composable -private fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { - Box( - modifier = Modifier - .fillMaxSize() - .background(Color(0x800A0B0D)) - .statusBarsPadding() - .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) {} - .navigationBarsPadding() - ) { - Grabber() - content() - } - } -} - /** Figma 7076:47424 "Select source": the four balances with a radio; unsupported rows disabled. */ @Composable private fun SourceSheet(uiState: ExternalSendUIState, actions: ExternalSendActions) { @@ -590,129 +530,32 @@ 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) - ) - // Weighted (not filling) so the scrolling details shrink on a short screen or with large - // text and the Cancel/Confirm row below always keeps its height. - Column( - modifier = Modifier - .fillMaxWidth() - .weight(1f, fill = false) - .verticalScroll(rememberScrollState()) - ) { - // What the recipient receives (a Core Max drain: the amount minus the fee, unknown - // while the fee is; a Shielded → Core Max: the amount minus the Core fee). - val recipientAmount = confirm.recipientAmount?.takeIf { !confirm.feeIncluded || !confirm.feeLoading } - ConfirmAmount(recipientAmount, uiState.rate, uiState.fiatCode, unknown) - 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. A null [amount] (not known yet) shows [unknown], as the fee and total rows do. - */ -@Composable -private fun ConfirmAmount(amount: Dash?, rate: Fiat?, fiatCode: String?, unknown: String) { - val separator = remember { decimalSeparatorFor(Locale.getDefault()) } - val fiat = amount?.toFiatAt(rate) - EnterAmount( - primaryAmount = amount?.let { localizeAmountForDisplay(it.toDisplayString(), separator) } ?: unknown, - secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", - currencyCodes = remember(fiatCode) { currencyCodesFor(fiatCode) }, - 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, unknown + // while the fee is; a Shielded → Core Max: the amount minus the Core fee). + amount = confirm.recipientAmount?.takeIf { !confirm.feeIncluded || !confirm.feeLoading }, + 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 ) } @@ -721,213 +564,17 @@ private fun ConfirmAmount(amount: Dash?, rate: Fiat?, fiatCode: String?, unknown * System messages: the send is not instant (icon `info-rect-small`), and the amount and * destination become public (icon `system_message-public`). No other route shows a note. */ -@Composable -private fun ConfirmNotes(source: SendBalance, destination: SendDestination) { - if (source != SendBalance.SHIELDED || destination is SendDestination.Shielded) return +internal fun externalConfirmNotes(source: SendBalance, destination: SendDestination): List { + if (source != SendBalance.SHIELDED || destination is SendDestination.Shielded) return emptyList() val publicNote = 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 } - val notes = listOf( - R.string.external_send_shielded_not_instant to R.drawable.ic_system_message_info, - publicNote to R.drawable.ic_system_message_public + return listOf( + ConfirmNote.notInstant(R.string.external_send_shielded_not_instant), + ConfirmNote.becomesPublic(publicNote) ) - 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, icon) -> - SystemMessage( - description = stringResource(note), - // At the icon's own Figma size, centred in the 30dp leading slot: `iconRes` - // would draw every icon at 18dp. - icon = { Image(painter = painterResource(icon), contentDescription = null) } - ) - } - } -} - -// ── 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 - ) - } - } - } -} - -/** - * The terminal outcome. Only Not sent offers to go back and edit; nothing offers a retry. - * - * Drawn inside the screen, like [SheetOverlay] and [SendingOverlay], rather than as a - * [org.dash.wallet.common.ui.components.ModalDialog]: a dialog is its own window, which stays - * above the lock screen and could be closed without the PIN. In the screen it is covered by the - * lock screen and shows again after unlock. The card copies that dialog's layout so it looks the - * same. Back is handled by the - * fragment, which acknowledges the outcome as the dialog's dismiss-on-back did. - */ -@Composable -private fun ResultOverlay(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { - val colors = LocalDashColors.current - val content = resultContentFor(result, afterRestart) - Box( - modifier = Modifier - .fillMaxSize() - .background(Color(0x800A0B0D)) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { - onClose() - }, - contentAlignment = Alignment.Center - ) { - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 15.dp) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, - shape = RoundedCornerShape(16.dp), - elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), - colors = CardDefaults.cardColors( - containerColor = colors.backgroundSecondary, - contentColor = colors.textPrimary - ) - ) { - Column( - modifier = Modifier - .fillMaxWidth() - .background(colors.backgroundSecondary) - .padding(start = 20.dp, end = 20.dp, top = 32.dp, bottom = 20.dp), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Icon( - imageVector = ImageVector.vectorResource(content.icon), - contentDescription = null, - tint = Color.Unspecified, - modifier = Modifier.size(46.dp) - ) - Spacer(modifier = Modifier.height(20.dp)) - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(2.dp) - ) { - Text( - text = stringResource(content.title), - style = MyTheme.SubtitleSemibold, - textAlign = TextAlign.Center, - color = colors.textPrimary - ) - Text( - text = stringResource(content.message), - style = MyTheme.Body2Regular, - textAlign = TextAlign.Center, - color = colors.textPrimary - ) - Spacer(modifier = Modifier.height(20.dp)) - } - Spacer(modifier = Modifier.height(32.dp)) - DashButton( - text = stringResource(content.button), - onClick = onClose, - modifier = Modifier.fillMaxWidth(), - size = Size.Medium, - 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 - ) -} - -@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.EARLIER_TOP_UP_COMPLETED -> R.string.external_send_not_sent_earlier_top_up_completed - NotSentReason.GENERIC -> R.string.external_send_not_sent_generic } // ── Icons and names ───────────────────────────────────────────────────────── 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 6cf197f295..da7a5a6e26 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -35,7 +35,9 @@ import de.schildbach.wallet.service.platform.sdk.WITHDRAWAL_CORE_FEE_DUFFS import de.schildbach.wallet.service.platform.sdk.balanceKindOf import de.schildbach.wallet.service.platform.sdk.detectSendDestination import de.schildbach.wallet.service.platform.sdk.externalSendSupport +import de.schildbach.wallet.service.platform.sdk.hasShieldedLeg import de.schildbach.wallet.service.platform.sdk.maxBoundsAmount +import de.schildbach.wallet.service.platform.sdk.pickerBalances import de.schildbach.wallet.ui.shielded.parseDashOrNull import de.schildbach.wallet.ui.shielded.parseDecimalOrNull import de.schildbach.wallet.ui.shielded.toDashAt @@ -90,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). @@ -112,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 @@ -122,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 } @@ -206,7 +221,7 @@ data class ExternalSendUIState( /** The sources the sheet lists, in order; Identity only for a user who has one. */ val sources: List - get() = SendBalance.entries.filter { it != SendBalance.IDENTITY || hasIdentity == true } + get() = pickerBalances(hasIdentity) /** Whether [source] can pay [destination]; null before a destination is set. */ fun supportOf(source: SendBalance): SendSupport? = destination?.let { @@ -321,10 +336,6 @@ class ExternalSendViewModel internal constructor( /** "tdash1z...lrs27eg4" — the first 7 and last 8 characters of a long address or id. */ fun shorten(value: String, head: Int = 7, tail: Int = 8): String = if (value.length <= head + tail + 3) value else "${value.take(head)}...${value.takeLast(tail)}" - - /** Whether a send from [source] to [destination] involves a ~30 s shielded proof. */ - fun hasShieldedLeg(source: SendBalance, destination: SendDestination): Boolean = - source == SendBalance.SHIELDED || destination is SendDestination.Shielded } private val _uiState = MutableStateFlow(ExternalSendUIState()) @@ -379,7 +390,7 @@ class ExternalSendViewModel internal constructor( // An outcome being dismissed: no dialog, nothing can be sent yet. ExternalSendExecution.Acknowledging -> ExternalSendStatus.Restoring is ExternalSendExecution.Sending -> ExternalSendStatus.Sending( - hasShieldedLeg(execution.request.source, execution.request.destination) + hasShieldedLeg(execution.request.source, balanceKindOf(execution.request.destination)) ) is ExternalSendExecution.Finished -> ExternalSendStatus.Done(execution.result) } 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..52eb16a9ca --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/SendConfirmComponents.kt @@ -0,0 +1,482 @@ +/* + * 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.Image +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.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +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.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.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 overlay. + +// ── Sheets ────────────────────────────────────────────────────────────────── + +/** + * Dimmed backdrop and a bottom sheet with a grabber, as in the shielded flows. + * + * The sheet keeps clear of the system bars like the app's other Compose sheets + * ([org.dash.wallet.common.ui.dialogs.ComposeBottomSheet]): its background runs under the + * navigation bar (Figma's home indicator), its content stops above it. Under MainActivity's + * fitsSystemWindows root these insets arrive already consumed (zero), so nothing is doubled; + * the padding only matters if the screen is ever hosted edge-to-edge (targetSdk 35+). + */ +@Composable +internal fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .statusBarsPadding() + .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) {} + .navigationBarsPadding() + ) { + 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; null while not known yet + * (a drain's fee is loading), shown as unknown like the fee and total rows. + * @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 System messages 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) + ) + // Weighted (not filling) so the scrolling details shrink on a short screen or with large + // text and the Cancel/Confirm row below always keeps its height. + Column( + modifier = Modifier + .fillMaxWidth() + .weight(1f, fill = false) + .verticalScroll(rememberScrollState()) + ) { + ConfirmAmount(amount, rate, fiatCode, unknown) + 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 + } + ) +} + +/** The amount bar's currencies: Dash, then the fiat currency when there is one. */ +internal fun currencyCodesFor(fiatCode: String?): List = + if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE) + +@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. A null [amount] (not known yet) shows [unknown], as the fee and total rows do. + */ +@Composable +private fun ConfirmAmount(amount: Dash?, rate: Fiat?, fiatCode: String?, unknown: String) { + val separator = remember { decimalSeparatorFor(Locale.getDefault()) } + val fiat = amount?.toFiatAt(rate) + EnterAmount( + primaryAmount = amount?.let { localizeAmountForDisplay(it.toDisplayString(), separator) } ?: unknown, + secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", + currencyCodes = remember(fiatCode) { currencyCodesFor(fiatCode) }, + selectedCurrencyIndex = 0, + showMaxButton = false, + showBalanceButton = false, + showPrimaryChevron = false, + showSecondary = fiat != null, + showCurrencyPicker = false, + modifier = Modifier.padding(horizontal = 20.dp) + ) +} + +/** + * A confirm-sheet System message (Figma 7107:48594): its text and its leading icon, drawn at the + * icon's own Figma size. + */ +internal data class ConfirmNote(@StringRes val text: Int, @DrawableRes val icon: Int) { + companion object { + /** Something takes time (icon `info-rect-small`). */ + fun notInstant(@StringRes text: Int) = ConfirmNote(text, R.drawable.ic_system_message_info) + + /** The amount and destination become public (icon `system_message-public`). */ + fun becomesPublic(@StringRes text: Int) = ConfirmNote(text, R.drawable.ic_system_message_public) + } +} + +/** The confirm sheet's System messages (Figma 7107:48594), 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.text), + // At the icon's own Figma size, centred in the 30dp leading slot: `iconRes` + // would draw every icon at 18dp. + icon = { Image(painter = painterResource(note.icon), contentDescription = null) } + ) + } + } +} + +// ── 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. + * + * Drawn inside the screen, like [SheetOverlay] and [SendingOverlay], rather than as a + * [org.dash.wallet.common.ui.components.ModalDialog]: a dialog is its own window, which stays + * above the lock screen and could be closed without the PIN. In the screen it is covered by the + * lock screen and shows again after unlock. The card copies that dialog's layout so it looks the + * same. Back is handled by the fragment, which acknowledges the outcome as the dialog's + * dismiss-on-back did. + */ +@Composable +internal fun ResultOverlay(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { + val colors = LocalDashColors.current + val content = resultContentFor(result, afterRestart) + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { + onClose() + }, + contentAlignment = Alignment.Center + ) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 15.dp) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, + shape = RoundedCornerShape(16.dp), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), + colors = CardDefaults.cardColors( + containerColor = colors.backgroundSecondary, + contentColor = colors.textPrimary + ) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .background(colors.backgroundSecondary) + .padding(start = 20.dp, end = 20.dp, top = 32.dp, bottom = 20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon( + imageVector = ImageVector.vectorResource(content.icon), + contentDescription = null, + tint = Color.Unspecified, + modifier = Modifier.size(46.dp) + ) + Spacer(modifier = Modifier.height(20.dp)) + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + Text( + text = stringResource(content.title), + style = MyTheme.SubtitleSemibold, + textAlign = TextAlign.Center, + color = colors.textPrimary + ) + Text( + text = stringResource(content.message), + style = MyTheme.Body2Regular, + textAlign = TextAlign.Center, + color = colors.textPrimary + ) + Spacer(modifier = Modifier.height(20.dp)) + } + Spacer(modifier = Modifier.height(32.dp)) + DashButton( + text = stringResource(content.button), + onClick = onClose, + modifier = Modifier.fillMaxWidth(), + size = Size.Medium, + style = Style.TintedGray + ) + } + } + } +} + +/** What the outcome overlay 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.EARLIER_TOP_UP_COMPLETED -> R.string.external_send_not_sent_earlier_top_up_completed + 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..9de71b557f --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferModelsTest.kt @@ -0,0 +1,102 @@ +/* + * 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 { + + @Test + 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 = if (from == to) InternalTransferSupport.SAME_BALANCE else InternalTransferSupport.SUPPORTED + assertEquals("$from → $to", expected, internalTransferSupport(from, to, true, true)) + } + } + assertEquals(InternalTransferSupport.SUPPORTED, internalTransferSupport(IDENTITY, SHIELDED, true, true)) + } + + @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)) + // 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)) + } + + @Test + fun `identity is listed only for a user known to have one`() { + assertEquals(listOf(CORE, SHIELDED, PLATFORM, IDENTITY), pickerBalances(true)) + assertEquals(listOf(CORE, SHIELDED, PLATFORM), pickerBalances(false)) + assertEquals(listOf(CORE, SHIELDED, PLATFORM), pickerBalances(null)) + } + + @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 + 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(hasShieldedLeg(SHIELDED, CORE)) + assertTrue(hasShieldedLeg(PLATFORM, SHIELDED)) + assertFalse(hasShieldedLeg(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..a690feb92b --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/InternalTransferServiceImplTest.kt @@ -0,0 +1,599 @@ +/* + * 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.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 +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 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 +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, destinationKind: SendBalance) = + pairFees[source to destinationKind] + override suspend fun maxSendable(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 platformAddressThrows: Throwable? = null + 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 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? { + boundReads++ + return boundWallets.removeFirstOrNull() ?: defaultBound + } + override suspend fun ownIdentityIdOrThrow(): String? = identity.getOrThrow() + override fun unadvertisedCoreAddress(): String = coreAddress() + val platformAddressReads = mutableListOf() + override suspend fun ownPlatformAddress(walletIdHex: String): String? { + platformAddressReads += walletIdHex + platformAddressThrows?.let { throw it } + return platformAddress + } + 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 + + 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 + } + + 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() + return unshieldResults.removeFirstOrNull() ?: creditsResult + } + } + + private val external = FakeExternal() + private val source = FakeSource() + 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) } + + 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(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(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() + } + + @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 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 `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) + 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) + // 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 + 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 SendBalance.entries.map { it to it }) { + 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)) + } + + // ── 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, IDENTITY 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, IDENTITY 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 + 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) + external.pairFees[CORE to PLATFORM] = fee + external.pairMax[CORE to PLATFORM] = Dash(5000) + assertEquals(fee, service.estimateFee(SHIELDED, CORE)) + assertEquals(Dash(5000), service.maxSendable(SHIELDED, CORE)) + // 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 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) + 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) + 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)) + assertNull(service.maxSendable(PLATFORM, CORE)) + external.pairFees[PLATFORM to CORE] = fee + external.pairMax[PLATFORM to CORE] = Dash(5000) + assertEquals(fee, service.estimateFee(PLATFORM, CORE)) + assertEquals(Dash(5000), service.maxSendable(PLATFORM, CORE)) + } + + @Test + 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(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/service/platform/sdk/ShieldedBalanceServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt index 39800691e1..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, @@ -1872,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 diff --git a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt index c7569a1fd7..d03119405e 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/AdvancedPaymentsTabsTest.kt @@ -17,85 +17,36 @@ 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.Assert.assertFalse +import org.junit.Assert.assertTrue 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 `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 `view model state is empty until the flag is read, then follows it`() { - val flag = MutableStateFlow(false) - val config = mockk { - every { observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) } returns flag - } - val viewModel = AdvancedPaymentsViewModel(config) - // Constants.SUPPORTS_PLATFORM decides whether a set flag can add Internal. - val expectedWhenOn = PaymentsFragment.tabIdsFor(de.schildbach.wallet.Constants.SUPPORTS_PLATFORM) - - assertEquals(twoTabs, viewModel.uiState.value.tabIds) - flag.value = true - assertEquals(expectedWhenOn, viewModel.uiState.value.tabIds) - } - - @Test - fun `initial state has no tabs`() { - assertNull(AdvancedPaymentsUIState().tabIds) + 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 @@ -105,4 +56,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/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( 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..07eb13d204 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferExecutorTest.kt @@ -0,0 +1,349 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.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.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 +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): 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 setGate: 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() { + setGate?.await() + 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) + } + + // ── 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) + } +} 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..d42eab9754 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/internal/InternalTransferViewModelTest.kt @@ -0,0 +1,754 @@ +/* + * 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.ExternalSendServiceImpl +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.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 +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.data.entity.ExchangeRate +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) = 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 rate = MutableStateFlow(null) + private val marker = FakeMarker() + private lateinit var executor: InternalTransferExecutor + private val mainDispatcher = UnconfinedTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(mainDispatcher) + 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 rate + } + 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`() { + service.shielded.value = false + val viewModel = buildViewModel() + 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) + assertTrue(viewModel.state.pickable(InternalTransferPicker.FROM, IDENTITY)) + viewModel.onBalancePicked(IDENTITY) + 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 + 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) + assertTrue(viewModel.state.pickable(InternalTransferPicker.TO, PLATFORM)) + viewModel.onBalancePicked(PLATFORM) + 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 + fun `Platform to Core is bounded by Max only, and a failed Max read is retried`() { + service.balances.getValue(PLATFORM).value = twoDash + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.FROM) + viewModel.onBalancePicked(PLATFORM) + viewModel.onShowPicker(InternalTransferPicker.TO) + viewModel.onBalancePicked(CORE) + assertEquals(PLATFORM to CORE, viewModel.state.from to viewModel.state.to) + viewModel.type("1") + assertNull(viewModel.state.maxSendable) + // The balance would overstate what the withdrawal takes: an unknown Max blocks Continue. + assertNull(viewModel.state.limit) + assertFalse(viewModel.state.canContinue) + + // The balance does not change; only the retry can recover. + service.max[PLATFORM to CORE] = oneDash + mainDispatcher.scheduler.advanceTimeBy(ExternalSendServiceImpl.BALANCE_POLL_MS + 1) + mainDispatcher.scheduler.runCurrent() + + assertEquals(oneDash, viewModel.state.maxSendable) + assertTrue(viewModel.state.canContinue) + viewModel.type("5") + assertTrue(viewModel.state.insufficientBalance) + } + + @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) + } + + @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 + 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 (a chosen Shielded pair with the flag unknown) blocks Continue`() { + service.balances.getValue(SHIELDED).value = twoDash + 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) + 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 `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 + 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()) + } + + // ── lock screen ────────────────────────────────────────────────────────── + + @Test + fun `the picker stays open under the lock screen`() { + val viewModel = buildViewModel() + viewModel.onShowPicker(InternalTransferPicker.FROM) + viewModel.onLockScreen() + // 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 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 confirm = requireNotNull(viewModel.state.confirm) + + viewModel.onLockScreen() + // 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) + assertTrue(service.transfers.isEmpty()) + + viewModel.onLockScreenDismissed() + assertFalse(viewModel.state.lockScreenShown) + assertEquals(confirm, viewModel.state.confirm) + assertEquals(confirm.request, viewModel.confirmedRequest()) + } + + @Test + 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() + viewModel.type("1") + viewModel.onContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + 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) + + 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 + 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( + ConfirmNote(R.string.external_send_shielded_not_instant, R.drawable.ic_system_message_info), + ConfirmNote(R.string.external_send_shielded_public_to_core, R.drawable.ic_system_message_public) + ), + internalConfirmNotes(SHIELDED, CORE) + ) + assertEquals( + listOf(ConfirmNote(R.string.internal_transfer_withdrawal_not_instant, R.drawable.ic_system_message_info)), + 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) + } +}