From 396bc35770820c9c15dd8dcd24ecc06901ac4efd Mon Sep 17 00:00:00 2001 From: Tangem Date: Thu, 25 Apr 2024 11:35:55 +0200 Subject: [PATCH] Updated on 2026-08-14 --- .../tap/di/domain/TokensDomainModule.kt | 3 - core/res/src/main/res/values-ru/strings.xml | 26 +-- core/res/src/main/res/values/strings.xml | 26 +-- .../domain/exchange/RampStateManager.kt | 2 + .../tokens/GetCryptoCurrencyActionsUseCase.kt | 173 ++++++------------ .../model/ScenarioUnavailabilityReason.kt | 21 ++- .../state/factory/TokenDetailsStateFactory.kt | 47 +++-- .../WalletCurrencyActionsClickIntents.kt | 46 +++-- 8 files changed, 126 insertions(+), 218 deletions(-) diff --git a/app/src/main/java/com/tangem/tap/di/domain/TokensDomainModule.kt b/app/src/main/java/com/tangem/tap/di/domain/TokensDomainModule.kt index be433d70bb..6821d4a992 100644 --- a/app/src/main/java/com/tangem/tap/di/domain/TokensDomainModule.kt +++ b/app/src/main/java/com/tangem/tap/di/domain/TokensDomainModule.kt @@ -6,7 +6,6 @@ import com.tangem.domain.tokens.* import com.tangem.domain.tokens.repository.* import com.tangem.domain.walletmanager.WalletManagersFacade import com.tangem.feature.swap.domain.api.SwapRepository -import com.tangem.features.send.api.featuretoggles.SendFeatureToggles import com.tangem.utils.coroutines.CoroutineDispatcherProvider import dagger.Module import dagger.Provides @@ -190,7 +189,6 @@ internal object TokensDomainModule { currenciesRepository: CurrenciesRepository, quotesRepository: QuotesRepository, networksRepository: NetworksRepository, - sendFeatureToggles: SendFeatureToggles, dispatchers: CoroutineDispatcherProvider, ): GetCryptoCurrencyActionsUseCase { return GetCryptoCurrencyActionsUseCase( @@ -199,7 +197,6 @@ internal object TokensDomainModule { currenciesRepository = currenciesRepository, quotesRepository = quotesRepository, networksRepository = networksRepository, - sendFeatureToggles = sendFeatureToggles, dispatchers = dispatchers, ) } diff --git a/core/res/src/main/res/values-ru/strings.xml b/core/res/src/main/res/values-ru/strings.xml index da22a118ee..adb56faef9 100644 --- a/core/res/src/main/res/values-ru/strings.xml +++ b/core/res/src/main/res/values-ru/strings.xml @@ -4,16 +4,12 @@ Валюты Отправляйте только %1$s (%2$s) в сети %3$s на этот адрес. Использование другой сети может привести к утрате средств. Обратиться в поддержку - Попробовать снова Эта функция недоступна в демонстрационном режиме Причина: %s Не могу отправить транзакцию Выбранный кошелёк не поддерживает сеть %1$s Для активации криптографии сети %1$s необходимо сбросить кошелек до заводских настроек. Пожалуйста, выведите свои средства, чтобы не потерять их, после сброса доступ к текущему кошельку будет невозможен. Токены в сети %1$s не поддерживаются этой картой из-за ограничений прошивки. - Спасибо за ваш отзыв. Мы ответим в кратчайшие сроки. - Ваши предложения отправлены - Пожалуйста, попробуйте приложить карту в точности, как показано на анимации, или запросите поддержку. У вас возникли трудности со сканированием карты? Эта карта не предназначена для работы с этим приложением Подключите функцию комиссии по умолчанию и при формировании транзакции на отправку средств комиссия будет выставлена автоматически, а экран комиссии пропущен. Вы всегда сможете на него вернуться. @@ -28,8 +24,6 @@ Тёмная Светлая Как в системе - При выборе настройки как в системе приложение будет использовать тему в соответствии с настройками вашего устройства - Системная Тема Настройки приложения Чтобы скрыть или показать баланс, просто поверните ваше устройство вниз или отключите опцию его в разделе \"Настройки\" @@ -81,7 +75,6 @@ Создать Удалить Отключено - Отключить Готово Включить Включено @@ -114,7 +107,6 @@ Отклонить Перезагрузить Переименовать - Повторить Сохранить изменения Искать Поиск токенов @@ -138,7 +130,6 @@ Я понял Произошла ошибка. Пожалуйста, попробуйте снова. Недоступно - Предупреждение Да Адрес контракта скопирован! Доступные сети @@ -185,7 +176,6 @@ Скрывать балансы жестом переворота Эмитент Подписано - Если вы забудете код, то потеряете доступ к своим средствам. Восстановление кода невозможно. Подробности Проверьте подключение с интернетом или переключитесь на другую сеть Условия использования @@ -551,12 +541,12 @@ Балансы показаны Отменить Выбранная операция в данный момент недоступна. Попробуйте позже. - В данный момент покупка монеты %s недоступна. Но мы работаем над её добавлением. - У вас нет средств для отправки. Пополните счет, чтобы иметь возможность отправить с него средства. - Выбранная операция в данный момент недоступна. Попробуйте позже. - Обмен %s не доступен. Но мы работаем над его добавлением. - В данный момент продажа монеты %s недоступна. Но мы работаем над её добавлением. - Выберите адрес + В данный момент покупка монеты %s недоступна. Следите за нашими обновлениями. + У вас нет средств для продажи. Пополните счет, чтобы иметь возможность продать с него средства. + У вас нет средств для отправки. Пополните счет, чтобы иметь возможность отправить с него средства. + В данный момент обмен монеты %s недоступен. Следите за нашими обновлениями. + Продажа средств станет доступной после завершения транзакции %s + В данный момент продажа %s недоступна. Следите за нашими обновлениями. Сгенерировать XPUB Скрыть Вы скрываете токен с главного экрана, но в любой момент сможете добавить его обратно через страницу управления токенами. @@ -667,9 +657,10 @@ Возможно, данная карта - образец или подделка Ошибка проверки подлинности Ассоциировать - Этот токен должен быть ассоциирован с вашей учетной записью Hedera, прежде чем вы сможете его принять. Стоимость ассоциации ~%.4f %s + Этот токен должен быть ассоциирован с вашей учетной записью Hedera, прежде чем вы сможете его принять. Стоимость ассоциации ~%1$s %2$s Этот токен должен быть ассоциирован с вашей учетной записью Hedera, прежде чем вы сможете его принять Ассоциируете свой токен + Недостаточно %s. Пополните ваш аккаунт Hedera для ассоциации этого токена На этой карте осталось всего %s подписей. Вам следует вывести все ваши средства. Малое количество подписей Токены на разных сетях могут иметь разные адреса. Пожалуйста, убедитесь при переводе средств, что ваш адрес соответствует сети. @@ -689,6 +680,7 @@ Карта уже подписывала транзакции Ваш отзыв мотивирует нас сделать кошелек Tangem еще лучше Нравится Tangem? + Вам необходимо провести ассоциацию токена для того, чтобы иметь возможность принимать его Необходима плата за аренду сети %1$s - это монета в сети %2$s. Для совершения транзакции %3$s, вам необходимо внести немного %4$s (%5$s), чтобы покрыть комиссию сети. Недостаточно %1$s для оплаты комиссии сети diff --git a/core/res/src/main/res/values/strings.xml b/core/res/src/main/res/values/strings.xml index efe98087bb..f40c8e0daa 100644 --- a/core/res/src/main/res/values/strings.xml +++ b/core/res/src/main/res/values/strings.xml @@ -4,16 +4,12 @@ Manage tokens Send only %1$s (%2$s) from %3$s network to this address. Using other tokens and networks may result in loss of funds. Request support - Try again This feature is disabled in Demo mode Reason: %s Can\'t send a transaction The selected does not support the %1$s network To activate the %1$s blockchain\'s cryptographic encryption, you\'ll need to reset the wallet to factory settings. Please withdraw your funds before doing so to ensure that you don\'t lose them, and then complete the reset process. Access to the current wallet will not be possible after the reset. Tokens in %1$s network are not supported by this card due to firmware limitation. - Thank you for your feedback. We will respond as soon as possible - Your suggestions were sent - Please try to tap the card exactly as shown in the animation or request support. Are you having difficulty scanning your card? This card is not designed to work with this app Default Fee @@ -29,8 +25,6 @@ Dark Light System default - If system is selected, the app will auto-adjust based on your device\'s system settings - System Theme App Settings To hide or show your balances, simply flip your device screen down, or switch it off in Settings @@ -80,7 +74,6 @@ Create Delete Disabled - Disconnect Done Enable Enabled @@ -113,7 +106,6 @@ Reject Reload Rename - Retry Save changes Search Search tokens @@ -137,7 +129,6 @@ I understand There was an error. Please try again. Unreachable - Warning Yes Contract address copied! Available networks @@ -184,7 +175,6 @@ Flip-to-Hide Balances Issuer Signed - If you forget the code you will lose access to your funds. Code recovery is not possible. Details Check your internet connection or switch to a different network Terms of Service @@ -552,12 +542,12 @@ Balances shown Undo This operation is currently unavailable. Please try again later. - The purchase of the %s is currently unavailable. But we are working on adding it. - You do not have funds to send. Top up your account to be able to send funds from it. - This operation is currently unavailable. Please try again later. - %s swap is not available. But we are working on adding it. - Sell of the %s coin is currently unavailable. But we are working on adding it. - Choose address + Buying %s is not available at the moment. Please check our updates. + You do not have funds to sell. Top up your account to be able to sell funds from it. + You do not have funds to send. Top up your account to be able to send funds from it. + Swapping %s is not available at the moment. Please check our updates. + Selling funds will be available once the %s transaction is complete + Selling %s is not available at the moment. Please check our updates. Generate XPUB Hide You are about to hide this token from the main screen. You can add it back anytime through the manage tokens page. @@ -668,9 +658,10 @@ This card might be a production sample or counterfeit Authenticity check failed Associate - This token must be associated with your Hedera account before you can receive it. Association fee ~%.4f %s + This token must be associated with your Hedera account before you can receive it. Association fee ~%1$s %2$s This token must be associated with your Hedera account before you can receive it Associate your token + Hot enough %s. Top up your Hedera account to associate this token Only %s signatures are left on this card. You must withdraw all of your funds. Low signature count Tokens on different networks can have different addresses. Double-check that your address matches the network when you transfer funds. @@ -688,6 +679,7 @@ Card has already signed transactions Your review keeps us motivated to make Tangem Wallet even better Enjoying Tangem? + You must associate your token before receiving tokens Network rent fee required %1$s is an asset in the %2$s network. To make a %3$s transaction, you must deposit some %4$s (%5$s) to cover the network fee. Insufficient %1$s to cover network fee diff --git a/domain/legacy/src/main/java/com/tangem/domain/exchange/RampStateManager.kt b/domain/legacy/src/main/java/com/tangem/domain/exchange/RampStateManager.kt index 29712ab27c..ac9b4fa892 100644 --- a/domain/legacy/src/main/java/com/tangem/domain/exchange/RampStateManager.kt +++ b/domain/legacy/src/main/java/com/tangem/domain/exchange/RampStateManager.kt @@ -6,6 +6,8 @@ import com.tangem.domain.tokens.model.CryptoCurrency * Manager that holds info about available actions as Sell and Buy */ interface RampStateManager { + fun availableForBuy(cryptoCurrency: CryptoCurrency): Boolean + fun availableForSell(cryptoCurrency: CryptoCurrency): Boolean } \ No newline at end of file diff --git a/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/GetCryptoCurrencyActionsUseCase.kt b/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/GetCryptoCurrencyActionsUseCase.kt index abd618d4b1..74e89db52c 100644 --- a/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/GetCryptoCurrencyActionsUseCase.kt +++ b/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/GetCryptoCurrencyActionsUseCase.kt @@ -9,13 +9,10 @@ import com.tangem.domain.tokens.repository.MarketCryptoCurrencyRepository import com.tangem.domain.tokens.repository.NetworksRepository import com.tangem.domain.tokens.repository.QuotesRepository import com.tangem.domain.wallets.models.UserWallet -import com.tangem.domain.wallets.models.UserWalletId -import com.tangem.features.send.api.featuretoggles.SendFeatureToggles import com.tangem.utils.coroutines.CoroutineDispatcherProvider import com.tangem.utils.isNullOrZero import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* -import java.math.BigDecimal /** * Use case to determine which TokenActions are available for a [CryptoCurrency] @@ -29,7 +26,6 @@ class GetCryptoCurrencyActionsUseCase( private val currenciesRepository: CurrenciesRepository, private val quotesRepository: QuotesRepository, private val networksRepository: NetworksRepository, - private val sendFeatureToggles: SendFeatureToggles, private val dispatchers: CoroutineDispatcherProvider, ) { @@ -82,8 +78,9 @@ class GetCryptoCurrencyActionsUseCase( /** * Creates list of action for expected order - * Actions priority: [Buy Send Receive Sell Swap] + * Actions priority: [Receive Send Swap Buy Sell] */ + @Suppress("CyclomaticComplexMethod", "LongMethod") private suspend fun createListOfActions( userWallet: UserWallet, coinStatus: CryptoCurrencyStatus?, @@ -112,7 +109,6 @@ class GetCryptoCurrencyActionsUseCase( // send val sendUnavailabilityReason = getSendUnavailabilityReason( - userWalletId = userWallet.walletId, cryptoCurrencyStatus = cryptoCurrencyStatus, coinStatus = coinStatus, ) @@ -124,7 +120,10 @@ class GetCryptoCurrencyActionsUseCase( // swap if (userWallet.isMultiCurrency) { - if (marketCryptoCurrencyRepository.isExchangeable(userWallet.walletId, cryptoCurrency)) { + if ( + marketCryptoCurrencyRepository.isExchangeable(userWallet.walletId, cryptoCurrency) && + cryptoCurrencyStatus.value !is CryptoCurrencyStatus.NoQuote + ) { activeList.add(TokenActionsState.ActionState.Swap(ScenarioUnavailabilityReason.None)) } else { disabledList.add( @@ -145,14 +144,42 @@ class GetCryptoCurrencyActionsUseCase( } // sell - if (rampManager.availableForSell(cryptoCurrency)) { - activeList.add(TokenActionsState.ActionState.Sell(ScenarioUnavailabilityReason.None)) - } else { - disabledList.add( - TokenActionsState.ActionState.Sell( - unavailabilityReason = ScenarioUnavailabilityReason.SellUnavailable(cryptoCurrency.name), - ), - ) + val sellSupportedByService = rampManager.availableForSell(cryptoCurrency) + val sendAvailable = sendUnavailabilityReason is ScenarioUnavailabilityReason.None + + when { + sellSupportedByService && sendAvailable -> { + activeList.add(TokenActionsState.ActionState.Sell(ScenarioUnavailabilityReason.None)) + } + sellSupportedByService && !sendAvailable -> { + (sendUnavailabilityReason as? ScenarioUnavailabilityReason.EmptyBalance)?.let { + disabledList.add( + TokenActionsState.ActionState.Sell( + unavailabilityReason = it.copy( + withdrawalScenario = ScenarioUnavailabilityReason.WithdrawalScenario.SELL, + ), + ), + ) + } + (sendUnavailabilityReason as? ScenarioUnavailabilityReason.PendingTransaction)?.let { + disabledList.add( + TokenActionsState.ActionState.Sell( + unavailabilityReason = it.copy( + withdrawalScenario = ScenarioUnavailabilityReason.WithdrawalScenario.SELL, + ), + ), + ) + } + } + else -> { + disabledList.add( + TokenActionsState.ActionState.Sell( + unavailabilityReason = ScenarioUnavailabilityReason.NotSupportedBySellService( + cryptoCurrency.name, + ), + ), + ) + } } // hide @@ -180,9 +207,9 @@ class GetCryptoCurrencyActionsUseCase( ), ) } - actionsList.add(TokenActionsState.ActionState.Send(ScenarioUnavailabilityReason.NoQuotes)) - actionsList.add(TokenActionsState.ActionState.Swap(ScenarioUnavailabilityReason.NoQuotes)) - actionsList.add(TokenActionsState.ActionState.Sell(ScenarioUnavailabilityReason.NoQuotes)) + actionsList.add(TokenActionsState.ActionState.Send(ScenarioUnavailabilityReason.Unreachable)) + actionsList.add(TokenActionsState.ActionState.Swap(ScenarioUnavailabilityReason.Unreachable)) + actionsList.add(TokenActionsState.ActionState.Sell(ScenarioUnavailabilityReason.Unreachable)) if (isAddressAvailable(cryptoCurrencyStatus.value.networkAddress)) { actionsList.add(TokenActionsState.ActionState.Receive(ScenarioUnavailabilityReason.None)) @@ -191,34 +218,22 @@ class GetCryptoCurrencyActionsUseCase( return actionsList } - private suspend fun getSendUnavailabilityReason( - userWalletId: UserWalletId, + private fun getSendUnavailabilityReason( cryptoCurrencyStatus: CryptoCurrencyStatus, coinStatus: CryptoCurrencyStatus?, ): ScenarioUnavailabilityReason { - val insufficientFundsForFee = insufficientFundsForFee( - userWalletId = userWalletId, - tokenStatus = cryptoCurrencyStatus, - coinStatus = coinStatus, - ) - return when { cryptoCurrencyStatus.value.amount.isNullOrZero() -> { - ScenarioUnavailabilityReason.EmptyBalance - } - insufficientFundsForFee != null -> { - ScenarioUnavailabilityReason.InsufficientFundsForFee( - currencyName = insufficientFundsForFee.currencyName, - networkName = insufficientFundsForFee.networkName, - feeCurrencyName = insufficientFundsForFee.feeCurrencyName, - feeCurrencySymbol = insufficientFundsForFee.feeCurrencySymbol, - ) + ScenarioUnavailabilityReason.EmptyBalance(ScenarioUnavailabilityReason.WithdrawalScenario.SEND) } currenciesRepository.hasPendingTransactions( cryptoCurrencyStatus = cryptoCurrencyStatus, coinStatus = coinStatus, ) -> { - ScenarioUnavailabilityReason.PendingTransaction(coinStatus?.currency?.symbol.orEmpty()) + ScenarioUnavailabilityReason.PendingTransaction( + withdrawalScenario = ScenarioUnavailabilityReason.WithdrawalScenario.SEND, + cryptoCurrencySymbol = coinStatus?.currency?.symbol.orEmpty(), + ) } else -> { ScenarioUnavailabilityReason.None @@ -226,93 +241,7 @@ class GetCryptoCurrencyActionsUseCase( } } - private suspend fun insufficientFundsForFee( - userWalletId: UserWalletId, - tokenStatus: CryptoCurrencyStatus, - coinStatus: CryptoCurrencyStatus?, - ): FeeInfo? { - val feePaidCurrency = currenciesRepository.getFeePaidCurrency(userWalletId, tokenStatus.currency) - coinStatus ?: return null - return when { - sendFeatureToggles.isRedesignedSendEnabled && !tokenStatus.value.amount.isZero() -> { - null - } - feePaidCurrency is FeePaidCurrency.Coin && - !tokenStatus.value.amount.isZero() && - coinStatus.value.amount.isZero() -> { - FeeInfo( - currencyName = tokenStatus.currency.name, - networkName = coinStatus.currency.network.name, - feeCurrencyName = coinStatus.currency.name, - feeCurrencySymbol = coinStatus.currency.symbol, - ) - } - feePaidCurrency is FeePaidCurrency.SameCurrency && !tokenStatus.value.amount.isZero() -> { - FeeInfo( - currencyName = tokenStatus.currency.name, - networkName = coinStatus.currency.network.name, - feeCurrencyName = coinStatus.currency.name, - feeCurrencySymbol = coinStatus.currency.symbol, - ) - } - feePaidCurrency is FeePaidCurrency.Token -> { - val feePaidTokenBalance = feePaidCurrency.balance - val amount = tokenStatus.value.amount ?: return null - if (!amount.isZero() && feePaidTokenBalance.isZero()) { - constructTokenBalanceNotEnoughWarning( - userWalletId = userWalletId, - tokenStatus = tokenStatus, - feePaidToken = feePaidCurrency, - ) - } else { - null - } - } - else -> null - } - } - - private suspend fun constructTokenBalanceNotEnoughWarning( - userWalletId: UserWalletId, - tokenStatus: CryptoCurrencyStatus, - feePaidToken: FeePaidCurrency.Token, - ): FeeInfo { - val token = currenciesRepository - .getMultiCurrencyWalletCurrenciesSync(userWalletId) - .find { - it is CryptoCurrency.Token && - it.contractAddress.equals(feePaidToken.contractAddress, ignoreCase = true) && - it.network.derivationPath == tokenStatus.currency.network.derivationPath - } - return if (token != null) { - FeeInfo( - currencyName = tokenStatus.currency.name, - networkName = token.network.name, - feeCurrencyName = feePaidToken.name, - feeCurrencySymbol = feePaidToken.symbol, - ) - } else { - FeeInfo( - currencyName = tokenStatus.currency.name, - networkName = tokenStatus.currency.network.name, - feeCurrencyName = feePaidToken.name, - feeCurrencySymbol = feePaidToken.symbol, - ) - } - } - private fun isAddressAvailable(networkAddress: NetworkAddress?): Boolean { return networkAddress != null && networkAddress.defaultAddress.value.isNotEmpty() } - - private fun BigDecimal?.isZero(): Boolean { - return this?.signum() == 0 - } - - data class FeeInfo( - val currencyName: String, - val networkName: String, - val feeCurrencyName: String, - val feeCurrencySymbol: String, - ) } \ No newline at end of file diff --git a/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/model/ScenarioUnavailabilityReason.kt b/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/model/ScenarioUnavailabilityReason.kt index a3b36c4216..27315e15a7 100644 --- a/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/model/ScenarioUnavailabilityReason.kt +++ b/domain/tokens/src/main/kotlin/com/tangem/domain/tokens/model/ScenarioUnavailabilityReason.kt @@ -3,15 +3,12 @@ package com.tangem.domain.tokens.model sealed class ScenarioUnavailabilityReason { data object None : ScenarioUnavailabilityReason() - // send-specific - data class PendingTransaction(val cryptoCurrencySymbol: String) : ScenarioUnavailabilityReason() - data object EmptyBalance : ScenarioUnavailabilityReason() - data class InsufficientFundsForFee( - val currencyName: String, - val networkName: String, - val feeCurrencyName: String, - val feeCurrencySymbol: String, + // send&sell-specific + data class PendingTransaction( + val withdrawalScenario: WithdrawalScenario, + val cryptoCurrencySymbol: String, ) : ScenarioUnavailabilityReason() + data class EmptyBalance(val withdrawalScenario: WithdrawalScenario) : ScenarioUnavailabilityReason() // buy-specific data class BuyUnavailable(val cryptoCurrencyName: String) : ScenarioUnavailabilityReason() @@ -20,7 +17,11 @@ sealed class ScenarioUnavailabilityReason { data class NotExchangeable(val cryptoCurrencyName: String) : ScenarioUnavailabilityReason() // sell-specific - data class SellUnavailable(val cryptoCurrencyName: String) : ScenarioUnavailabilityReason() + data class NotSupportedBySellService(val cryptoCurrencyName: String) : ScenarioUnavailabilityReason() - data object NoQuotes : ScenarioUnavailabilityReason() + data object Unreachable : ScenarioUnavailabilityReason() + + enum class WithdrawalScenario { + SELL, SEND + } } \ No newline at end of file diff --git a/features/tokendetails/impl/src/main/kotlin/com/tangem/feature/tokendetails/presentation/tokendetails/state/factory/TokenDetailsStateFactory.kt b/features/tokendetails/impl/src/main/kotlin/com/tangem/feature/tokendetails/presentation/tokendetails/state/factory/TokenDetailsStateFactory.kt index cd21841371..0109f66fa5 100644 --- a/features/tokendetails/impl/src/main/kotlin/com/tangem/feature/tokendetails/presentation/tokendetails/state/factory/TokenDetailsStateFactory.kt +++ b/features/tokendetails/impl/src/main/kotlin/com/tangem/feature/tokendetails/presentation/tokendetails/state/factory/TokenDetailsStateFactory.kt @@ -334,29 +334,27 @@ internal class TokenDetailsStateFactory( private fun getUnavailabilityReasonText(unavailabilityReason: ScenarioUnavailabilityReason): TextReference { return when (unavailabilityReason) { - // send is ScenarioUnavailabilityReason.PendingTransaction -> { - resourceReference( - id = R.string.warning_send_blocked_pending_transactions_message, - formatArgs = wrappedList(unavailabilityReason.cryptoCurrencySymbol), - ) + when (unavailabilityReason.withdrawalScenario) { + ScenarioUnavailabilityReason.WithdrawalScenario.SEND -> resourceReference( + id = R.string.warning_send_blocked_pending_transactions_message, + formatArgs = wrappedList(unavailabilityReason.cryptoCurrencySymbol), + ) + ScenarioUnavailabilityReason.WithdrawalScenario.SELL -> resourceReference( + id = R.string.token_button_unavailability_reason_pending_transaction_sell, + formatArgs = wrappedList(unavailabilityReason.cryptoCurrencySymbol), + ) + } } - ScenarioUnavailabilityReason.EmptyBalance -> { - resourceReference( - id = R.string.token_button_unavailability_reason_empty_balance, - ) - } - is ScenarioUnavailabilityReason.InsufficientFundsForFee -> { - resourceReference( - id = R.string.warning_send_blocked_funds_for_fee_message, - formatArgs = wrappedList( - unavailabilityReason.currencyName, - unavailabilityReason.networkName, - unavailabilityReason.currencyName, - unavailabilityReason.feeCurrencyName, - unavailabilityReason.feeCurrencySymbol, - ), - ) + is ScenarioUnavailabilityReason.EmptyBalance -> { + when (unavailabilityReason.withdrawalScenario) { + ScenarioUnavailabilityReason.WithdrawalScenario.SEND -> resourceReference( + id = R.string.token_button_unavailability_reason_empty_balance_send, + ) + ScenarioUnavailabilityReason.WithdrawalScenario.SELL -> resourceReference( + id = R.string.token_button_unavailability_reason_empty_balance_sell, + ) + } } is ScenarioUnavailabilityReason.BuyUnavailable -> { resourceReference( @@ -370,18 +368,17 @@ internal class TokenDetailsStateFactory( formatArgs = wrappedList(unavailabilityReason.cryptoCurrencyName), ) } - is ScenarioUnavailabilityReason.SellUnavailable -> { + is ScenarioUnavailabilityReason.NotSupportedBySellService -> { resourceReference( id = R.string.token_button_unavailability_reason_sell_unavailable, formatArgs = wrappedList(unavailabilityReason.cryptoCurrencyName), ) } - ScenarioUnavailabilityReason.NoQuotes -> { + ScenarioUnavailabilityReason.Unreachable -> { resourceReference( - id = R.string.token_button_unavailability_reason_no_quotes, + id = R.string.token_button_unavailability_generic_description, ) } - ScenarioUnavailabilityReason.None -> { throw IllegalArgumentException("The unavailability reason must be other than None") } diff --git a/features/wallet/impl/src/main/java/com/tangem/feature/wallet/presentation/wallet/viewmodels/intents/WalletCurrencyActionsClickIntents.kt b/features/wallet/impl/src/main/java/com/tangem/feature/wallet/presentation/wallet/viewmodels/intents/WalletCurrencyActionsClickIntents.kt index 16fa32b0e7..3294411975 100644 --- a/features/wallet/impl/src/main/java/com/tangem/feature/wallet/presentation/wallet/viewmodels/intents/WalletCurrencyActionsClickIntents.kt +++ b/features/wallet/impl/src/main/java/com/tangem/feature/wallet/presentation/wallet/viewmodels/intents/WalletCurrencyActionsClickIntents.kt @@ -446,29 +446,27 @@ internal class WalletCurrencyActionsClickIntentsImplementor @Inject constructor( private fun getUnavailabilityReasonText(unavailabilityReason: ScenarioUnavailabilityReason): TextReference { return when (unavailabilityReason) { - // send is ScenarioUnavailabilityReason.PendingTransaction -> { - resourceReference( - id = R.string.warning_send_blocked_pending_transactions_message, - formatArgs = wrappedList(unavailabilityReason.cryptoCurrencySymbol), - ) + when (unavailabilityReason.withdrawalScenario) { + ScenarioUnavailabilityReason.WithdrawalScenario.SEND -> resourceReference( + id = R.string.warning_send_blocked_pending_transactions_message, + formatArgs = wrappedList(unavailabilityReason.cryptoCurrencySymbol), + ) + ScenarioUnavailabilityReason.WithdrawalScenario.SELL -> resourceReference( + id = R.string.token_button_unavailability_reason_pending_transaction_sell, + formatArgs = wrappedList(unavailabilityReason.cryptoCurrencySymbol), + ) + } } - ScenarioUnavailabilityReason.EmptyBalance -> { - resourceReference( - id = R.string.token_button_unavailability_reason_empty_balance, - ) - } - is ScenarioUnavailabilityReason.InsufficientFundsForFee -> { - resourceReference( - id = R.string.warning_send_blocked_funds_for_fee_message, - formatArgs = wrappedList( - unavailabilityReason.currencyName, - unavailabilityReason.networkName, - unavailabilityReason.currencyName, - unavailabilityReason.feeCurrencyName, - unavailabilityReason.feeCurrencySymbol, - ), - ) + is ScenarioUnavailabilityReason.EmptyBalance -> { + when (unavailabilityReason.withdrawalScenario) { + ScenarioUnavailabilityReason.WithdrawalScenario.SEND -> resourceReference( + id = R.string.token_button_unavailability_reason_empty_balance_send, + ) + ScenarioUnavailabilityReason.WithdrawalScenario.SELL -> resourceReference( + id = R.string.token_button_unavailability_reason_empty_balance_sell, + ) + } } is ScenarioUnavailabilityReason.BuyUnavailable -> { resourceReference( @@ -482,15 +480,15 @@ internal class WalletCurrencyActionsClickIntentsImplementor @Inject constructor( formatArgs = wrappedList(unavailabilityReason.cryptoCurrencyName), ) } - is ScenarioUnavailabilityReason.SellUnavailable -> { + is ScenarioUnavailabilityReason.NotSupportedBySellService -> { resourceReference( id = R.string.token_button_unavailability_reason_sell_unavailable, formatArgs = wrappedList(unavailabilityReason.cryptoCurrencyName), ) } - ScenarioUnavailabilityReason.NoQuotes -> { + ScenarioUnavailabilityReason.Unreachable -> { resourceReference( - id = R.string.token_button_unavailability_reason_no_quotes, + id = R.string.token_button_unavailability_generic_description, ) } ScenarioUnavailabilityReason.None -> {