diff --git a/app/build.gradle b/app/build.gradle index 446c060d9f..addaddcc5c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -93,7 +93,7 @@ dependencies { implementation 'com.google.android.play:core-ktx:1.8.1' coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5' - implementation 'com.tangem:blockchain:develop-83' + implementation 'com.tangem:blockchain:develop-84' // implementation 'com.tangem:blockchain:0.0.1' implementation 'com.tangem.tangem-sdk-kotlin:core:develop-142' implementation 'com.tangem.tangem-sdk-kotlin:android:develop-142' @@ -170,6 +170,8 @@ dependencies { implementation 'androidx.compose.ui:ui-tooling:1.1.1' implementation "com.google.accompanist:accompanist-appcompat-theme:0.23.0" + implementation "com.github.skydoves:androidveil:1.1.2" + implementation("io.coil-kt:coil:2.0.0-rc01") implementation("io.coil-kt:coil-compose:2.0.0-rc01") @@ -180,4 +182,4 @@ dependencies { androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' -} \ No newline at end of file +} diff --git a/app/src/main/assets/tangem-app-config b/app/src/main/assets/tangem-app-config index 64ae04d208..7f058ec409 160000 --- a/app/src/main/assets/tangem-app-config +++ b/app/src/main/assets/tangem-app-config @@ -1 +1 @@ -Subproject commit 64ae04d2086e5a605dd4da3cba4af32a60d46c79 +Subproject commit 7f058ec409b4eaaf8688ecd4bf944ef8d58d3564 diff --git a/app/src/main/java/com/tangem/tap/TapApplication.kt b/app/src/main/java/com/tangem/tap/TapApplication.kt index 28bf6c2485..b58485ab88 100644 --- a/app/src/main/java/com/tangem/tap/TapApplication.kt +++ b/app/src/main/java/com/tangem/tap/TapApplication.kt @@ -62,7 +62,9 @@ class TapApplication : Application() { NetworkConnectivity.createInstance(store, this) preferencesStorage = PreferencesStorage(this) PicassoHelper.initPicassoWithCaching(this) - currenciesRepository = CurrenciesRepository(this) + currenciesRepository = CurrenciesRepository( + this, store.state.domainNetworks.tangemTechService + ) walletConnectRepository = WalletConnectRepository(this) initFeedbackManager() diff --git a/app/src/main/java/com/tangem/tap/common/DialogManager.kt b/app/src/main/java/com/tangem/tap/common/DialogManager.kt index 19dd6168cb..8af2818c0a 100644 --- a/app/src/main/java/com/tangem/tap/common/DialogManager.kt +++ b/app/src/main/java/com/tangem/tap/common/DialogManager.kt @@ -19,7 +19,11 @@ import com.tangem.tap.features.onboarding.products.wallet.ui.dialogs.AddMoreBack import com.tangem.tap.features.onboarding.products.wallet.ui.dialogs.BackupInProgressDialog import com.tangem.tap.features.onboarding.products.wallet.ui.dialogs.ConfirmDiscardingBackupDialog import com.tangem.tap.features.onboarding.products.wallet.ui.dialogs.UnfinishedBackupFoundDialog +import com.tangem.tap.features.wallet.redux.WalletDialog +import com.tangem.tap.features.wallet.ui.dialogs.AmountToSendBottomSheetDialog +import com.tangem.tap.features.wallet.ui.dialogs.ChooseTradeActionBottomSheetDialog import com.tangem.tap.features.wallet.ui.dialogs.ScanFailsDialog +import com.tangem.tap.features.wallet.ui.dialogs.SignedHashesWarningDialog import com.tangem.tap.features.wallet.ui.dialogs.SimpleOkDialog import com.tangem.tap.features.wallet.ui.wallet.CurrencySelectionDialog import com.tangem.tap.store @@ -60,8 +64,6 @@ class DialogManager : StoreSubscriber { is AppDialog.ScanFailsDialog -> ScanFailsDialog.create(context) is AppDialog.AddressInfoDialog -> AddressInfoBottomSheetDialog(state.dialog, context) is AppDialog.TestActionsDialog -> TestActionsBottomSheetDialog(state.dialog, context) - is AppDialog.CurrencySelectionDialog -> - CurrencySelectionDialog.create(state.dialog, context) is TwinCardsAction.Wallet.ShowInterruptDialog -> CreateWalletInterruptDialog.create(state.dialog, context) is WalletConnectDialog.UnsupportedCard -> @@ -105,6 +107,14 @@ class DialogManager : StoreSubscriber { is BackupDialog.BackupInProgress -> BackupInProgressDialog.create(context) is BackupDialog.UnfinishedBackupFound -> UnfinishedBackupFoundDialog.create(context) is BackupDialog.ConfirmDiscardingBackup -> ConfirmDiscardingBackupDialog.create(context) + is WalletDialog.CurrencySelectionDialog -> + CurrencySelectionDialog.create(state.dialog, context) + is WalletDialog.ChooseTradeActionDialog -> + ChooseTradeActionBottomSheetDialog(context) + is WalletDialog.SelectAmountToSendDialog -> + AmountToSendBottomSheetDialog(context, state.dialog) + is WalletDialog.SignedHashesMultiWalletDialog -> + SignedHashesWarningDialog.create(context) else -> null } dialog?.show() diff --git a/app/src/main/java/com/tangem/tap/common/compose/extensions/LazyListState.kt b/app/src/main/java/com/tangem/tap/common/compose/extensions/LazyListState.kt new file mode 100644 index 0000000000..a14477efca --- /dev/null +++ b/app/src/main/java/com/tangem/tap/common/compose/extensions/LazyListState.kt @@ -0,0 +1,20 @@ +package com.tangem.tap.common.compose.extensions + +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.* + +@Composable +fun LazyListState.OnBottomReached(loadMoreThreshold: Int, loadMore: () -> Unit) { + require(loadMoreThreshold >= 0) + val shouldLoadMore by remember { + derivedStateOf { + val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull() + ?: return@derivedStateOf false + lastVisibleItem.index >= layoutInfo.totalItemsCount - 1 - loadMoreThreshold + } + } + + LaunchedEffect(shouldLoadMore) { + if (shouldLoadMore) loadMore() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/common/extensions/Specific.kt b/app/src/main/java/com/tangem/tap/common/extensions/Specific.kt index ea112781c3..b431b780ad 100644 --- a/app/src/main/java/com/tangem/tap/common/extensions/Specific.kt +++ b/app/src/main/java/com/tangem/tap/common/extensions/Specific.kt @@ -108,24 +108,22 @@ fun BigDecimal.isLessThanOrEqual(value: BigDecimal): Boolean { fun BigDecimal.formatAmountAsSpannedString( currencySymbol: String, - integerPartSizeProportion: Float = 1.4f + reminderPartSizeProportion: Float = 0.7f ): SpannedString { val amount = this .setScale(2, RoundingMode.HALF_UP) - .toString() + .formatWithSpaces() val integer = amount.substringBefore('.') val reminder = amount.substringAfter('.') return buildSpannedString { + append(integer) + append('.') append( - integer, - RelativeSizeSpan(integerPartSizeProportion), + "$reminder $currencySymbol", + RelativeSizeSpan(reminderPartSizeProportion), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) - append('.') - append(reminder) - append(' ') - append(currencySymbol) } } diff --git a/app/src/main/java/com/tangem/tap/common/redux/StateDialog.kt b/app/src/main/java/com/tangem/tap/common/redux/StateDialog.kt index 6181bbbc44..591a20e896 100644 --- a/app/src/main/java/com/tangem/tap/common/redux/StateDialog.kt +++ b/app/src/main/java/com/tangem/tap/common/redux/StateDialog.kt @@ -2,7 +2,6 @@ package com.tangem.tap.common.redux import com.tangem.common.extensions.VoidCallback import com.tangem.tap.common.TestAction -import com.tangem.tap.common.entities.FiatCurrency import com.tangem.tap.features.wallet.redux.AddressData import com.tangem.tap.features.wallet.redux.Currency @@ -28,9 +27,4 @@ sealed class AppDialog : StateDialog { data class TestActionsDialog( val actionsList: List ) : AppDialog() - - data class CurrencySelectionDialog( - val currenciesList: List, - val currentAppCurrency: FiatCurrency, - ) : AppDialog() } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/TapWalletManager.kt b/app/src/main/java/com/tangem/tap/domain/TapWalletManager.kt index 3349096d24..cce3a27c15 100644 --- a/app/src/main/java/com/tangem/tap/domain/TapWalletManager.kt +++ b/app/src/main/java/com/tangem/tap/domain/TapWalletManager.kt @@ -15,7 +15,7 @@ import com.tangem.tap.domain.configurable.config.ConfigManager import com.tangem.tap.domain.extensions.isMultiwalletAllowed import com.tangem.tap.domain.extensions.makePrimaryWalletManager import com.tangem.tap.domain.extensions.makeWalletManagersForApp -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.demo.isDemoCard import com.tangem.tap.features.wallet.redux.WalletAction import com.tangem.tap.network.NetworkConnectivity diff --git a/app/src/main/java/com/tangem/tap/domain/extensions/Amount.kt b/app/src/main/java/com/tangem/tap/domain/extensions/Amount.kt deleted file mode 100644 index 08703ba05c..0000000000 --- a/app/src/main/java/com/tangem/tap/domain/extensions/Amount.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.tangem.tap.domain.extensions - -import com.tangem.blockchain.common.Amount -import com.tangem.blockchain.common.AmountType -import com.tangem.blockchain.extensions.isAboveZero - -fun Map.toSendableAmounts(): List { - return this.toList().unzip().second - .filter { it.type != AmountType.Reserve } - .filter { it.isAboveZero() } -} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/extensions/WalletManagerFactory.kt b/app/src/main/java/com/tangem/tap/domain/extensions/WalletManagerFactory.kt index 8053bb2959..bff4c0c3b7 100644 --- a/app/src/main/java/com/tangem/tap/domain/extensions/WalletManagerFactory.kt +++ b/app/src/main/java/com/tangem/tap/domain/extensions/WalletManagerFactory.kt @@ -10,7 +10,7 @@ import com.tangem.common.hdWallet.DerivationPath import com.tangem.domain.common.ScanResponse import com.tangem.domain.common.TapWorkarounds.isTestCard import com.tangem.domain.common.TapWorkarounds.useOldStyleDerivation -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.wallet.redux.Currency fun WalletManagerFactory.makeWalletManagerForApp( diff --git a/app/src/main/java/com/tangem/tap/domain/tasks/product/ScanProductTask.kt b/app/src/main/java/com/tangem/tap/domain/tasks/product/ScanProductTask.kt index b8b4799532..d57336841e 100644 --- a/app/src/main/java/com/tangem/tap/domain/tasks/product/ScanProductTask.kt +++ b/app/src/main/java/com/tangem/tap/domain/tasks/product/ScanProductTask.kt @@ -28,9 +28,11 @@ import com.tangem.operations.issuerAndUserData.ReadIssuerDataCommand import com.tangem.tap.domain.TapSdkError import com.tangem.tap.domain.extensions.getPrimaryCurve import com.tangem.tap.domain.extensions.getSingleWallet -import com.tangem.tap.domain.tokens.BlockchainNetwork import com.tangem.tap.domain.tokens.CurrenciesRepository +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.preferencesStorage +import com.tangem.tap.scope +import kotlinx.coroutines.launch class ScanProductTask( val card: Card? = null, @@ -192,47 +194,50 @@ private class ScanWalletProcessor( session: CardSession, callback: (result: CompletionResult) -> Unit ) { - val derivations = collectDerivations(card) - if (derivations.isEmpty() || !card.settings.isHDWalletAllowed) { - callback( - CompletionResult.Success( - ScanResponse( - card = card, - productType = ProductType.Wallet, - walletData = session.environment.walletData, - primaryCard = primaryCard + scope.launch { + val derivations = collectDerivations(card) + if (derivations.isEmpty() || !card.settings.isHDWalletAllowed) { + callback( + CompletionResult.Success( + ScanResponse( + card = card, + productType = ProductType.Wallet, + walletData = session.environment.walletData, + primaryCard = primaryCard + ) ) ) - ) - return - } - - DeriveMultipleWalletPublicKeysTask(derivations).run(session) { result -> - when (result) { - is CompletionResult.Success -> { - val response = ScanResponse( - card = card, - productType = ProductType.Wallet, - walletData = session.environment.walletData, - derivedKeys = result.data.entries, - primaryCard = primaryCard - ) - callback(CompletionResult.Success(response)) + return@launch + } + DeriveMultipleWalletPublicKeysTask(derivations).run(session) { result -> + when (result) { + is CompletionResult.Success -> { + val response = ScanResponse( + card = card, + productType = ProductType.Wallet, + walletData = session.environment.walletData, + derivedKeys = result.data.entries, + primaryCard = primaryCard + ) + callback(CompletionResult.Success(response)) + } + is CompletionResult.Failure -> callback(CompletionResult.Failure(result.error)) } - is CompletionResult.Failure -> callback(CompletionResult.Failure(result.error)) } } } - private fun getBlockchainsToDerive(card: Card): List { + private suspend fun getBlockchainsToDerive(card: Card): List { val currenciesRepository = currenciesRepository ?: return emptyList() + val cardCurrencies = currenciesRepository.loadSavedCurrencies(card.cardId, card.settings.isHDWalletAllowed).toMutableList() val blockchainsToDerive = cardCurrencies.ifEmpty { mutableListOf( BlockchainNetwork(Blockchain.Bitcoin, card), - BlockchainNetwork(Blockchain.Ethereum, card)) + BlockchainNetwork(Blockchain.Ethereum, card) + ) } if (card.settings.isHDWalletAllowed) { @@ -260,7 +265,7 @@ private class ScanWalletProcessor( return blockchainsToDerive.distinct() } - private fun collectDerivations(card: Card): Map> { + private suspend fun collectDerivations(card: Card): Map> { val blockchains = getBlockchainsToDerive(card) val derivations = mutableMapOf>() diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/CurrenciesRepository.kt b/app/src/main/java/com/tangem/tap/domain/tokens/CurrenciesRepository.kt index 01c51ceee4..6888b7f648 100644 --- a/app/src/main/java/com/tangem/tap/domain/tokens/CurrenciesRepository.kt +++ b/app/src/main/java/com/tangem/tap/domain/tokens/CurrenciesRepository.kt @@ -2,26 +2,32 @@ package com.tangem.tap.domain.tokens import android.app.Application import android.content.Context -import com.squareup.moshi.Json import com.squareup.moshi.JsonAdapter -import com.squareup.moshi.JsonClass import com.squareup.moshi.Types import com.tangem.blockchain.common.Blockchain import com.tangem.blockchain.common.DerivationStyle import com.tangem.blockchain.common.Token -import com.tangem.blockchain.common.WalletManager -import com.tangem.common.card.Card import com.tangem.common.card.FirmwareVersion -import com.tangem.domain.common.TapWorkarounds.derivationStyle +import com.tangem.common.services.Result +import com.tangem.domain.common.extensions.getTokens +import com.tangem.domain.common.extensions.toNetworkId +import com.tangem.network.api.tangemTech.TangemTechService import com.tangem.network.common.MoshiConverter import com.tangem.tap.common.extensions.appendIf import com.tangem.tap.common.extensions.readJsonFileToString -import com.tangem.tap.domain.extensions.setCustomIconUrl +import com.tangem.tap.domain.tokens.models.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.ObsoleteTokenDao +import com.tangem.tap.domain.tokens.models.TokenDao import com.tangem.tap.features.demo.DemoHelper +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import timber.log.Timber import java.util.* -class CurrenciesRepository(val context: Application) { +class CurrenciesRepository( + private val context: Application, + private val tangemNetworkService: TangemTechService +) { private val moshi = MoshiConverter.defaultMoshi() private val blockchainsAdapter: JsonAdapter> = moshi.adapter( @@ -41,7 +47,7 @@ class CurrenciesRepository(val context: Application) { fun saveUpdatedCurrency(cardId: String, blockchainNetwork: BlockchainNetwork) { var changed = false - val currencies = loadSavedCurrencies(cardId).map { + val currencies = loadSavedCurrenciesWithoutMigration(cardId).map { if (it == blockchainNetwork) { changed = true blockchainNetwork @@ -54,7 +60,7 @@ class CurrenciesRepository(val context: Application) { } fun removeToken(cardId: String, token: Token, blockchainNetwork: BlockchainNetwork) { - val currencies = loadSavedCurrencies(cardId).map { + val currencies = loadSavedCurrenciesWithoutMigration(cardId).map { if (it == blockchainNetwork) { it.copy(tokens = it.tokens.filterNot { it == token }) } else { @@ -65,7 +71,8 @@ class CurrenciesRepository(val context: Application) { } fun removeBlockchain(cardId: String, blockchainNetwork: BlockchainNetwork) { - val currencies = loadSavedCurrencies(cardId).filterNot { it == blockchainNetwork } + val currencies = loadSavedCurrenciesWithoutMigration(cardId) + .filterNot { it == blockchainNetwork } saveCurrencies(cardId, currencies) } @@ -98,12 +105,12 @@ class CurrenciesRepository(val context: Application) { } } - fun loadSavedCurrencies( + suspend fun loadSavedCurrencies( cardId: String, isHdWalletSupported: Boolean = false ): List { if (DemoHelper.isDemoCardId(cardId)) { - return loadDemoCurrencies(cardId) + return loadDemoCurrencies() } return try { val json = context.readFileText(getFileNameForBlockchains(cardId)) @@ -113,7 +120,21 @@ class CurrenciesRepository(val context: Application) { } } - private fun loadDemoCurrencies(cardId: String): List { + fun loadSavedCurrenciesWithoutMigration( + cardId: String, + ): List { + if (DemoHelper.isDemoCardId(cardId)) { + return loadDemoCurrencies() + } + return try { + val json = context.readFileText(getFileNameForBlockchains(cardId)) + blockchainNetworkAdapter.fromJson(json)?.distinct() ?: emptyList() + } catch (exception: Exception) { + emptyList() + } + } + + private fun loadDemoCurrencies(): List { return DemoHelper.config.demoBlockchains.map { BlockchainNetwork( blockchain = it, @@ -123,7 +144,7 @@ class CurrenciesRepository(val context: Application) { } } - private fun tryToLoadPreviousFormatAndMigrate( + private suspend fun tryToLoadPreviousFormatAndMigrate( cardId: String, isHdWalletSupported: Boolean = false ): List { @@ -137,12 +158,12 @@ class CurrenciesRepository(val context: Application) { } } - private fun loadSavedCurrenciesOldWay( + private suspend fun loadSavedCurrenciesOldWay( cardId: String, isHdWalletSupported: Boolean = false ): List { val blockchains = loadSavedBlockchains(cardId) val tokens = loadSavedTokens(cardId) - val currencies = getSupportedTokens() + val ids = getTokensIds(tokens) val derivationStyle = if (isHdWalletSupported) DerivationStyle.LEGACY else null val blockchainNetworks = blockchains.map { blockchain -> BlockchainNetwork( @@ -152,10 +173,7 @@ class CurrenciesRepository(val context: Application) { .filter { it.blockchainDao.toBlockchain() == blockchain } .map { val token = it.toToken() - val id = currencies - .find { it.contracts.find { it.address == token.contractAddress } != null } - ?.id - token.copy(id = id) + token.copy(id = ids[token.contractAddress]) } ) } @@ -163,6 +181,21 @@ class CurrenciesRepository(val context: Application) { return blockchainNetworks } + private suspend fun getTokensIds(tokens: List): Map = coroutineScope { + tokens.map { + async { + tangemNetworkService.getTokens( + it.contractAddress, + it.blockchainDao.toBlockchain().toNetworkId() + ) + } + }.map { it.await() } + .map { (it as? Result.Success)?.data?.coins?.firstOrNull()?.id } + .mapIndexedNotNull { index, id -> + if (id == null) null else tokens[index].contractAddress to id + }.toMap() + } + fun saveCurrencies(cardId: String, currencies: List) { val json = blockchainNetworkAdapter.toJson(currencies) context.rewriteFile(json, getFileNameForBlockchains(cardId)) @@ -177,9 +210,8 @@ class CurrenciesRepository(val context: Application) { } } - fun getSupportedTokens(isTestNet: Boolean = false): List { - val fileName = if (isTestNet) "testnet_tokens" else "tokens" - val json = context.assets.readJsonFileToString(fileName) + fun getTestnetCoins(): List { + val json = context.assets.readJsonFileToString(FILE_NAME_TESTNET_COINS) return currenciesAdapter.fromJson(json)!!.coins .map { Currency.fromJsonObject(it) } } @@ -232,6 +264,7 @@ class CurrenciesRepository(val context: Application) { companion object { private const val FILE_NAME_PREFIX_TOKENS = "tokens" private const val FILE_NAME_PREFIX_BLOCKCHAINS = "blockchains" + private const val FILE_NAME_TESTNET_COINS = "testnet_tokens" fun getFileNameForTokens(cardId: String): String = "${FILE_NAME_PREFIX_TOKENS}_$cardId" fun getFileNameForBlockchains(cardId: String): String = @@ -245,145 +278,3 @@ fun Blockchain.getTokensName(): String { else -> this.fullName } } - -@JsonClass(generateAdapter = true) -data class TokenDao( - val name: String, - val symbol: String, - val contractAddress: String, - val decimalCount: Int, - @Json(name = "blockchain") - val blockchainDao: BlockchainDao, - val customIconUrl: String? = null, - val type: String? = null -) { - fun toToken(): Token { - return Token( - name = name, - symbol = symbol, - contractAddress = contractAddress, - decimals = decimalCount, - ).apply { - customIconUrl?.let { this.setCustomIconUrl(it) } - } - } - -} - -@JsonClass(generateAdapter = true) -data class BlockchainDao( - @Json(name = "key") - val name: String, - @Json(name = "testnet") - val isTestNet: Boolean -) { - fun toBlockchain(): Blockchain { - val blockchain = Blockchain.values().find { it.name.lowercase() == name.lowercase() } - ?: throw Exception("Invalid BlockchainDao") - return if (!isTestNet) blockchain else blockchain.getTestnetVersion() - ?: throw Exception("Invalid BlockchainDao") - } - - companion object { - fun fromBlockchain(blockchain: Blockchain): BlockchainDao { - val name = blockchain.name.removeSuffix("Testnet").lowercase() - return BlockchainDao(name, blockchain.isTestnet()) - } - } -} - -@JsonClass(generateAdapter = true) -data class ObsoleteTokenDao( - val name: String, - val symbol: String, - val contractAddress: String, - val decimalCount: Int, - val customIconUrl: String?, -) { - fun toTokenDao(blockchain: Blockchain): TokenDao { - return TokenDao( - name = name, - symbol = symbol, - contractAddress = contractAddress, - decimalCount = decimalCount, - blockchainDao = BlockchainDao.fromBlockchain(blockchain), - customIconUrl = customIconUrl - ) - } -} - -//@JsonClass(generateAdapter = true) -//data class CardCurrenciesDao( -// val tokens: List, -// val blockchains: List, -//) { -// fun toCardCurrencies(): CardCurrencies { -// return CardCurrencies( -// tokens = tokens.map { it.toToken() }.distinct(), -// blockchains = blockchains -// ) -// } -// -// companion object { -// fun fromCardCurrencies(cardCurrencies: CardCurrencies): CardCurrenciesDao { -// return CardCurrenciesDao( -// tokens = cardCurrencies.tokens.map { TokenDao.fromToken(it) }.distinct(), -// blockchains = cardCurrencies.blockchains -// ) -// } -// } -//} - -data class CardCurrencies( - val tokens: List, - val blockchains: List, -) - -@JsonClass(generateAdapter = true) -data class BlockchainNetwork( - val blockchain: Blockchain, - val derivationPath: String?, - val tokens: List -) { - - constructor(blockchain: Blockchain, card: Card) : this( - blockchain = blockchain, - derivationPath = if (card.settings.isHDWalletAllowed) blockchain.derivationPath(card.derivationStyle)?.rawPath else null, - tokens = emptyList() - ) - - - fun updateTokens(tokens: List): BlockchainNetwork { - return copy( - tokens = (this.tokens + tokens).distinct() - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as BlockchainNetwork - - if (blockchain != other.blockchain) return false - if (derivationPath != other.derivationPath) return false - - return true - } - - override fun hashCode(): Int { - var result = blockchain.hashCode() - result = 31 * result + (derivationPath?.hashCode() ?: 0) - return result - } - - companion object { - fun fromWalletManager(walletManager: WalletManager): BlockchainNetwork { - return BlockchainNetwork( - walletManager.wallet.blockchain, - walletManager.wallet.publicKey.derivationPath?.rawPath, - walletManager.cardTokens.toList() - ) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/Currency.kt b/app/src/main/java/com/tangem/tap/domain/tokens/Currency.kt index 5a4df2c316..6e94b5a88a 100644 --- a/app/src/main/java/com/tangem/tap/domain/tokens/Currency.kt +++ b/app/src/main/java/com/tangem/tap/domain/tokens/Currency.kt @@ -3,6 +3,7 @@ package com.tangem.tap.domain.tokens import com.squareup.moshi.JsonClass import com.tangem.blockchain.common.Blockchain import com.tangem.domain.common.extensions.fromNetworkId +import com.tangem.network.api.tangemTech.CoinsResponse @JsonClass(generateAdapter = true) data class CurrencyFromJson( @@ -44,10 +45,20 @@ data class Currency( id = currency.id, name = currency.name, symbol = currency.symbol, - iconUrl = getIconUrl(currency.id), + iconUrl = getIconUrl(currency.id, null), contracts = currency.networks?.toContracts() ?: emptyList() ) } + + fun fromCoinResponse(currency: CoinsResponse.Coin, imageHost: String?): Currency { + return Currency( + id = currency.id, + name = currency.name, + symbol = currency.symbol, + iconUrl = getIconUrl(currency.id, imageHost), + contracts = currency.networks.mapNotNull { Contract.fromNetwork(it, imageHost) } + ) + } } } @@ -67,12 +78,26 @@ data class Contract( blockchain = blockchain, address = contract.contractAddress, decimalCount = contract.decimalCount, - iconUrl = getIconUrl(contract.networkId) + iconUrl = getIconUrl(contract.networkId, null) + ) + } + + fun fromNetwork(contract: CoinsResponse.Coin.Network, imageHost: String?): Contract? { + val blockchain = Blockchain.fromNetworkId(contract.networkId) ?: return null + return Contract( + networkId = contract.networkId, + blockchain = blockchain, + address = contract.contractAddress, + decimalCount = contract.decimalCount?.toInt(), + iconUrl = getIconUrl(contract.networkId, imageHost) ) } } } -fun getIconUrl(id: String): String { - return "https://s3.eu-central-1.amazonaws.com/tangem.api/coins/large/$id.png" -} \ No newline at end of file +fun getIconUrl(id: String, imageHost: String? = null): String { + return "${imageHost ?: DEFAULT_IMAGE_HOST}large/$id.png" +} + +private const val DEFAULT_IMAGE_HOST = + "https://s3.eu-central-1.amazonaws.com/tangem.api/coins/" \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/LoadAvailableCoinsService.kt b/app/src/main/java/com/tangem/tap/domain/tokens/LoadAvailableCoinsService.kt new file mode 100644 index 0000000000..b195457e4f --- /dev/null +++ b/app/src/main/java/com/tangem/tap/domain/tokens/LoadAvailableCoinsService.kt @@ -0,0 +1,71 @@ +package com.tangem.tap.domain.tokens + +import com.tangem.blockchain.common.Blockchain +import com.tangem.common.services.Result +import com.tangem.domain.common.extensions.getListOfCoins +import com.tangem.domain.common.extensions.toNetworkId +import com.tangem.network.api.tangemTech.CoinsResponse +import com.tangem.network.api.tangemTech.TangemTechService + +class LoadAvailableCoinsService( + private val networkService: TangemTechService, + private val currenciesRepository: CurrenciesRepository +) { + + suspend fun getSupportedTokens( + isTestNet: Boolean = false, + supportedBlockchains: List, + page: Int, + searchInput: String? = null + ): Result { + if (isTestNet) { + return Result.Success( + LoadedCoins( + currencies = currenciesRepository.getTestnetCoins(), + moreAvailable = false, + ) + ) + } + val offset = page * LOAD_PER_PAGE + val result = loadCoins(supportedBlockchains, offset, searchInput) + + return when (result) { + is Result.Success -> { + val data = result.data + Result.Success( + LoadedCoins( + currencies = data.coins.map { Currency.fromCoinResponse(it, data.imageHost) }, + moreAvailable = data.total > offset + LOAD_PER_PAGE, + ) + ) + } + is Result.Failure -> { + Result.Failure(result.error) + } + } + } + + private suspend fun loadCoins( + supportedBlockchains: List, + offset: Int, + searchInput: String? = null + ): Result { + val networkIds = supportedBlockchains.toSet().map { it.toNetworkId() } + return networkService.getListOfCoins( + networkIds = networkIds, + offset = offset, + limit = LOAD_PER_PAGE, + searchText = searchInput + ) + } + + companion object { + const val LOAD_PER_PAGE = 100 + } +} + + +data class LoadedCoins( + val currencies: List, + val moreAvailable: Boolean, +) \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/models/BlockchainDao.kt b/app/src/main/java/com/tangem/tap/domain/tokens/models/BlockchainDao.kt new file mode 100644 index 0000000000..73eef228ad --- /dev/null +++ b/app/src/main/java/com/tangem/tap/domain/tokens/models/BlockchainDao.kt @@ -0,0 +1,30 @@ +package com.tangem.tap.domain.tokens.models + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +import com.tangem.blockchain.common.Blockchain + +@Deprecated("The class is used only for migration from older versions of the app") +@JsonClass(generateAdapter = true) +data class BlockchainDao( + @Json(name = "key") + val name: String, + @Json(name = "testnet") + val isTestNet: Boolean +) { + @Deprecated("The method is used only for migration from older versions of the app") + fun toBlockchain(): Blockchain { + val blockchain = Blockchain.values().find { it.name.lowercase() == name.lowercase() } + ?: throw Exception("Invalid BlockchainDao") + return if (!isTestNet) blockchain else blockchain.getTestnetVersion() + ?: throw Exception("Invalid BlockchainDao") + } + + companion object { + @Deprecated("The method is used only for migration from older versions of the app") + fun fromBlockchain(blockchain: Blockchain): BlockchainDao { + val name = blockchain.name.removeSuffix("Testnet").lowercase() + return BlockchainDao(name, blockchain.isTestnet()) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/models/BlockchainNetwork.kt b/app/src/main/java/com/tangem/tap/domain/tokens/models/BlockchainNetwork.kt new file mode 100644 index 0000000000..36e376a08b --- /dev/null +++ b/app/src/main/java/com/tangem/tap/domain/tokens/models/BlockchainNetwork.kt @@ -0,0 +1,56 @@ +package com.tangem.tap.domain.tokens.models + +import com.squareup.moshi.JsonClass +import com.tangem.blockchain.common.Blockchain +import com.tangem.blockchain.common.Token +import com.tangem.blockchain.common.WalletManager +import com.tangem.common.card.Card +import com.tangem.common.extensions.calculateHashCode +import com.tangem.domain.common.TapWorkarounds.derivationStyle + +@JsonClass(generateAdapter = true) +data class BlockchainNetwork( + val blockchain: Blockchain, + val derivationPath: String?, + val tokens: List +) { + + constructor(blockchain: Blockchain, card: Card) : this( + blockchain = blockchain, + derivationPath = if (card.settings.isHDWalletAllowed) blockchain.derivationPath(card.derivationStyle)?.rawPath else null, + tokens = emptyList() + ) + + + fun updateTokens(tokens: List): BlockchainNetwork { + return copy( + tokens = (this.tokens + tokens).distinct() + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as BlockchainNetwork + + if (blockchain != other.blockchain) return false + if (derivationPath != other.derivationPath) return false + + return true + } + + override fun hashCode(): Int = calculateHashCode( + blockchain.hashCode(), derivationPath?.hashCode() ?: 0 + ) + + companion object { + fun fromWalletManager(walletManager: WalletManager): BlockchainNetwork { + return BlockchainNetwork( + walletManager.wallet.blockchain, + walletManager.wallet.publicKey.derivationPath?.rawPath, + walletManager.cardTokens.toList() + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/models/ObsoleteTokenDao.kt b/app/src/main/java/com/tangem/tap/domain/tokens/models/ObsoleteTokenDao.kt new file mode 100644 index 0000000000..19d8bbf73d --- /dev/null +++ b/app/src/main/java/com/tangem/tap/domain/tokens/models/ObsoleteTokenDao.kt @@ -0,0 +1,24 @@ +package com.tangem.tap.domain.tokens.models + +import com.squareup.moshi.JsonClass +import com.tangem.blockchain.common.Blockchain + +@JsonClass(generateAdapter = true) +data class ObsoleteTokenDao( + val name: String, + val symbol: String, + val contractAddress: String, + val decimalCount: Int, + val customIconUrl: String?, +) { + fun toTokenDao(blockchain: Blockchain): TokenDao { + return TokenDao( + name = name, + symbol = symbol, + contractAddress = contractAddress, + decimalCount = decimalCount, + blockchainDao = BlockchainDao.fromBlockchain(blockchain), + customIconUrl = customIconUrl + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/domain/tokens/models/TokenDao.kt b/app/src/main/java/com/tangem/tap/domain/tokens/models/TokenDao.kt new file mode 100644 index 0000000000..a8a717b1ce --- /dev/null +++ b/app/src/main/java/com/tangem/tap/domain/tokens/models/TokenDao.kt @@ -0,0 +1,30 @@ +package com.tangem.tap.domain.tokens.models + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +import com.tangem.blockchain.common.Token +import com.tangem.tap.domain.extensions.setCustomIconUrl + +@JsonClass(generateAdapter = true) +data class TokenDao( + val name: String, + val symbol: String, + val contractAddress: String, + val decimalCount: Int, + @Json(name = "blockchain") + val blockchainDao: BlockchainDao, + val customIconUrl: String? = null, + val type: String? = null +) { + fun toToken(): Token { + return Token( + name = name, + symbol = symbol, + contractAddress = contractAddress, + decimals = decimalCount, + ).apply { + customIconUrl?.let { this.setCustomIconUrl(it) } + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/details/redux/DetailsReducer.kt b/app/src/main/java/com/tangem/tap/features/details/redux/DetailsReducer.kt index 5b6eaa198f..45910f64c4 100644 --- a/app/src/main/java/com/tangem/tap/features/details/redux/DetailsReducer.kt +++ b/app/src/main/java/com/tangem/tap/features/details/redux/DetailsReducer.kt @@ -7,8 +7,7 @@ import com.tangem.domain.common.isTangemTwin import com.tangem.tap.common.redux.AppState import com.tangem.tap.domain.extensions.isWalletDataSupported import com.tangem.tap.domain.extensions.signedHashesCount -import com.tangem.tap.domain.extensions.toSendableAmounts -import com.tangem.tap.features.wallet.models.hasPendingTransactions +import com.tangem.tap.features.wallet.models.hasSendableAmountsOrPendingTransactions import org.rekotlin.Action import java.util.* @@ -62,9 +61,7 @@ private fun handleEraseWallet( (card?.isWalletDataSupported == true && (!state.scanResponse.isTangemNote() && !state.scanResponse.supportsBackup())) - val notEmpty = state.wallets.any { - it.hasPendingTransactions() || it.amounts.toSendableAmounts().isNotEmpty() - } + val notEmpty = state.wallets.any { it.hasSendableAmountsOrPendingTransactions() } val eraseWalletState = when { notAllowedByCard -> EraseWalletState.NotAllowedByCard notEmpty -> EraseWalletState.NotEmpty diff --git a/app/src/main/java/com/tangem/tap/features/details/redux/walletconnect/WalletConnectMiddleware.kt b/app/src/main/java/com/tangem/tap/features/details/redux/walletconnect/WalletConnectMiddleware.kt index cb9b4061b5..8dbaafc988 100644 --- a/app/src/main/java/com/tangem/tap/features/details/redux/walletconnect/WalletConnectMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/details/redux/walletconnect/WalletConnectMiddleware.kt @@ -16,15 +16,17 @@ import com.tangem.tap.common.redux.navigation.NavigationAction import com.tangem.tap.currenciesRepository import com.tangem.tap.domain.extensions.isMultiwalletAllowed import com.tangem.tap.domain.extensions.makeWalletManagerForApp -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.domain.walletconnect.BnbHelper import com.tangem.tap.domain.walletconnect.WalletConnectManager import com.tangem.tap.domain.walletconnect.WalletConnectNetworkUtils import com.tangem.tap.features.demo.DemoHelper import com.tangem.tap.features.wallet.redux.Currency import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.scope import com.tangem.tap.store import com.tangem.wallet.R +import kotlinx.coroutines.launch import org.rekotlin.Action import org.rekotlin.Middleware @@ -257,14 +259,16 @@ class WalletConnectMiddleware { blockchainToMake, card.derivationStyle?.let { DerivationParams.Default(it) } ) - if (currenciesRepository.loadSavedCurrencies(card.cardId, card.settings.isHDWalletAllowed) - .find { it.blockchain == blockchainToMake } != null - ) { - walletManager?.let { - currenciesRepository.saveUpdatedCurrency( - card.cardId, - BlockchainNetwork.fromWalletManager(walletManager) - ) + scope.launch { + if (currenciesRepository.loadSavedCurrencies(card.cardId, card.settings.isHDWalletAllowed) + .find { it.blockchain == blockchainToMake } != null + ) { + walletManager?.let { + currenciesRepository.saveUpdatedCurrency( + card.cardId, + BlockchainNetwork.fromWalletManager(walletManager) + ) + } } } return walletManager diff --git a/app/src/main/java/com/tangem/tap/features/home/compose/FirstStoriesContent.kt b/app/src/main/java/com/tangem/tap/features/home/compose/FirstStoriesContent.kt index 6bb3d25b87..30e72ec626 100644 --- a/app/src/main/java/com/tangem/tap/features/home/compose/FirstStoriesContent.kt +++ b/app/src/main/java/com/tangem/tap/features/home/compose/FirstStoriesContent.kt @@ -8,7 +8,11 @@ import androidx.compose.animation.core.tween import androidx.compose.animation.scaleIn import androidx.compose.animation.slideInVertically import androidx.compose.foundation.Image -import androidx.compose.foundation.layout.* +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf diff --git a/app/src/main/java/com/tangem/tap/features/send/redux/middlewares/SendMiddleware.kt b/app/src/main/java/com/tangem/tap/features/send/redux/middlewares/SendMiddleware.kt index 795e331174..1727c81944 100644 --- a/app/src/main/java/com/tangem/tap/features/send/redux/middlewares/SendMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/send/redux/middlewares/SendMiddleware.kt @@ -24,7 +24,7 @@ import com.tangem.tap.domain.TangemSigner import com.tangem.tap.domain.TapError import com.tangem.tap.domain.configurable.warningMessage.WarningMessage import com.tangem.tap.domain.extensions.minimalAmount -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.demo.DemoTransactionSender import com.tangem.tap.features.demo.isDemoWallet import com.tangem.tap.features.send.redux.* diff --git a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensAction.kt b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensAction.kt index e95dc24e86..72d7919766 100644 --- a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensAction.kt +++ b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensAction.kt @@ -17,7 +17,8 @@ sealed class TokensAction : Action { val supportedBlockchains: List? = null, val scanResponse: ScanResponse? = null ) : TokensAction() { - data class Success(val currencies: List) : TokensAction() + data class Success(val currencies: List, val loadMore: Boolean) : TokensAction() + object Failure : TokensAction() } data class SetAddedCurrencies( @@ -32,4 +33,6 @@ sealed class TokensAction : Action { ) : TokensAction() object PrepareAndNavigateToAddCustomToken : TokensAction() + + data class SetSearchInput(val searchInput: String) : TokensAction() } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensMiddleware.kt b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensMiddleware.kt index 1c91c67b5f..48f848e65a 100644 --- a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensMiddleware.kt @@ -8,11 +8,13 @@ import com.tangem.common.card.EllipticCurve import com.tangem.common.extensions.ByteArrayKey import com.tangem.common.extensions.toMapKey import com.tangem.common.hdWallet.DerivationPath +import com.tangem.common.services.Result import com.tangem.domain.DomainWrapped import com.tangem.domain.common.KeyWalletPublicKey import com.tangem.domain.common.ScanResponse import com.tangem.domain.common.TapWorkarounds.derivationStyle import com.tangem.domain.common.TapWorkarounds.isTestCard +import com.tangem.domain.common.extensions.supportedBlockchains import com.tangem.domain.features.addCustomToken.CustomCurrency import com.tangem.domain.features.addCustomToken.redux.AddCustomTokenAction import com.tangem.domain.redux.domainStore @@ -26,10 +28,10 @@ import com.tangem.tap.common.redux.navigation.AppScreen import com.tangem.tap.common.redux.navigation.NavigationAction import com.tangem.tap.domain.TapError import com.tangem.tap.domain.extensions.makeWalletManagerForApp -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.LoadAvailableCoinsService +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.wallet.redux.Currency import com.tangem.tap.features.wallet.redux.WalletAction -import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.rekotlin.Middleware @@ -40,26 +42,65 @@ class TokensMiddleware { { next -> { action -> when (action) { - is TokensAction.LoadCurrencies -> handleLoadCurrencies(action) + is TokensAction.LoadCurrencies -> handleLoadCurrencies(action.scanResponse) is TokensAction.SaveChanges -> handleSaveChanges(action) - is TokensAction.PrepareAndNavigateToAddCustomToken -> handleAddingCustomToken(action) + is TokensAction.PrepareAndNavigateToAddCustomToken -> handleAddingCustomToken( + action + ) + is TokensAction.SetSearchInput -> { + handleLoadCurrencies( + scanResponse = store.state.globalState.scanResponse, + action.searchInput + ) + } + } next(action) } } } - private fun handleLoadCurrencies(action: TokensAction.LoadCurrencies) { - val scanResponse = store.state.globalState.scanResponse + private fun handleLoadCurrencies(scanResponse: ScanResponse?, newSearchInput: String? = null) { + val tokensState = store.state.tokensState + val isTestcard = scanResponse?.card?.isTestCard ?: false + val supportedBlockchains: List = + scanResponse?.card?.supportedBlockchains() ?: Blockchain.values().toList() + .filter { !it.isTestnet() } + + val loadCoinsService = LoadAvailableCoinsService( + store.state.domainNetworks.tangemTechService, + currenciesRepository + ) + scope.launch { - val currencies = async { - currenciesRepository.getSupportedTokens(isTestcard) - .filter(action.supportedBlockchains?.toSet()) + + val loadCoinsResult = if (newSearchInput == null) { + loadCoinsService.getSupportedTokens( + isTestcard, + supportedBlockchains, + tokensState.pageToLoad, + tokensState.searchInput + ) + } else { + loadCoinsService.getSupportedTokens( + isTestcard, supportedBlockchains, 0, newSearchInput.ifBlank { null } + ) } - delay(600) - store.dispatchOnMain(TokensAction.LoadCurrencies.Success(currencies.await())) + when (loadCoinsResult) { + is Result.Success -> { + val currencies = loadCoinsResult.data.currencies + .filter(supportedBlockchains.toSet()) + store.dispatchOnMain( + TokensAction.LoadCurrencies.Success( + currencies, loadCoinsResult.data.moreAvailable + ) + ) + } + is Result.Failure -> store.dispatchOnMain(TokensAction.LoadCurrencies.Failure) + } + } } @@ -74,7 +115,8 @@ class TokensMiddleware { ) val blockchainsToAdd = action.addedBlockchains.filter { !currentBlockchains.contains(it) } - val blockchainsToRemove = currentBlockchains.filter { !action.addedBlockchains.contains(it) } + val blockchainsToRemove = + currentBlockchains.filter { !action.addedBlockchains.contains(it) } val tokensToAdd = action.addedTokens.filter { !currentTokens.contains(it) } val tokensToRemove = currentTokens.filter { token -> @@ -82,11 +124,13 @@ class TokensMiddleware { } val derivationStyle = scanResponse.card.derivationStyle - removeCurrenciesIfNeeded(convertToCurrencies( - blockchains = blockchainsToRemove, - tokens = tokensToRemove, - derivationStyle = derivationStyle - )) + removeCurrenciesIfNeeded( + convertToCurrencies( + blockchains = blockchainsToRemove, + tokens = tokensToRemove, + derivationStyle = derivationStyle + ) + ) if (tokensToAdd.isEmpty() && blockchainsToAdd.isEmpty()) { store.dispatchDebugErrorNotification("Nothing to save") @@ -246,7 +290,8 @@ class TokensMiddleware { val rawDerivationPath = currency.derivationPath ?: currency.blockchain.derivationPath(derivationStyle)?.rawPath - val blockchainNetwork = BlockchainNetwork(currency.blockchain, rawDerivationPath, emptyList()) + val blockchainNetwork = + BlockchainNetwork(currency.blockchain, rawDerivationPath, emptyList()) WalletAction.MultiWallet.AddToken(currency.token, blockchainNetwork) } } @@ -297,8 +342,15 @@ class TokensMiddleware { walletStore.walletsData.map { walletData -> walletData.currency } }.flatten().map { when (it) { - is Currency.Blockchain -> DomainWrapped.Currency.Blockchain(it.blockchain, it.derivationPath) - is Currency.Token -> DomainWrapped.Currency.Token(it.token, it.blockchain, it.derivationPath) + is Currency.Blockchain -> DomainWrapped.Currency.Blockchain( + it.blockchain, + it.derivationPath + ) + is Currency.Token -> DomainWrapped.Currency.Token( + it.token, + it.blockchain, + it.derivationPath + ) } } domainStore.dispatch(AddCustomTokenAction.Init.SetAddedCurrencies(addedCurrencies)) diff --git a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensReducer.kt b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensReducer.kt index 6ac0dbd968..374f6ad820 100644 --- a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensReducer.kt +++ b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensReducer.kt @@ -15,9 +15,24 @@ private fun internalReduce(action: Action, state: AppState): TokensState { val tokensState = state.tokensState return when (action) { is TokensAction.ResetState -> TokensState() - is TokensAction.LoadCurrencies -> tokensState.copy(scanResponse = action.scanResponse) + is TokensAction.LoadCurrencies -> { + val loadingState = if (tokensState.currencies.isEmpty()) { + LoadCoinsState.LOADING + } else { + LoadCoinsState.LOADED + } + tokensState.copy( + scanResponse = action.scanResponse, + loadCoinsState = loadingState + ) + } is TokensAction.LoadCurrencies.Success -> { - tokensState.copy(currencies = action.currencies) + tokensState.copy( + currencies = tokensState.currencies + action.currencies, + needToLoadMore = action.loadMore, + pageToLoad = tokensState.pageToLoad + 1, + loadCoinsState = LoadCoinsState.LOADED + ) } is TokensAction.SetAddedCurrencies -> { @@ -38,6 +53,15 @@ private fun internalReduce(action: Action, state: AppState): TokensState { is TokensAction.AllowToAddTokens -> { tokensState.copy(allowToAdd = action.allow) } + is TokensAction.SetSearchInput -> { + tokensState.copy( + searchInput = action.searchInput.ifBlank { null }, + needToLoadMore = true, + currencies = emptyList(), + pageToLoad = 0, + loadCoinsState = LoadCoinsState.LOADING + ) + } else -> tokensState } } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensState.kt b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensState.kt index 6c8e6a58e8..1c60655d24 100644 --- a/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensState.kt +++ b/app/src/main/java/com/tangem/tap/features/tokens/redux/TokensState.kt @@ -17,9 +17,13 @@ data class TokensState( val nonRemovableTokens: List = emptyList(), val nonRemovableBlockchains: List = emptyList(), val currencies: List = emptyList(), + val searchInput: String? = null, val allowToAdd: Boolean = true, val derivationStyle: DerivationStyle? = null, - val scanResponse: ScanResponse? = null + val scanResponse: ScanResponse? = null, + val needToLoadMore: Boolean = true, + val pageToLoad: Int = 0, + val loadCoinsState: LoadCoinsState = LoadCoinsState.LOADING, ) : StateType { fun canHandleToken(token: TokenWithBlockchain): Boolean { @@ -74,4 +78,8 @@ fun List.filter(supportedBlockchains: Set?): List = mutableStateOf(store.state.tokensState), - searchInput: MutableState, onSaveChanges: (List, List) -> Unit, - onNetworkItemClicked: (ContractAddress) -> Unit + onNetworkItemClicked: (ContractAddress) -> Unit, + onLoadMore: () -> Unit ) { val context = LocalContext.current val addedTokensState = remember { mutableStateOf(tokensState.value.addedTokens) } @@ -76,7 +77,7 @@ fun CurrenciesScreen( ) { AnimatedVisibility( - visible = tokensState.value.currencies.isEmpty(), + visible = tokensState.value.loadCoinsState == LoadCoinsState.LOADING, enter = fadeIn(), exit = fadeOut() ) { @@ -90,7 +91,7 @@ fun CurrenciesScreen( } } AnimatedVisibility( - visible = tokensState.value.currencies.isNotEmpty(), + visible = tokensState.value.loadCoinsState == LoadCoinsState.LOADED, enter = fadeIn(animationSpec = tween(1000)), exit = fadeOut(animationSpec = tween(1000)) ) { @@ -103,7 +104,6 @@ fun CurrenciesScreen( nonRemovableBlockchains = tokensState.value.nonRemovableBlockchains, addedTokens = addedTokensState.value, addedBlockchains = addedBlockchainsState.value, - searchInput = searchInput.value, allowToAdd = tokensState.value.allowToAdd, onAddCurrencyToggled = { currency, token -> onAddCurrencyToggleClick(currency, token) @@ -118,7 +118,8 @@ fun CurrenciesScreen( } }, - onNetworkItemClicked = onNetworkItemClicked + onNetworkItemClicked = onNetworkItemClicked, + onLoadMore = onLoadMore ) } } diff --git a/app/src/main/java/com/tangem/tap/features/tokens/ui/compose/ListOfCurrencies.kt b/app/src/main/java/com/tangem/tap/features/tokens/ui/compose/ListOfCurrencies.kt index d55cbd35a4..75755a0e73 100644 --- a/app/src/main/java/com/tangem/tap/features/tokens/ui/compose/ListOfCurrencies.kt +++ b/app/src/main/java/com/tangem/tap/features/tokens/ui/compose/ListOfCurrencies.kt @@ -3,13 +3,15 @@ package com.tangem.tap.features.tokens.ui.compose import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.tangem.blockchain.common.Blockchain +import com.tangem.tap.common.compose.extensions.OnBottomReached import com.tangem.tap.domain.tokens.Currency import com.tangem.tap.features.tokens.redux.ContractAddress import com.tangem.tap.features.tokens.redux.TokenWithBlockchain @@ -17,16 +19,16 @@ import com.tangem.tap.features.tokens.redux.TokenWithBlockchain @Composable fun ListOfCurrencies( - header: @Composable ()->Unit, + header: @Composable () -> Unit, currencies: List, nonRemovableTokens: List, nonRemovableBlockchains: List, addedTokens: List, addedBlockchains: List, - searchInput: String, allowToAdd: Boolean, onAddCurrencyToggled: (Currency, TokenWithBlockchain?) -> Unit, - onNetworkItemClicked: (ContractAddress) -> Unit + onNetworkItemClicked: (ContractAddress) -> Unit, + onLoadMore: () -> Unit ) { val expandedCurrencies = remember { mutableStateOf(listOf("")) } @@ -41,22 +43,16 @@ fun ListOfCurrencies( expandedCurrencies.value = mutableList } + val listState = rememberLazyListState() + LazyColumn( + state = listState, modifier = Modifier .fillMaxSize(), contentPadding = PaddingValues(bottom = 90.dp) ) { - - val filteredCurrencies = if (searchInput.isBlank()) { - currencies - } else { - currencies.asSequence().filter { - it.name.lowercase().contains(searchInput) || it.symbol.lowercase() - .contains(searchInput) - }.toList() - } item { header() } - items(filteredCurrencies) { currency -> + itemsIndexed(currencies) { index, currency -> CurrencyItem( currency = currency, nonRemovableTokens = nonRemovableTokens, @@ -70,8 +66,8 @@ fun ListOfCurrencies( onNetworkItemClicked = onNetworkItemClicked ) } - } + listState.OnBottomReached(loadMoreThreshold = 40) { onLoadMore() } } val Currency.fullName: String diff --git a/app/src/main/java/com/tangem/tap/features/wallet/models/PendingTransaction.kt b/app/src/main/java/com/tangem/tap/features/wallet/models/PendingTransaction.kt index 722b2c7d03..d24a3ea480 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/models/PendingTransaction.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/models/PendingTransaction.kt @@ -1,20 +1,26 @@ package com.tangem.tap.features.wallet.models -import com.tangem.blockchain.common.Token -import com.tangem.blockchain.common.TransactionData -import com.tangem.blockchain.common.TransactionStatus -import com.tangem.blockchain.common.Wallet +import com.tangem.blockchain.common.* +import com.tangem.blockchain.extensions.isAboveZero import com.tangem.tap.common.extensions.toFormattedString -import com.tangem.tap.domain.extensions.toSendableAmounts import java.math.BigDecimal data class PendingTransaction( - val address: String?, - val amount: BigDecimal?, - val amountUi: String?, - val currency: String, - val type: PendingTransactionType -) + val transactionData: TransactionData, + val type: PendingTransactionType, +) { + val address: String? = when (type) { + PendingTransactionType.Incoming -> transactionData.destinationAddress + PendingTransactionType.Outgoing -> transactionData.sourceAddress + PendingTransactionType.Unknown -> null + } + + val amountValue: BigDecimal? = transactionData.amount.value + + val amountValueUi: String? = amountValue?.toFormattedString(transactionData.amount.decimals) + + val currency: String = transactionData.amount.currencySymbol +} enum class PendingTransactionType { Incoming, Outgoing, Unknown } @@ -22,29 +28,11 @@ fun TransactionData.toPendingTransaction(walletAddress: String): PendingTransact if (this.status == TransactionStatus.Confirmed) return null val type: PendingTransactionType = when { - this.sourceAddress == walletAddress -> { - PendingTransactionType.Outgoing - } - this.destinationAddress == walletAddress -> { - PendingTransactionType.Incoming - } - else -> { - PendingTransactionType.Unknown - } + this.sourceAddress == walletAddress -> PendingTransactionType.Outgoing + this.destinationAddress == walletAddress -> PendingTransactionType.Incoming + else -> PendingTransactionType.Unknown } - val address = if (this.sourceAddress == walletAddress) { - this.destinationAddress - } else { - this.sourceAddress - } - - return PendingTransaction( - if (address == "unknown") null else address, - this.amount.value, - this.amount.value?.toFormattedString(amount.decimals), - this.amount.currencySymbol, - type - ) + return PendingTransaction(this, type) } fun List.toPendingTransactions(walletAddress: String): List { @@ -55,27 +43,58 @@ fun List.removeUnknownTransactions(): List.filterByCoin(): List { + return this.filter { it.transactionData.amount.type == AmountType.Coin } +} + +fun List.filterByToken(token: Token): List { + return this.filter { it.currency == token.symbol } +} + fun TransactionData.toPendingTransactionForToken(token: Token, walletAddress: String): PendingTransaction? { if (this.amount.currencySymbol != token.symbol) return null return this.toPendingTransaction(walletAddress) } -fun List.toPendingTransactionsForToken(token: Token, walletAddress: String): List { - return this.mapNotNull { it.toPendingTransactionForToken(token, walletAddress) } -} - fun Wallet.getPendingTransactions(type: PendingTransactionType? = null): List { val txs = recentTransactions.toPendingTransactions(address) - return when(type) { + return when (type) { null -> txs else -> txs.filter { it.type == type } } } +fun Wallet.getPendingTransactions(token: Token): List { + return recentTransactions.mapNotNull { it.toPendingTransactionForToken(token, address) } +} + fun Wallet.hasPendingTransactions(): Boolean { return getPendingTransactions().isNotEmpty() } +fun Wallet.hasPendingTransactions(token: Token): Boolean { + return getPendingTransactions(token).isNotEmpty() +} + +fun Wallet.getSendableAmounts(): List { + return amounts.values + .filter { it.type != AmountType.Reserve } + .filter { it.isAboveZero() } +} + +fun Wallet.hasSendableAmounts(): Boolean { + return getSendableAmounts().isNotEmpty() +} + fun Wallet.hasSendableAmountsOrPendingTransactions(): Boolean { - return hasPendingTransactions() || amounts.toSendableAmounts().isNotEmpty() + return hasPendingTransactions() || hasSendableAmounts() +} + +fun Wallet.isSendableAmount(type: AmountType): Boolean { + return amounts[type]?.isAboveZero() == true + +} + +fun Wallet.isSendableAmount(token: Token): Boolean { + return isSendableAmount(AmountType.Token(token)) } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletAction.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletAction.kt index ce2ce4b63d..6ca5098dd8 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletAction.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletAction.kt @@ -1,11 +1,7 @@ package com.tangem.tap.features.wallet.redux import android.content.Context -import com.tangem.blockchain.common.Amount -import com.tangem.blockchain.common.Blockchain -import com.tangem.blockchain.common.Token -import com.tangem.blockchain.common.Wallet -import com.tangem.blockchain.common.WalletManager +import com.tangem.blockchain.common.* import com.tangem.blockchain.common.address.AddressType import com.tangem.common.card.Card import com.tangem.tap.common.entities.FiatCurrency @@ -13,10 +9,10 @@ import com.tangem.tap.common.redux.ErrorAction import com.tangem.tap.common.redux.NotificationAction import com.tangem.tap.domain.TapError import com.tangem.tap.domain.configurable.warningMessage.WarningMessage -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.wallet.R -import java.math.BigDecimal import org.rekotlin.Action +import java.math.BigDecimal sealed class WalletAction : Action { @@ -121,10 +117,8 @@ sealed class WalletAction : Action { data class Send(val amount: Amount? = null) : WalletAction() { data class ChooseCurrency(val amounts: List?) : WalletAction() - object Cancel : WalletAction() } - object EmptyField : WalletAction(), ErrorAction { override val error = TapError.PayIdEmptyField } @@ -137,13 +131,18 @@ sealed class WalletAction : Action { data class ShareAddress(val address: String, val context: Context) : WalletAction() - object ShowDialog : WalletAction() { - object QrCode : WalletAction() - object SignedHashesMultiWalletDialog : WalletAction() - object ChooseTradeActionDialog : WalletAction() - } + sealed class DialogAction : WalletAction() { + data class QrCode( + val currency: Currency, + val selectedAddress: AddressData, + ) : DialogAction() - object HideDialog : WalletAction() + object SignedHashesMultiWalletDialog : DialogAction() + object ChooseTradeActionDialog : DialogAction() + data class ChooseCurrency(val amounts: List?) : DialogAction() + + object Hide : DialogAction() + } data class ExploreAddress(val exploreUrl: String, val context: Context) : WalletAction() diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletState.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletState.kt index c815b4b404..aecdd574e8 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletState.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/WalletState.kt @@ -1,20 +1,14 @@ package com.tangem.tap.features.wallet.redux import android.graphics.Bitmap -import com.tangem.blockchain.common.Amount -import com.tangem.blockchain.common.AmountType -import com.tangem.blockchain.common.Blockchain -import com.tangem.blockchain.common.DerivationStyle -import com.tangem.blockchain.common.Token -import com.tangem.blockchain.common.Wallet -import com.tangem.blockchain.common.WalletManager +import com.tangem.blockchain.common.* import com.tangem.blockchain.common.address.AddressType -import com.tangem.blockchain.extensions.isAboveZero import com.tangem.common.extensions.isZero import com.tangem.domain.common.extensions.canHandleToken import com.tangem.domain.common.extensions.toCoinId import com.tangem.domain.features.addCustomToken.CustomCurrency import com.tangem.tap.common.entities.Button +import com.tangem.tap.common.entities.FiatCurrency import com.tangem.tap.common.extensions.toQrCode import com.tangem.tap.common.redux.StateDialog import com.tangem.tap.common.redux.global.CryptoCurrencyName @@ -22,22 +16,18 @@ import com.tangem.tap.common.toggleWidget.WidgetState import com.tangem.tap.domain.configurable.warningMessage.WarningMessage import com.tangem.tap.domain.extensions.buyIsAllowed import com.tangem.tap.domain.extensions.sellIsAllowed -import com.tangem.tap.domain.extensions.toSendableAmounts -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.onboarding.products.twins.redux.TwinCardsState import com.tangem.tap.features.tokens.redux.TokenWithBlockchain -import com.tangem.tap.features.wallet.models.PendingTransaction -import com.tangem.tap.features.wallet.models.TotalBalance -import com.tangem.tap.features.wallet.models.WalletRent -import com.tangem.tap.features.wallet.models.WalletWarning -import com.tangem.tap.features.wallet.models.toPendingTransactions -import com.tangem.tap.features.wallet.models.toPendingTransactionsForToken +import com.tangem.tap.features.wallet.models.* +import com.tangem.tap.features.wallet.redux.reducers.calculateTotalFiatAmount +import com.tangem.tap.features.wallet.redux.reducers.findTotalBalanceState import com.tangem.tap.features.wallet.ui.BalanceStatus import com.tangem.tap.features.wallet.ui.BalanceWidgetData import com.tangem.tap.network.exchangeServices.CurrencyExchangeManager import com.tangem.tap.store -import java.math.BigDecimal import org.rekotlin.StateType +import java.math.BigDecimal import kotlin.properties.ReadOnlyProperty data class WalletState( @@ -45,7 +35,6 @@ data class WalletState( val error: ErrorType? = null, val cardImage: Artwork? = null, val hashesCountVerified: Boolean? = null, - val walletDialog: StateDialog? = null, val mainWarningsList: List = mutableListOf(), val wallets: List = listOf(), val isMultiwalletAllowed: Boolean = false, @@ -151,16 +140,13 @@ data class WalletState( val wallet = walletManager.wallet - if (walletData.currency is Currency.Blockchain) { - return wallet.recentTransactions.toPendingTransactions(wallet.address).isEmpty() && - wallet.amounts.toSendableAmounts().isEmpty() - } else if (walletData.currency is Currency.Token) ( - return wallet.recentTransactions.toPendingTransactionsForToken( - walletData.currency.token, wallet.address - ).isEmpty() - && wallet.amounts[AmountType.Token(token = walletData.currency.token)] - ?.isAboveZero() != true - ) + return when (walletData.currency) { + is Currency.Blockchain -> !wallet.hasPendingTransactions() && !wallet.hasSendableAmounts() + is Currency.Token -> { + val token = walletData.currency.token + !wallet.hasPendingTransactions(token) && !wallet.isSendableAmount(token) + } + } } return false } @@ -200,11 +186,11 @@ data class WalletState( .distinct().map { getWalletStore(it) }.mapNotNull { it?.updateWallets(walletsData) } return updateWalletStores(walletStores) - } fun updateWalletStore(walletStore: WalletStore?): WalletState { return copy(wallets = replaceWalletInWallets(walletStore)) + .updateTotalBalance() } private fun updateWalletStores(walletStores: List): WalletState { @@ -221,6 +207,7 @@ data class WalletState( } } return copy(wallets = updatedWallets + walletStoresMutable) + .updateTotalBalance() } fun removeWallet(walletData: WalletData?): WalletState { @@ -282,19 +269,30 @@ data class WalletState( } } - fun updateTotalBalance( - totalBalance: TotalBalance? - ): WalletState { - return this.copy( - totalBalance = totalBalance + private fun updateTotalBalance(): WalletState { + return if (wallets.isNotEmpty()) { + val walletsData = wallets.flatMap(WalletStore::walletsData) + this.copy( + totalBalance = TotalBalance( + state = walletsData.findTotalBalanceState(), + fiatAmount = walletsData.calculateTotalFiatAmount(), + fiatCurrency = store.state.globalState.appCurrency + ) + ) + } else this.copy( + totalBalance = null ) } } -sealed class WalletDialog : StateDialog { - data class SelectAmountToSendDialog(val amounts: List?) : WalletDialog() - object SignedHashesMultiWalletDialog : WalletDialog() - object ChooseTradeActionDialog : WalletDialog() +sealed interface WalletDialog : StateDialog { + data class SelectAmountToSendDialog(val amounts: List?) : WalletDialog + object SignedHashesMultiWalletDialog : WalletDialog + object ChooseTradeActionDialog : WalletDialog + data class CurrencySelectionDialog( + val currenciesList: List, + val currentAppCurrency: FiatCurrency, + ) : WalletDialog } enum class ProgressState : WidgetState { Loading, Done, Error } @@ -373,7 +371,11 @@ data class WalletData( return listOfAddresses.size > 1 } - fun shouldEnableTokenSendButton(): Boolean = !blockchainAmountIsEmpty() || !tokenAmountIsEmpty() + fun shouldEnableTokenSendButton(): Boolean = if (blockchainAmountIsEmpty()) { + false + } else { + !tokenAmountIsEmpty() + } fun assembleWarnings(): List { val blockchain = currency.blockchain @@ -396,10 +398,11 @@ data class WalletData( val fullName = currency.blockchain.fullName walletWarnings.add(WalletWarning.BalanceNotEnoughForFee(fullName)) } + return walletWarnings.sortedBy { it.showingPosition } } - private fun blockchainAmountIsEmpty(): Boolean = currencyData.blockchainAmount?.isZero() ?: false + private fun blockchainAmountIsEmpty(): Boolean = currencyData.blockchainAmount?.isZero() == true private fun tokenAmountIsEmpty(): Boolean = currencyData.amount?.isZero() == true } diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/AppCurrencyMiddleware.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/AppCurrencyMiddleware.kt index 3c9c87e9f8..904aecab65 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/AppCurrencyMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/AppCurrencyMiddleware.kt @@ -5,10 +5,10 @@ import com.tangem.network.api.tangemTech.CurrenciesResponse import com.tangem.network.api.tangemTech.TangemTechService import com.tangem.tap.common.entities.FiatCurrency import com.tangem.tap.common.extensions.dispatchDialogShow -import com.tangem.tap.common.redux.AppDialog import com.tangem.tap.common.redux.global.GlobalAction import com.tangem.tap.domain.TapWalletManager import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletDialog import com.tangem.tap.persistence.FiatCurrenciesPrefStorage import com.tangem.tap.scope import com.tangem.tap.store @@ -31,7 +31,7 @@ class AppCurrencyMiddleware( val storedFiatCurrencies = fiatCurrenciesPrefStorage.restore() if (storedFiatCurrencies.isNotEmpty()) { store.dispatchDialogShow( - AppDialog.CurrencySelectionDialog( + WalletDialog.CurrencySelectionDialog( currenciesList = storedFiatCurrencies.mapToUiModel(), currentAppCurrency = appCurrencyProvider.invoke() ) @@ -47,7 +47,7 @@ class AppCurrencyMiddleware( ) { fiatCurrenciesPrefStorage.save(currenciesList) store.dispatchDialogShow( - AppDialog.CurrencySelectionDialog( + WalletDialog.CurrencySelectionDialog( currenciesList = currenciesList.mapToUiModel(), currentAppCurrency = appCurrencyProvider.invoke() ) diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/MultiWalletMiddleware.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/MultiWalletMiddleware.kt index 22ce291074..ace70c1988 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/MultiWalletMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/MultiWalletMiddleware.kt @@ -9,7 +9,7 @@ import com.tangem.tap.common.redux.navigation.AppScreen import com.tangem.tap.common.redux.navigation.NavigationAction import com.tangem.tap.currenciesRepository import com.tangem.tap.domain.extensions.makeWalletManagerForApp -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.demo.DemoHelper import com.tangem.tap.features.demo.isDemoCard import com.tangem.tap.features.wallet.redux.Currency diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/TradeCryptoMiddleware.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/TradeCryptoMiddleware.kt index 45e34c15f9..3e4210fe42 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/TradeCryptoMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/TradeCryptoMiddleware.kt @@ -2,6 +2,7 @@ package com.tangem.tap.features.wallet.redux.middlewares import com.tangem.blockchain.blockchains.ethereum.EthereumWalletManager import com.tangem.blockchain.common.AmountType +import com.tangem.tap.common.extensions.dispatchDebugErrorNotification import com.tangem.tap.common.extensions.dispatchOnMain import com.tangem.tap.common.redux.AppState import com.tangem.tap.common.redux.navigation.AppScreen @@ -51,7 +52,10 @@ class TradeCryptoMiddleware { currency is Currency.Token && currency.blockchain.isTestnet() ) { val walletManager = store.state.walletState.getWalletManager(currency) - if (walletManager !is EthereumWalletManager) return + if (walletManager !is EthereumWalletManager) { + store.dispatchDebugErrorNotification("Testnet tokens available only for the ETH") + return + } scope.launch { exchangeManager.buyErc20Tokens(walletManager, currency.token) } return diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletDialogsMiddleware.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletDialogsMiddleware.kt new file mode 100644 index 0000000000..e495c55c94 --- /dev/null +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletDialogsMiddleware.kt @@ -0,0 +1,39 @@ +package com.tangem.tap.features.wallet.redux.middlewares + +import com.tangem.tap.common.extensions.dispatchDialogHide +import com.tangem.tap.common.extensions.dispatchDialogShow +import com.tangem.tap.common.redux.AppDialog +import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletDialog +import com.tangem.tap.store + +class WalletDialogsMiddleware { + fun handle(action: WalletAction.DialogAction) { + when (action) { + is WalletAction.DialogAction.SignedHashesMultiWalletDialog -> { + store.dispatchDialogShow(WalletDialog.SignedHashesMultiWalletDialog) + } + is WalletAction.DialogAction.ChooseTradeActionDialog -> { + store.dispatchDialogShow(WalletDialog.ChooseTradeActionDialog) + } + is WalletAction.DialogAction.QrCode -> { + store.dispatchDialogShow( + AppDialog.AddressInfoDialog( + currency = action.currency, + addressData = action.selectedAddress, + ) + ) + } + is WalletAction.DialogAction.ChooseCurrency -> { + store.dispatchDialogShow( + WalletDialog.SelectAmountToSendDialog( + amounts = action.amounts + ) + ) + } + is WalletAction.DialogAction.Hide -> { + store.dispatchDialogHide() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletMiddleware.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletMiddleware.kt index e2d7c6d4b5..a4862b21b8 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletMiddleware.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/middlewares/WalletMiddleware.kt @@ -15,19 +15,11 @@ import com.tangem.domain.common.extensions.withMainContext import com.tangem.operations.attestation.Attestation import com.tangem.operations.attestation.OnlineCardVerifier import com.tangem.tap.common.analytics.Analytics -import com.tangem.tap.common.extensions.copyToClipboard -import com.tangem.tap.common.extensions.dispatchDebugErrorNotification -import com.tangem.tap.common.extensions.dispatchDialogShow -import com.tangem.tap.common.extensions.dispatchOnMain -import com.tangem.tap.common.extensions.onCardScanned -import com.tangem.tap.common.extensions.shareText -import com.tangem.tap.common.extensions.stripZeroPlainString -import com.tangem.tap.common.redux.AppDialog +import com.tangem.tap.common.extensions.* import com.tangem.tap.common.redux.AppState import com.tangem.tap.common.redux.global.GlobalAction import com.tangem.tap.common.redux.navigation.AppScreen import com.tangem.tap.common.redux.navigation.NavigationAction -import com.tangem.tap.domain.extensions.toSendableAmounts import com.tangem.tap.domain.failedRates import com.tangem.tap.domain.loadedRates import com.tangem.tap.features.demo.DemoHelper @@ -35,17 +27,13 @@ import com.tangem.tap.features.home.redux.HomeAction import com.tangem.tap.features.send.redux.PrepareSendScreen import com.tangem.tap.features.wallet.models.PendingTransactionType import com.tangem.tap.features.wallet.models.getPendingTransactions -import com.tangem.tap.features.wallet.redux.Currency -import com.tangem.tap.features.wallet.redux.WalletAction -import com.tangem.tap.features.wallet.redux.WalletData -import com.tangem.tap.features.wallet.redux.WalletState -import com.tangem.tap.features.wallet.redux.WalletStore +import com.tangem.tap.features.wallet.models.getSendableAmounts +import com.tangem.tap.features.wallet.redux.* import com.tangem.tap.network.NetworkStateChanged import com.tangem.tap.preferencesStorage import com.tangem.tap.scope import com.tangem.tap.store import com.tangem.tap.tangemSdkManager -import java.math.BigDecimal import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch @@ -53,11 +41,13 @@ import org.rekotlin.Action import org.rekotlin.DispatchFunction import org.rekotlin.Middleware import timber.log.Timber +import java.math.BigDecimal class WalletMiddleware { private val tradeCryptoMiddleware = TradeCryptoMiddleware() private val warningsMiddleware = WarningsMiddleware() private val multiWalletMiddleware = MultiWalletMiddleware() + private val walletDialogMiddleware = WalletDialogsMiddleware() private val appCurrencyMiddleware by lazy(mode = LazyThreadSafetyMode.NONE) { AppCurrencyMiddleware( tangemTechService = store.state.domainNetworks.tangemTechService, @@ -91,6 +81,7 @@ class WalletMiddleware { globalState ) is WalletAction.AppCurrencyAction -> appCurrencyMiddleware.handle(action) + is WalletAction.DialogAction -> walletDialogMiddleware.handle(action) is WalletAction.LoadWallet -> { scope.launch { if (action.blockchain == null) { @@ -242,15 +233,6 @@ class WalletMiddleware { store.dispatch(NavigationAction.NavigateTo(AppScreen.Send)) } } - is WalletAction.ShowDialog.QrCode -> { - val selectedWalletData = - walletState.getWalletData(walletState.selectedCurrency) ?: return - val selectedAddressData = - selectedWalletData.walletAddresses?.selectedAddress ?: return - - val currency = selectedWalletData.currency - store.dispatchDialogShow(AppDialog.AddressInfoDialog(currency, selectedAddressData)) - } } } @@ -266,13 +248,13 @@ class WalletMiddleware { PrepareSendScreen(amount, selectedWalletData?.fiatRate, walletStore?.walletManager) } } else { - val amounts = walletStore?.walletManager?.wallet?.amounts?.toSendableAmounts() + val amounts = walletStore?.walletManager?.wallet?.getSendableAmounts() if (currency != null && state.isMultiwalletAllowed) { when (currency) { is Currency.Blockchain -> { val amountToSend = amounts?.find { it.currencySymbol == currency.blockchain.currency } - ?: return WalletAction.Send.ChooseCurrency(amounts) + ?: return WalletAction.DialogAction.ChooseCurrency(amounts) PrepareSendScreen( coinAmount = amountToSend, coinRate = selectedWalletData.fiatRate, @@ -282,7 +264,7 @@ class WalletMiddleware { is Currency.Token -> { val amountToSend = amounts?.find { it.currencySymbol == currency.token.symbol } - ?: return WalletAction.Send.ChooseCurrency(amounts) + ?: return WalletAction.DialogAction.ChooseCurrency(amounts) prepareSendActionForToken( amount = amountToSend, state = state, @@ -345,7 +327,7 @@ class WalletMiddleware { val show = if (outgoingTxs.isEmpty()) { isNeedToShowWarning(balance, rentExempt) } else { - val outgoingAmount = outgoingTxs.sumOf { it.amount ?: BigDecimal.ZERO } + val outgoingAmount = outgoingTxs.sumOf { it.amountValue ?: BigDecimal.ZERO } val rest = balance.minus(outgoingAmount) isNeedToShowWarning(rest, rentExempt) } diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/MultiWalletReducer.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/MultiWalletReducer.kt index a7437c94eb..28a7675472 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/MultiWalletReducer.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/MultiWalletReducer.kt @@ -2,15 +2,22 @@ package com.tangem.tap.features.wallet.redux.reducers import com.tangem.blockchain.common.AmountType import com.tangem.blockchain.common.Token +import com.tangem.blockchain.extensions.isAboveZero import com.tangem.common.extensions.guard -import com.tangem.common.extensions.isZero import com.tangem.tap.common.extensions.toFiatString import com.tangem.tap.common.extensions.toFormattedCurrencyString import com.tangem.tap.domain.getFirstToken -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork +import com.tangem.tap.features.wallet.models.filterByToken +import com.tangem.tap.features.wallet.models.getPendingTransactions import com.tangem.tap.features.wallet.models.removeUnknownTransactions import com.tangem.tap.features.wallet.models.toPendingTransactions -import com.tangem.tap.features.wallet.redux.* +import com.tangem.tap.features.wallet.redux.Currency +import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletData +import com.tangem.tap.features.wallet.redux.WalletMainButton +import com.tangem.tap.features.wallet.redux.WalletState +import com.tangem.tap.features.wallet.redux.WalletStore import com.tangem.tap.features.wallet.ui.BalanceStatus import com.tangem.tap.features.wallet.ui.BalanceWidgetData import com.tangem.tap.features.wallet.ui.TokenData @@ -106,17 +113,16 @@ class MultiWalletReducer { throw NullPointerException("MultiWallet.TokenLoaded: WalletManager must be no NULL") } - val pendingTransactions = wallet.recentTransactions.toPendingTransactions(wallet.address) - val sendButtonEnabled = - action.amount.value?.isZero() == false && pendingTransactions.isEmpty() - val tokenPendingTransactions = pendingTransactions - .filter { it.currency == action.amount.currencySymbol } + val pendingTransactions = wallet.getPendingTransactions() + val tokenPendingTransactions = pendingTransactions.filterByToken(action.token) val tokenBalanceStatus = when { tokenPendingTransactions.isNotEmpty() -> BalanceStatus.TransactionInProgress pendingTransactions.isNotEmpty() -> BalanceStatus.SameCurrencyTransactionInProgress else -> BalanceStatus.VerifiedOnline } val tokenWalletData = state.getWalletData(currency) + val isTokenSendButtonEnabled = action.amount.isAboveZero() && pendingTransactions.isEmpty() + val newTokenWalletData = tokenWalletData?.copy( currencyData = tokenWalletData.currencyData.copy( status = tokenBalanceStatus, @@ -126,12 +132,12 @@ class MultiWalletReducer { ), fiatAmountFormatted = tokenWalletData.fiatRate?.let { action.amount.value - ?.toFiatString(it, store.state.globalState.appCurrency.code) + ?.toFiatString(it, store.state.globalState.appCurrency.symbol) }, blockchainAmount = wallet.amounts[AmountType.Coin]?.value ?: BigDecimal.ZERO ), pendingTransactions = pendingTransactions.removeUnknownTransactions(), - mainButton = WalletMainButton.SendButton(sendButtonEnabled), + mainButton = WalletMainButton.SendButton(isTokenSendButtonEnabled), currency = Currency.Token( token = action.token, blockchain = action.blockchain.blockchain, diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/OnWalletLoadedReducer.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/OnWalletLoadedReducer.kt index ce9b5cf80a..442cbf46ec 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/OnWalletLoadedReducer.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/OnWalletLoadedReducer.kt @@ -8,10 +8,16 @@ import com.tangem.tap.common.extensions.toFiatValue import com.tangem.tap.common.extensions.toFormattedCurrencyString import com.tangem.tap.common.extensions.toFormattedFiatValue import com.tangem.tap.domain.getFirstToken -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork +import com.tangem.tap.features.wallet.models.filterByToken +import com.tangem.tap.features.wallet.models.getPendingTransactions import com.tangem.tap.features.wallet.models.removeUnknownTransactions import com.tangem.tap.features.wallet.models.toPendingTransactions -import com.tangem.tap.features.wallet.redux.* +import com.tangem.tap.features.wallet.redux.Currency +import com.tangem.tap.features.wallet.redux.ProgressState +import com.tangem.tap.features.wallet.redux.TradeCryptoState +import com.tangem.tap.features.wallet.redux.WalletMainButton +import com.tangem.tap.features.wallet.redux.WalletState import com.tangem.tap.features.wallet.ui.BalanceStatus import com.tangem.tap.features.wallet.ui.BalanceWidgetData import com.tangem.tap.features.wallet.ui.TokenData @@ -44,10 +50,8 @@ class OnWalletLoadedReducer { wallet.blockchain.currency ) - val pendingTransactions = wallet.recentTransactions - .toPendingTransactions(wallet.address) - - val coinSendButton = coinAmountValue?.isZero() == false && pendingTransactions.isEmpty() + val pendingTransactions = wallet.getPendingTransactions() + val isCoinSendButtonEnabled = coinAmountValue?.isZero() == false && pendingTransactions.isEmpty() val balanceStatus = if (pendingTransactions.isNotEmpty()) { BalanceStatus.TransactionInProgress } else { @@ -66,7 +70,7 @@ class OnWalletLoadedReducer { fiatAmountFormatted = fiatAmount?.toFormattedFiatValue(fiatCurrency.symbol) ), pendingTransactions = pendingTransactions.removeUnknownTransactions(), - mainButton = WalletMainButton.SendButton(coinSendButton), + mainButton = WalletMainButton.SendButton(isCoinSendButtonEnabled), currency = Currency.fromBlockchainNetwork(blockchainNetwork), tradeCryptoState = TradeCryptoState.from(exchangeManager, walletData), ) @@ -74,8 +78,7 @@ class OnWalletLoadedReducer { val tokens = wallet.getTokens().mapNotNull { token -> val currency = Currency.fromBlockchainNetwork(blockchainNetwork, token) val tokenWalletData = walletState.getWalletData(currency) - val tokenPendingTransactions = - pendingTransactions.filter { it.currency == token.symbol } + val tokenPendingTransactions = pendingTransactions.filterByToken(token) val tokenBalanceStatus = when { tokenPendingTransactions.isNotEmpty() -> BalanceStatus.TransactionInProgress pendingTransactions.isNotEmpty() -> BalanceStatus.SameCurrencyTransactionInProgress @@ -85,8 +88,8 @@ class OnWalletLoadedReducer { val tokenFiatAmount = tokenWalletData?.fiatRate?.let { rate -> tokenAmountValue?.toFiatValue(rate) } - val tokenSendButton = newWalletData.shouldEnableTokenSendButton() - && tokenPendingTransactions.isEmpty() + val isTokenSendButtonEnabled = newWalletData.shouldEnableTokenSendButton() + && tokenPendingTransactions.isEmpty() tokenWalletData?.copy( currencyData = tokenWalletData.currencyData.copy( status = tokenBalanceStatus, @@ -97,10 +100,10 @@ class OnWalletLoadedReducer { token.symbol ), fiatAmount = tokenFiatAmount, - fiatAmountFormatted = tokenFiatAmount?.toFormattedFiatValue(fiatCurrency.code) + fiatAmountFormatted = tokenFiatAmount?.toFormattedFiatValue(fiatCurrency.symbol) ), pendingTransactions = tokenPendingTransactions.removeUnknownTransactions(), - mainButton = WalletMainButton.SendButton(tokenSendButton), + mainButton = WalletMainButton.SendButton(isTokenSendButtonEnabled), tradeCryptoState = TradeCryptoState.from(exchangeManager, tokenWalletData), ) } @@ -114,9 +117,6 @@ class OnWalletLoadedReducer { } return walletState .updateWalletsData(wallets) - .updateTotalBalance( - totalBalance = obtainTotalBalance(wallets, fiatCurrency) - ) .copy( state = state, error = null @@ -157,7 +157,7 @@ class OnWalletLoadedReducer { val fiatAmountRaw = fiatRate?.multiply(amount)?.setScale(2, RoundingMode.DOWN) val fiatAmount = fiatRate?.let { amount?.toFiatString(it, fiatCurrencyName) } - val pendingTransactions = wallet.recentTransactions.toPendingTransactions(wallet.address) + val pendingTransactions = wallet.getPendingTransactions() val sendButtonEnabled = amount?.isZero() == false && pendingTransactions.isEmpty() val balanceStatus = if (pendingTransactions.isNotEmpty()) { BalanceStatus.TransactionInProgress diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/TotalBalanceOperations.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/TotalBalanceOperations.kt index b949fe11d9..06d91d7db0 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/TotalBalanceOperations.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/TotalBalanceOperations.kt @@ -1,37 +1,21 @@ package com.tangem.tap.features.wallet.redux.reducers -import com.tangem.tap.common.entities.FiatCurrency import com.tangem.tap.features.wallet.models.TotalBalance import com.tangem.tap.features.wallet.redux.WalletData import com.tangem.tap.features.wallet.ui.BalanceStatus import java.math.BigDecimal -fun obtainTotalBalance( - wallets: List, - appCurrency: FiatCurrency -): TotalBalance? { - return if (wallets.isNotEmpty()) { - TotalBalance( - state = wallets.findTotalBalanceState(), - fiatAmount = wallets.calculateTotalFiatAmount(), - fiatCurrency = appCurrency - ) - } else null -} - -private fun List.findTotalBalanceState(): TotalBalance.State { +fun List.findTotalBalanceState(): TotalBalance.State { return this.mapToTotalBalanceState() - .fold(initial = TotalBalance.State.Loading) { accState, newState -> - accState or newState - } + .reduce(TotalBalance.State::or) } -private fun List.calculateTotalFiatAmount(): BigDecimal { +fun List.calculateTotalFiatAmount(): BigDecimal { return this.map { it.currencyData.fiatAmount ?: BigDecimal.ZERO } .reduce(BigDecimal::plus) } -private fun List.mapToTotalBalanceState(): List { +fun List.mapToTotalBalanceState(): List { return this.map { when (it.currencyData.status) { BalanceStatus.VerifiedOnline, @@ -50,9 +34,9 @@ private fun List.mapToTotalBalanceState(): List infix fun TotalBalance.State.or(newState: TotalBalance.State): TotalBalance.State { return when (this) { TotalBalance.State.Loading -> when (newState) { - TotalBalance.State.Loading -> this + TotalBalance.State.Loading, TotalBalance.State.SomeTokensFailed, - TotalBalance.State.Success -> newState + TotalBalance.State.Success -> this } TotalBalance.State.Success, TotalBalance.State.SomeTokensFailed -> when (newState) { diff --git a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/WalletReducer.kt b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/WalletReducer.kt index e4126a3f8c..11ea7236c0 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/WalletReducer.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/redux/reducers/WalletReducer.kt @@ -14,14 +14,26 @@ import com.tangem.tap.common.redux.AppState import com.tangem.tap.domain.TapError import com.tangem.tap.domain.extensions.getArtworkUrl import com.tangem.tap.domain.getFirstToken -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.wallet.models.WalletRent -import com.tangem.tap.features.wallet.redux.* +import com.tangem.tap.features.wallet.redux.AddressData +import com.tangem.tap.features.wallet.redux.Artwork +import com.tangem.tap.features.wallet.redux.Currency +import com.tangem.tap.features.wallet.redux.ErrorType +import com.tangem.tap.features.wallet.redux.ProgressState +import com.tangem.tap.features.wallet.redux.TradeCryptoState +import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletAddresses +import com.tangem.tap.features.wallet.redux.WalletData +import com.tangem.tap.features.wallet.redux.WalletDialog +import com.tangem.tap.features.wallet.redux.WalletMainButton +import com.tangem.tap.features.wallet.redux.WalletState +import com.tangem.tap.features.wallet.redux.WalletStore import com.tangem.tap.features.wallet.ui.BalanceStatus import com.tangem.tap.features.wallet.ui.BalanceWidgetData import com.tangem.tap.store -import org.rekotlin.Action import java.math.BigDecimal +import org.rekotlin.Action class WalletReducer { companion object { @@ -272,21 +284,6 @@ private fun internalReduce(action: Action, state: AppState): WalletState { } newState = newState.copy(cardImage = Artwork(artworkId = artworkUrl)) } - is WalletAction.ShowDialog.SignedHashesMultiWalletDialog -> { - newState = newState.copy(walletDialog = WalletDialog.SignedHashesMultiWalletDialog) - } - is WalletAction.ShowDialog.ChooseTradeActionDialog -> { - newState = newState.copy(walletDialog = WalletDialog.ChooseTradeActionDialog) - } - is WalletAction.HideDialog -> { - newState = newState.copy(walletDialog = null) - } - is WalletAction.Send.ChooseCurrency -> { - newState = newState.copy( - walletDialog = WalletDialog.SelectAmountToSendDialog(action.amounts) - ) - } - is WalletAction.Send.Cancel -> newState = newState.copy(walletDialog = null) is WalletAction.TradeCryptoAction -> return newState is WalletAction.ChangeSelectedAddress -> { val selectedWalletData = newState.getWalletData(newState.selectedCurrency) @@ -436,9 +433,6 @@ private fun setMultiWalletFiatRate( return state .updateWalletsData(newWalletsData) - .updateTotalBalance( - totalBalance = obtainTotalBalance(newWalletsData, appCurrency) - ) } private fun setSingleWalletFiatRate( diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletDetailsFragment.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletDetailsFragment.kt index f267c25f89..77ed03ebfa 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletDetailsFragment.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletDetailsFragment.kt @@ -1,8 +1,11 @@ package com.tangem.tap.features.wallet.ui -import android.app.Dialog import android.os.Bundle -import android.view.* +import android.view.Menu +import android.view.MenuInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup import android.widget.TextView import androidx.activity.OnBackPressedCallback import androidx.annotation.ColorRes @@ -15,17 +18,28 @@ import by.kirich1409.viewbindingdelegate.viewBinding import com.squareup.picasso.Picasso import com.tangem.tap.common.SnackbarHandler import com.tangem.tap.common.TestActions -import com.tangem.tap.common.extensions.* +import com.tangem.tap.common.extensions.appendIfNotNull +import com.tangem.tap.common.extensions.beginDelayedTransition +import com.tangem.tap.common.extensions.fitChipsByGroupWidth +import com.tangem.tap.common.extensions.getColor +import com.tangem.tap.common.extensions.getString +import com.tangem.tap.common.extensions.hide +import com.tangem.tap.common.extensions.loadCurrenciesIcon +import com.tangem.tap.common.extensions.show +import com.tangem.tap.common.extensions.toQrCode import com.tangem.tap.common.recyclerView.SpaceItemDecoration -import com.tangem.tap.common.redux.StateDialog import com.tangem.tap.common.redux.navigation.NavigationAction -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.onboarding.getQRReceiveMessage import com.tangem.tap.features.wallet.models.PendingTransaction -import com.tangem.tap.features.wallet.redux.* +import com.tangem.tap.features.wallet.redux.Currency +import com.tangem.tap.features.wallet.redux.ErrorType +import com.tangem.tap.features.wallet.redux.ProgressState +import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletData +import com.tangem.tap.features.wallet.redux.WalletState import com.tangem.tap.features.wallet.ui.adapters.PendingTransactionsAdapter import com.tangem.tap.features.wallet.ui.adapters.WalletDetailWarningMessagesAdapter -import com.tangem.tap.features.wallet.ui.dialogs.AmountToSendDialog import com.tangem.tap.features.wallet.ui.test.TestWalletDetails import com.tangem.tap.store import com.tangem.wallet.R @@ -37,7 +51,6 @@ class WalletDetailsFragment : Fragment(R.layout.fragment_wallet_details), private lateinit var pendingTransactionAdapter: PendingTransactionsAdapter private lateinit var warningMessagesAdapter: WalletDetailWarningMessagesAdapter - private var dialog: Dialog? = null private val binding: FragmentWalletDetailsBinding by viewBinding(FragmentWalletDetailsBinding::bind) @@ -92,14 +105,18 @@ class WalletDetailsFragment : Fragment(R.layout.fragment_wallet_details), } private fun setupButtons() = with(binding) { - btnConfirm.text = getString(R.string.wallet_button_send) - btnConfirm.setOnClickListener { store.dispatch(WalletAction.Send()) } - - binding.lWalletDetails.btnShare.setOnClickListener { store.dispatch(WalletAction.ShowDialog.QrCode) } - - btnTrade.setOnClickListener { store.dispatch(WalletAction.TradeCryptoAction.Buy) } - - btnSell.setOnClickListener { store.dispatch(WalletAction.TradeCryptoAction.Sell) } + rowButtons.onBuyClick = { + store.dispatch(WalletAction.TradeCryptoAction.Buy) + } + rowButtons.onSellClick = { + store.dispatch(WalletAction.TradeCryptoAction.Sell) + } + rowButtons.onTradeClick = { + store.dispatch(WalletAction.DialogAction.ChooseTradeActionDialog) + } + rowButtons.onSendClick = { + store.dispatch(WalletAction.Send()) + } } private fun setupTestActionButton() { @@ -124,7 +141,6 @@ class WalletDetailsFragment : Fragment(R.layout.fragment_wallet_details), setupBalanceData(selectedWallet.currencyData) setupButtons(selectedWallet) - handleDialogs(state.walletDialog) handleCurrencyIcon(selectedWallet) handleWarnings(selectedWallet) @@ -156,7 +172,6 @@ class WalletDetailsFragment : Fragment(R.layout.fragment_wallet_details), } private fun setupButtons(selectedWallet: WalletData) = with(binding) { - btnConfirm.isEnabled = selectedWallet.mainButton.enabled lWalletDetails.btnCopy.setOnClickListener { selectedWallet.walletAddresses?.selectedAddress?.address?.let { addressString -> store.dispatch(WalletAction.CopyAddress(addressString, requireContext())) @@ -167,8 +182,12 @@ class WalletDetailsFragment : Fragment(R.layout.fragment_wallet_details), store.dispatch(WalletAction.ShareAddress(addressString, requireContext())) } } - btnTrade.isEnabled = selectedWallet.tradeCryptoState.buyingAllowed - btnSell.show(selectedWallet.tradeCryptoState.sellingAllowed) + + rowButtons.updateButtonsVisibility( + buyAllowed = selectedWallet.tradeCryptoState.buyingAllowed, + sellAllowed = selectedWallet.tradeCryptoState.sellingAllowed, + sendAllowed = selectedWallet.mainButton.enabled, + ) } private fun handleWarnings(selectedWallet: WalletData) = with(binding) { @@ -291,21 +310,6 @@ class WalletDetailsFragment : Fragment(R.layout.fragment_wallet_details), } } - private fun handleDialogs(walletDialog: StateDialog?) { - when (walletDialog) { - is WalletDialog.SelectAmountToSendDialog -> { - if (dialog == null) dialog = AmountToSendDialog(requireContext()).apply { - this.show(walletDialog.amounts) - } - } - null -> { - dialog?.dismiss() - dialog = null - } - } - } - - override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_remove -> { diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletFragment.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletFragment.kt index 9c4661dbb8..24473568ef 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletFragment.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/WalletFragment.kt @@ -24,7 +24,11 @@ import com.tangem.tap.domain.statePrinter.printScanResponseState import com.tangem.tap.domain.statePrinter.printWalletState import com.tangem.tap.domain.termsOfUse.CardTou import com.tangem.tap.features.details.redux.DetailsAction -import com.tangem.tap.features.wallet.redux.* +import com.tangem.tap.features.wallet.redux.Artwork +import com.tangem.tap.features.wallet.redux.ErrorType +import com.tangem.tap.features.wallet.redux.ProgressState +import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletState import com.tangem.tap.features.wallet.ui.adapters.WarningMessagesAdapter import com.tangem.tap.features.wallet.ui.wallet.MultiWalletView import com.tangem.tap.features.wallet.ui.wallet.SingleWalletView @@ -78,7 +82,7 @@ class WalletFragment : Fragment(R.layout.fragment_wallet), StoreSubscriber { + root.getString(R.string.wallet_balance_tx_in_progress) + } + BalanceStatus.Unreachable -> { + root.getString(R.string.wallet_balance_blockchain_unreachable) + } + BalanceStatus.NoAccount -> { + root.getString(R.string.wallet_error_no_account) + } + BalanceStatus.VerifiedOnline, + BalanceStatus.SameCurrencyTransactionInProgress, + BalanceStatus.EmptyCard, + BalanceStatus.UnknownBlockchain, + BalanceStatus.Loading, + null -> null } - val blockchain = wallet.currency.blockchain - val token = (wallet.currency as? Currency.Token)?.token - val isCustom = wallet.currency - .isCustomCurrency(store.state.globalState.scanResponse?.card?.derivationStyle) - tvExchangeRate.show(!isCustom) - tvCustomCurrency.show(isCustom) + if (status == null || status == BalanceStatus.Loading) { + lContent.root.hide() + lShimmer.root.veil() + } else { + lShimmer.root.unVeil() + lContent.root.show() + } Picasso.get().loadCurrenciesIcon( imageView = ivCurrency, textView = tvTokenLetter, - token = token, blockchain = blockchain, + token = (wallet.currency as? Currency.Token)?.token, + blockchain = wallet.currency.blockchain, ) - when (wallet.currencyData.status) { - BalanceStatus.VerifiedOnline, - BalanceStatus.SameCurrencyTransactionInProgress -> hideMessage() - BalanceStatus.Loading -> if (wallet.currencyData.amountFormatted == null) { - showMessage(root.getString(R.string.wallet_balance_loading)) - } - BalanceStatus.TransactionInProgress -> - showMessage(root.getString(R.string.wallet_balance_tx_in_progress)) - BalanceStatus.Unreachable -> - showMessage(root.getString(R.string.wallet_balance_blockchain_unreachable)) + lContent.tvCurrency.text = wallet.currencyData.currency + lContent.tvAmountFiat.text = wallet.currencyData.fiatAmountFormatted ?: "—" + lContent.tvAmount.text = wallet.currencyData.amountFormatted ?: "—" - BalanceStatus.NoAccount -> - showMessage(root.getString(R.string.wallet_error_no_account)) - else -> { - } + lContent.tvStatus.isVisible = statusMessage != null + lContent.tvStatus.text = statusMessage + + lContent.tvExchangeRate.isVisible = statusMessage == null + lContent.tvExchangeRate.text = if (isCustomCurrency) { + root.getString(id = R.string.token_item_no_rate) + } else { + wallet.fiatRateString } - } - private fun showMessage(message: String) { - toggleMessage(true) - binding.tvStatus.text = message - } - - private fun hideMessage() { - toggleMessage(false) - } - - private fun toggleMessage(show: Boolean) { - binding.tvAmount.show(!show) - binding.tvStatus.show(show) + cardWallet.setOnClickListener { + store.dispatch(WalletAction.MultiWallet.SelectWallet(wallet)) + } } } } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/adapters/WarningMessagesAdapter.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/adapters/WarningMessagesAdapter.kt index 946e347a65..9014d5d4ff 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/adapters/WarningMessagesAdapter.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/adapters/WarningMessagesAdapter.kt @@ -10,7 +10,12 @@ import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.google.android.play.core.review.ReviewManagerFactory import com.tangem.tap.common.analytics.AnalyticsEvent -import com.tangem.tap.common.extensions.* +import com.tangem.tap.common.extensions.dispatchOpenUrl +import com.tangem.tap.common.extensions.getActivity +import com.tangem.tap.common.extensions.getColor +import com.tangem.tap.common.extensions.getString +import com.tangem.tap.common.extensions.hide +import com.tangem.tap.common.extensions.show import com.tangem.tap.common.redux.global.GlobalAction import com.tangem.tap.domain.configurable.warningMessage.WarningMessage import com.tangem.tap.domain.configurable.warningMessage.WarningMessagesManager @@ -87,7 +92,7 @@ class WarningMessageVH(val binding: LayoutWarningCardActionBinding) : RecyclerVi when { warning.titleResId == R.string.warning_important_security_info -> { View.OnClickListener { - store.dispatch(WalletAction.ShowDialog.SignedHashesMultiWalletDialog) + store.dispatch(WalletAction.DialogAction.SignedHashesMultiWalletDialog) } } warning.messageResId == R.string.alert_funds_restoration_message -> { diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/AmountToSendDialog.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/AmountToSendBottomSheetDialog.kt similarity index 80% rename from app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/AmountToSendDialog.kt rename to app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/AmountToSendBottomSheetDialog.kt index 69219eff90..2f9e597096 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/AmountToSendDialog.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/AmountToSendBottomSheetDialog.kt @@ -5,17 +5,25 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.appcompat.view.ContextThemeWrapper -import androidx.recyclerview.widget.* +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.DividerItemDecoration +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.ListAdapter +import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetDialog import com.tangem.blockchain.common.Amount import com.tangem.tap.common.extensions.toFormattedString import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletDialog import com.tangem.tap.store import com.tangem.wallet.R import com.tangem.wallet.databinding.DialogWalletSendBinding import com.tangem.wallet.databinding.ItemWalletAmountToSendBinding -class AmountToSendDialog(context: Context) : BottomSheetDialog(context) { +class AmountToSendBottomSheetDialog( + context: Context, + private val dialog: WalletDialog.SelectAmountToSendDialog, +) : BottomSheetDialog(context) { var binding: DialogWalletSendBinding? = null @@ -25,12 +33,12 @@ class AmountToSendDialog(context: Context) : BottomSheetDialog(context) { setContentView(binding!!.root) } - fun show(amounts: List?) { + override fun show() { super.show() setOnDismissListener { binding = null - store.dispatch(WalletAction.Send.Cancel) + store.dispatch(WalletAction.DialogAction.Hide) } binding!!.rvAmountsToSend.layoutManager = LinearLayoutManager(context) @@ -43,7 +51,7 @@ class AmountToSendDialog(context: Context) : BottomSheetDialog(context) { val viewAdapter = ChooseAmountAdapter() binding!!.rvAmountsToSend.adapter = viewAdapter - viewAdapter.submitList(amounts) + viewAdapter.submitList(dialog.amounts) } } @@ -79,7 +87,7 @@ class ChooseAmountAdapter tvCurrencySymbol.text = amount.currencySymbol tvAmount.text = amount.value?.toFormattedString(amount.decimals) root.setOnClickListener { - store.dispatch(WalletAction.Send.Cancel) + store.dispatch(WalletAction.DialogAction.Hide) store.dispatch(WalletAction.Send(amount)) } } diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/ChooseTradeActionDialog.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/ChooseTradeActionBottomSheetDialog.kt similarity index 87% rename from app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/ChooseTradeActionDialog.kt rename to app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/ChooseTradeActionBottomSheetDialog.kt index 93baaf29a3..1c65315d3a 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/ChooseTradeActionDialog.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/ChooseTradeActionBottomSheetDialog.kt @@ -8,7 +8,7 @@ import com.tangem.tap.features.wallet.redux.WalletAction import com.tangem.tap.store import com.tangem.wallet.databinding.DialogWalletTradeBinding -class ChooseTradeActionDialog(context: Context) : BottomSheetDialog(context) { +class ChooseTradeActionBottomSheetDialog(context: Context) : BottomSheetDialog(context) { var binding: DialogWalletTradeBinding? = null @@ -23,7 +23,7 @@ class ChooseTradeActionDialog(context: Context) : BottomSheetDialog(context) { this.setOnDismissListener { binding = null - store.dispatch(WalletAction.HideDialog) + store.dispatch(WalletAction.DialogAction.Hide) } binding!!.dialogBtnBuy.setOnClickListener { diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/SignedHashesWarningDialog.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/SignedHashesWarningDialog.kt index 9aaf4b88d6..609537bbaf 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/SignedHashesWarningDialog.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/dialogs/SignedHashesWarningDialog.kt @@ -24,7 +24,7 @@ class SignedHashesWarningDialog { } setNegativeButton(R.string.common_cancel) { _, _ -> } setOnDismissListener { - store.dispatch(WalletAction.HideDialog) + store.dispatch(WalletAction.DialogAction.Hide) } }.create() } diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/test/TestWalletDetailsActions.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/test/TestWalletDetailsActions.kt index e72efc46ac..6b99ef8be9 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/test/TestWalletDetailsActions.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/test/TestWalletDetailsActions.kt @@ -4,7 +4,7 @@ import com.tangem.blockchain.common.Amount import com.tangem.blockchain.common.WalletManager import com.tangem.tap.common.TestAction import com.tangem.tap.common.TestActions -import com.tangem.tap.domain.tokens.BlockchainNetwork +import com.tangem.tap.domain.tokens.models.BlockchainNetwork import com.tangem.tap.features.wallet.redux.WalletAction import com.tangem.tap.store import java.math.BigDecimal diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/view/WalletDetailsButtonsRow.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/view/WalletDetailsButtonsRow.kt new file mode 100644 index 0000000000..12efe010c8 --- /dev/null +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/view/WalletDetailsButtonsRow.kt @@ -0,0 +1,47 @@ +package com.tangem.tap.features.wallet.ui.view + +import android.content.Context +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.LinearLayout +import androidx.core.view.isVisible +import com.tangem.wallet.databinding.ViewWalletDetailsButtonsRowBinding + +internal class WalletDetailsButtonsRow @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0, +) : LinearLayout(context, attrs, defStyleAttr) { + private val binding = ViewWalletDetailsButtonsRowBinding.inflate( + LayoutInflater.from(context), + this + ) + + var onBuyClick: (() -> Unit)? = null + var onSellClick: (() -> Unit)? = null + var onTradeClick: (() -> Unit)? = null + var onSendClick: (() -> Unit)? = null + + init { + orientation = HORIZONTAL + + with(binding) { + btnBuy.setOnClickListener { onBuyClick?.invoke() } + btnSell.setOnClickListener { onSellClick?.invoke() } + btnTrade.setOnClickListener { onTradeClick?.invoke() } + btnSend.setOnClickListener { onSendClick?.invoke() } + } + } + + fun updateButtonsVisibility( + buyAllowed: Boolean, + sellAllowed: Boolean, + sendAllowed: Boolean + ) = with(binding) { + btnBuy.isVisible = (buyAllowed && !sellAllowed) || (!buyAllowed && !sellAllowed) + btnBuy.isEnabled = buyAllowed + btnSell.isVisible = !buyAllowed && sellAllowed + btnTrade.isVisible = buyAllowed && sellAllowed + btnSend.isEnabled = sendAllowed + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/CurrencySelectionDialog.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/CurrencySelectionDialog.kt index deab5c4759..78b665cde6 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/CurrencySelectionDialog.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/CurrencySelectionDialog.kt @@ -3,14 +3,14 @@ package com.tangem.tap.features.wallet.ui.wallet import android.content.Context import androidx.appcompat.app.AlertDialog import com.tangem.tap.common.extensions.dispatchDialogHide -import com.tangem.tap.common.redux.AppDialog import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletDialog import com.tangem.tap.store import com.tangem.wallet.R object CurrencySelectionDialog { fun create( - dialog: AppDialog.CurrencySelectionDialog, + dialog: WalletDialog.CurrencySelectionDialog, context: Context ): AlertDialog { val currenciesToShow = dialog.currenciesList diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/MultiWalletView.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/MultiWalletView.kt index 8c4a49b1fb..b777d3ef00 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/MultiWalletView.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/MultiWalletView.kt @@ -1,7 +1,6 @@ package com.tangem.tap.features.wallet.ui.wallet -import android.app.Dialog -import android.view.View +import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import com.tangem.common.card.Card import com.tangem.domain.common.TapWorkarounds.derivationStyle @@ -10,19 +9,16 @@ import com.tangem.tap.common.extensions.animateVisibility import com.tangem.tap.common.extensions.formatAmountAsSpannedString import com.tangem.tap.common.extensions.hide import com.tangem.tap.common.extensions.show -import com.tangem.tap.common.redux.StateDialog import com.tangem.tap.common.redux.navigation.AppScreen import com.tangem.tap.common.redux.navigation.NavigationAction import com.tangem.tap.currenciesRepository import com.tangem.tap.features.tokens.redux.TokensAction import com.tangem.tap.features.wallet.models.TotalBalance import com.tangem.tap.features.wallet.redux.WalletAction -import com.tangem.tap.features.wallet.redux.WalletDialog import com.tangem.tap.features.wallet.redux.WalletState import com.tangem.tap.features.wallet.ui.BalanceStatus import com.tangem.tap.features.wallet.ui.WalletFragment import com.tangem.tap.features.wallet.ui.adapters.WalletAdapter -import com.tangem.tap.features.wallet.ui.dialogs.SignedHashesWarningDialog import com.tangem.tap.store import com.tangem.wallet.R import com.tangem.wallet.databinding.FragmentWalletBinding @@ -32,7 +28,6 @@ class MultiWalletView : WalletView { private var fragment: WalletFragment? = null private var binding: FragmentWalletBinding? = null - private var dialog: Dialog? = null private lateinit var walletsAdapter: WalletAdapter @@ -41,7 +36,6 @@ class MultiWalletView : WalletView { setFragment(fragment, binding) onViewCreated() showMultiWalletView(binding) - setupButtons(binding) } @@ -52,7 +46,6 @@ class MultiWalletView : WalletView { lAddress.root.hide() lButtonsShort.root.hide() lButtonsLong.root.hide() - btnScanMultiwallet.show() rvMultiwallet.show() btnAddToken.show() setupWalletCardNumber(binding) @@ -70,11 +63,6 @@ class MultiWalletView : WalletView { } } - - private fun setupButtons(binding: FragmentWalletBinding) = with(binding) { - btnScanMultiwallet.setOnClickListener { store.dispatch(WalletAction.Scan) } - } - override fun setFragment(fragment: WalletFragment, binding: FragmentWalletBinding) { this.fragment = fragment this.binding = binding @@ -129,36 +117,32 @@ class MultiWalletView : WalletView { store.dispatch(NavigationAction.NavigateTo(AppScreen.AddTokens)) } handleErrorStates(state = state, binding = binding, fragment = fragment) - handleDialogs(state.walletDialog) } private fun handleTotalBalance( binding: FragmentWalletBinding, totalBalance: TotalBalance?, ) = with(binding.lCardTotalBalance) { - if (totalBalance == null) { - this.root.hide() - return@with - } + root.isVisible = totalBalance != null + if (totalBalance != null) { + if (totalBalance.state == TotalBalance.State.Loading) { + veilBalance.veil() + } else { + veilBalance.unVeil() + } + tvProcessing.animateVisibility( + show = totalBalance.state == TotalBalance.State.SomeTokensFailed + ) - tvBalance.animateVisibility( - show = totalBalance.state != TotalBalance.State.Loading, - hiddenVisibility = View.INVISIBLE - ) - pbLoading.animateVisibility( - show = totalBalance.state == TotalBalance.State.Loading - ) - tvProcessing.animateVisibility( - show = totalBalance.state == TotalBalance.State.SomeTokensFailed - ) + tvBalance.text = if (totalBalance.state == TotalBalance.State.SomeTokensFailed) "—" + else totalBalance.fiatAmount.formatAmountAsSpannedString( + currencySymbol = totalBalance.fiatCurrency.symbol + ) + tvCurrencyName.text = totalBalance.fiatCurrency.code - tvBalance.text = totalBalance.fiatAmount.formatAmountAsSpannedString( - currencySymbol = totalBalance.fiatCurrency.symbol - ) - tvCurrencyName.text = totalBalance.fiatCurrency.code - - tvCurrencyName.setOnClickListener { - store.dispatch(WalletAction.AppCurrencyAction.ChooseAppCurrency) + tvCurrencyName.setOnClickListener { + store.dispatch(WalletAction.AppCurrencyAction.ChooseAppCurrency) + } } } @@ -204,27 +188,10 @@ class MultiWalletView : WalletView { private fun configureButtonsForEmptyWalletState(binding: FragmentWalletBinding) = with(binding) { - btnScanMultiwallet.hide() lButtonsLong.root.show() lButtonsLong.btnScanLong.setOnClickListener { store.dispatch(WalletAction.Scan) } lButtonsLong.btnConfirmLong.setOnClickListener { store.dispatch(WalletAction.CreateWallet) } lButtonsLong.btnConfirmLong.text = fragment?.getText(R.string.wallet_button_create_wallet) } - - private fun handleDialogs(walletDialog: StateDialog?) { - val fragment = fragment ?: return - val context = fragment.context ?: return - when (walletDialog) { - is WalletDialog.SignedHashesMultiWalletDialog -> { - if (dialog == null) { - dialog = SignedHashesWarningDialog.create(context).apply { show() } - } - } - else -> { - dialog?.dismiss() - dialog = null - } - } - } } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/SingleWalletView.kt b/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/SingleWalletView.kt index a26f2582fb..4fb9b0ca0b 100644 --- a/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/SingleWalletView.kt +++ b/app/src/main/java/com/tangem/tap/features/wallet/ui/wallet/SingleWalletView.kt @@ -1,6 +1,5 @@ package com.tangem.tap.features.wallet.ui.wallet -import android.app.Dialog import android.view.View import android.view.ViewGroup import android.widget.Button @@ -10,17 +9,18 @@ import com.tangem.tap.common.extensions.beginDelayedTransition import com.tangem.tap.common.extensions.fitChipsByGroupWidth import com.tangem.tap.common.extensions.hide import com.tangem.tap.common.extensions.show -import com.tangem.tap.common.redux.StateDialog import com.tangem.tap.features.onboarding.products.twins.redux.TwinCardsState import com.tangem.tap.features.wallet.models.PendingTransaction -import com.tangem.tap.features.wallet.redux.* +import com.tangem.tap.features.wallet.redux.Currency +import com.tangem.tap.features.wallet.redux.TradeCryptoState +import com.tangem.tap.features.wallet.redux.WalletAction +import com.tangem.tap.features.wallet.redux.WalletData +import com.tangem.tap.features.wallet.redux.WalletMainButton +import com.tangem.tap.features.wallet.redux.WalletState import com.tangem.tap.features.wallet.ui.BalanceWidget import com.tangem.tap.features.wallet.ui.MultipleAddressUiHelper import com.tangem.tap.features.wallet.ui.WalletFragment import com.tangem.tap.features.wallet.ui.adapters.PendingTransactionsAdapter -import com.tangem.tap.features.wallet.ui.dialogs.AmountToSendDialog -import com.tangem.tap.features.wallet.ui.dialogs.ChooseTradeActionDialog -import com.tangem.tap.features.wallet.ui.dialogs.SignedHashesWarningDialog import com.tangem.tap.store import com.tangem.wallet.R import com.tangem.wallet.databinding.FragmentWalletBinding @@ -30,7 +30,6 @@ class SingleWalletView : WalletView { private lateinit var pendingTransactionAdapter: PendingTransactionsAdapter private var fragment: WalletFragment? = null private var binding: FragmentWalletBinding? = null - private var dialog: Dialog? = null override fun setFragment(fragment: WalletFragment, binding: FragmentWalletBinding) { this.fragment = fragment @@ -51,7 +50,6 @@ class SingleWalletView : WalletView { private fun showSingleWalletView(binding: FragmentWalletBinding) = with(binding) { rvMultiwallet.hide() btnAddToken.hide() - btnScanMultiwallet.hide() rvPendingTransaction.hide() lCardBalance.root.show() lAddress.root.show() @@ -80,7 +78,6 @@ class SingleWalletView : WalletView { setupAddressCard(state.primaryWallet, binding) showPendingTransactionsIfPresent(state.primaryWallet.pendingTransactions) setupBalance(state, state.primaryWallet) - handleDialogs(state.walletDialog, fragment) } private fun showPendingTransactionsIfPresent(pendingTransactions: List) { @@ -153,7 +150,14 @@ class SingleWalletView : WalletView { } } lAddress.btnShowQr.setOnClickListener { - store.dispatch(WalletAction.ShowDialog.QrCode) + state.walletAddresses?.selectedAddress?.let { selectedAddress -> + store.dispatch( + WalletAction.DialogAction.QrCode( + currency = state.currency, + selectedAddress = selectedAddress + ) + ) + } } setupTradeButton(binding, state.tradeCryptoState) @@ -165,7 +169,7 @@ class SingleWalletView : WalletView { val action = when { allowedToBuy && !allowedToSell -> WalletAction.TradeCryptoAction.Buy !allowedToBuy && allowedToSell -> WalletAction.TradeCryptoAction.Sell - allowedToBuy && allowedToSell -> WalletAction.ShowDialog.ChooseTradeActionDialog + allowedToBuy && allowedToSell -> WalletAction.DialogAction.ChooseTradeActionDialog else -> null } val text = when { @@ -257,28 +261,4 @@ class SingleWalletView : WalletView { binding.lAddress.root.hide() } } - - private fun handleDialogs(walletDialog: StateDialog?, fragment: WalletFragment) { - val context = fragment.context ?: return - when (walletDialog) { - is WalletDialog.SelectAmountToSendDialog -> { - if (dialog == null) dialog = AmountToSendDialog(context).apply { - this.show(walletDialog.amounts) - } - } - is WalletDialog.SignedHashesMultiWalletDialog -> { - if (dialog == null) { - dialog = SignedHashesWarningDialog.create(context).apply { show() } - } - } - is WalletDialog.ChooseTradeActionDialog -> { - if (dialog == null) dialog = ChooseTradeActionDialog(context).apply { show() } - } - null -> { - dialog?.dismiss() - dialog = null - } - } - } - } \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_more_vertical_24.xml b/app/src/main/res/drawable/ic_more_vertical_24.xml new file mode 100644 index 0000000000..fd51d1fbf2 --- /dev/null +++ b/app/src/main/res/drawable/ic_more_vertical_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_scan_card_24.xml b/app/src/main/res/drawable/ic_scan_card_24.xml new file mode 100644 index 0000000000..b77d547233 --- /dev/null +++ b/app/src/main/res/drawable/ic_scan_card_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/layout/card_total_balance.xml b/app/src/main/res/layout/card_total_balance.xml index 0b0d382e71..196dc167e1 100644 --- a/app/src/main/res/layout/card_total_balance.xml +++ b/app/src/main/res/layout/card_total_balance.xml @@ -22,10 +22,10 @@ - + tools:veilLayout_veiled="false"> - + + + + + + + + diff --git a/app/src/main/res/layout/fragment_home.xml b/app/src/main/res/layout/fragment_home.xml index 30dfad0768..7a95116cd8 100644 --- a/app/src/main/res/layout/fragment_home.xml +++ b/app/src/main/res/layout/fragment_home.xml @@ -8,4 +8,4 @@ android:layout_width="match_parent" android:layout_height="match_parent"/> - \ No newline at end of file + diff --git a/app/src/main/res/layout/fragment_wallet.xml b/app/src/main/res/layout/fragment_wallet.xml index 829a1f019b..3b962facaf 100644 --- a/app/src/main/res/layout/fragment_wallet.xml +++ b/app/src/main/res/layout/fragment_wallet.xml @@ -18,12 +18,13 @@ app:liftOnScroll="true"> + android:id="@+id/toolbar" + android:layout_width="match_parent" + android:layout_height="?attr/actionBarSize" + app:menu="@menu/wallet" + app:navigationIcon="@drawable/ic_scan_card_24" + app:navigationIconTint="@color/iconGray" + app:title="@string/wallet_title" /> @@ -41,19 +42,20 @@ android:overScrollMode="never"> - - + + - - - - - - - - - + android:layout_marginTop="30dp" + app:layout_constraintTop_toBottomOf="@id/l_address" + app:layout_constraintVertical_bias="1" + app:layout_constraintBottom_toBottomOf="parent" /> @@ -214,4 +179,19 @@ + + diff --git a/app/src/main/res/layout/fragment_wallet_details.xml b/app/src/main/res/layout/fragment_wallet_details.xml index cd51f4c2fa..04649efe6b 100644 --- a/app/src/main/res/layout/fragment_wallet_details.xml +++ b/app/src/main/res/layout/fragment_wallet_details.xml @@ -105,78 +105,27 @@ android:layout_marginStart="16dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" - app:layout_constraintStart_toStartOf="parent" - app:layout_constraintTop_toBottomOf="@+id/l_wallet_details" /> + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toBottomOf="@+id/l_wallet_details" /> + android:id="@+id/barrier" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + app:barrierDirection="bottom" + app:constraint_referenced_ids="l_wallet_details" /> - - - - - - - - - + @@ -184,4 +133,4 @@ - \ No newline at end of file + diff --git a/app/src/main/res/layout/item_currency_wallet.xml b/app/src/main/res/layout/item_currency_wallet.xml index c2d664e182..ddb13e5666 100644 --- a/app/src/main/res/layout/item_currency_wallet.xml +++ b/app/src/main/res/layout/item_currency_wallet.xml @@ -21,7 +21,8 @@ android:layout_marginTop="12dp" android:layout_marginBottom="12dp" android:layout_marginStart="16dp" - android:layout_marginEnd="16dp"> + android:layout_marginEnd="16dp" + android:animateLayoutChanges="true"> - - - - - - - - - - - - + app:layout_constraintEnd_toEndOf="parent" + tools:visibility="visible" /> - - - + app:layout_constraintStart_toEndOf="@id/iv_currency" + app:layout_constraintEnd_toEndOf="parent" /> diff --git a/app/src/main/res/layout/item_currency_wallet_content.xml b/app/src/main/res/layout/item_currency_wallet_content.xml new file mode 100644 index 0000000000..18249f4c63 --- /dev/null +++ b/app/src/main/res/layout/item_currency_wallet_content.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/item_currency_wallet_shimmer.xml b/app/src/main/res/layout/item_currency_wallet_shimmer.xml new file mode 100644 index 0000000000..a37bd8c956 --- /dev/null +++ b/app/src/main/res/layout/item_currency_wallet_shimmer.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/view_wallet_details_buttons_row.xml b/app/src/main/res/layout/view_wallet_details_buttons_row.xml new file mode 100644 index 0000000000..bb5bd190b0 --- /dev/null +++ b/app/src/main/res/layout/view_wallet_details_buttons_row.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + diff --git a/app/src/main/res/menu/wallet.xml b/app/src/main/res/menu/wallet.xml index c4947ea75b..7f6107b331 100644 --- a/app/src/main/res/menu/wallet.xml +++ b/app/src/main/res/menu/wallet.xml @@ -2,8 +2,9 @@ - \ No newline at end of file + android:id="@+id/details_menu" + android:title="@string/details_title" + android:icon="@drawable/ic_more_vertical_24" + app:iconTint="@color/iconGray" + app:showAsAction="ifRoom" /> + diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index bc04e7cf38..c45da10b0e 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -382,6 +382,4 @@ Привет, команда поддержки, Пожалуйста, расскажите нам больше о Вашей проблеме. Каждая деталь может быть полезной. Информация ниже не является обязательной. Вы можете стереть её, если хотите. - Баланс - Обработка полной суммы… diff --git a/app/src/main/res/values-ru/strings_final.xml b/app/src/main/res/values-ru/strings_final.xml index 8ce3f1256a..ea424b57b6 100644 --- a/app/src/main/res/values-ru/strings_final.xml +++ b/app/src/main/res/values-ru/strings_final.xml @@ -40,10 +40,14 @@ Доступные сети Внимание! Валюты на разных сетях имеют разные адреса. Убедитесь, что адрес соответствует сети, в которой вы отправляете средства. Токены в сети Solana не поддерживаются этой картой из-за ограничений прошивки. - Не осуществляйте перевод на токены в данной сети иначе это может привести к их безвозвратной утере. + Не осуществляйте перевод на токены в данной сети, иначе это может привести к их безвозвратной утере. Адрес контракта скопирован! Если вы совершили ошибку с выбором сети при переводе средств с биржи, эта инструкция поможет вам восстановить средства Пользовательский - \ No newline at end of file + Баланс + Обработка полной суммы… + Управление токенами + Нет цены + diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml index ce2c35b5fb..63924e74c0 100644 --- a/app/src/main/res/values/dimens.xml +++ b/app/src/main/res/values/dimens.xml @@ -30,6 +30,7 @@ 135dp 4dp + 8dp 44dp 32sp diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c3caa853e1..520b7bc183 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -206,6 +206,4 @@ To avoid paying an increased commission the next time you top up your wallet, reduce the amount by %s XTZ Reduce by %s XTZ No, send all - Total balance - Processing full amount… diff --git a/app/src/main/res/values/strings_final.xml b/app/src/main/res/values/strings_final.xml index de09eb54fd..2478dee488 100644 --- a/app/src/main/res/values/strings_final.xml +++ b/app/src/main/res/values/strings_final.xml @@ -46,4 +46,8 @@ Custom - \ No newline at end of file + Total balance + Some networks are unreachable + Manage tokens + No rate + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index 49c8fefbbb..f36d1cd4bf 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -160,7 +160,6 @@ - diff --git a/domain/build.gradle b/domain/build.gradle index bb6f9ae760..db9f1b15b3 100644 --- a/domain/build.gradle +++ b/domain/build.gradle @@ -59,7 +59,7 @@ dependencies { implementation implementation(project(path: ':network')) implementation implementation(project(path: ':common')) - implementation 'com.tangem:blockchain:develop-83' + implementation 'com.tangem:blockchain:develop-84' // implementation 'com.tangem:blockchain:0.0.1' implementation 'com.tangem.tangem-sdk-kotlin:core:develop-142' implementation 'com.tangem.tangem-sdk-kotlin:android:develop-142' diff --git a/domain/src/main/java/com/tangem/domain/common/extensions/Blockchain.kt b/domain/src/main/java/com/tangem/domain/common/extensions/Blockchain.kt index 9b9c451aef..b69ffb1c49 100644 --- a/domain/src/main/java/com/tangem/domain/common/extensions/Blockchain.kt +++ b/domain/src/main/java/com/tangem/domain/common/extensions/Blockchain.kt @@ -91,7 +91,7 @@ fun Blockchain.toCoinId(): String { Blockchain.Stellar, Blockchain.StellarTestnet -> "stellar" Blockchain.Cardano, Blockchain.CardanoShelley -> "cardano" Blockchain.Polygon, Blockchain.PolygonTestnet -> "matic-network" - Blockchain.Arbitrum, Blockchain.ArbitrumTestnet -> "arbitrum-one" + Blockchain.Arbitrum, Blockchain.ArbitrumTestnet -> "ethereum" Blockchain.Avalanche, Blockchain.AvalancheTestnet -> "avalanche-2" Blockchain.Solana, Blockchain.SolanaTestnet -> "solana" Blockchain.Fantom, Blockchain.FantomTestnet -> "fantom" diff --git a/domain/src/main/java/com/tangem/domain/common/extensions/TangemTechService.kt b/domain/src/main/java/com/tangem/domain/common/extensions/TangemTechService.kt new file mode 100644 index 0000000000..f841679ffb --- /dev/null +++ b/domain/src/main/java/com/tangem/domain/common/extensions/TangemTechService.kt @@ -0,0 +1,27 @@ +package com.tangem.domain.common.extensions + +import com.tangem.common.services.Result +import com.tangem.network.api.tangemTech.CoinsResponse +import com.tangem.network.api.tangemTech.TangemTechService + +suspend fun TangemTechService.getTokens( + contractAddress: String, + networkId: String? = null, + active: Boolean? = null, +): Result = coins( + contractAddress = contractAddress, + networkIds = networkId, + active = active + ) + +suspend fun TangemTechService.getListOfCoins( + networkIds: List, + searchText: String? = null, + offset: Int? = null, + limit: Int? = null +): Result = coins( + networkIds = networkIds.joinToString(","), + searchText = searchText, + offset = offset, + limit = limit + ) \ No newline at end of file diff --git a/domain/src/main/java/com/tangem/domain/features/addCustomToken/AddCustomTokenService.kt b/domain/src/main/java/com/tangem/domain/features/addCustomToken/AddCustomTokenService.kt index 9a1f717c34..502452e476 100644 --- a/domain/src/main/java/com/tangem/domain/features/addCustomToken/AddCustomTokenService.kt +++ b/domain/src/main/java/com/tangem/domain/features/addCustomToken/AddCustomTokenService.kt @@ -1,6 +1,7 @@ package com.tangem.domain.features.addCustomToken import com.tangem.common.services.Result +import com.tangem.domain.common.extensions.getTokens import com.tangem.network.api.tangemTech.CoinsResponse import com.tangem.network.api.tangemTech.TangemTechService @@ -18,7 +19,7 @@ class AddCustomTokenService( active: Boolean? = null, ): Result> { val networksIds = selectNetworksForSearch(networkId) - val result = tangemTechService.coins(contractAddress, networksIds, active) + val result = tangemTechService.getTokens(contractAddress, networksIds, active) return when (result) { is Result.Success -> { var coinsList = mutableListOf() diff --git a/network/src/main/java/com/tangem/network/api/tangemTech/Responses.kt b/network/src/main/java/com/tangem/network/api/tangemTech/Responses.kt index bc5b09f51f..c21fb92726 100644 --- a/network/src/main/java/com/tangem/network/api/tangemTech/Responses.kt +++ b/network/src/main/java/com/tangem/network/api/tangemTech/Responses.kt @@ -9,7 +9,7 @@ interface HttpResponse sealed interface TangemTechResponse : HttpResponse data class CoinsResponse( - val imageHost: String, + val imageHost: String?, val coins: List, val total: Int ) : TangemTechResponse { diff --git a/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechApi.kt b/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechApi.kt index f2c689e15c..0081f4ee24 100644 --- a/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechApi.kt +++ b/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechApi.kt @@ -11,8 +11,11 @@ interface TangemTechApi { @GET("coins") suspend fun coins( @Query("contractAddress") contractAddress: String? = null, - @Query("networkIds") networkId: String? = null, + @Query("networkIds") networkIds: String? = null, @Query("active") active: Boolean? = null, + @Query("searchText") searchText: String? = null, + @Query("offset") offset: Int? = null, + @Query("limit") limit: Int? = null ): CoinsResponse @GET("rates") diff --git a/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechService.kt b/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechService.kt index e4c3321f3b..5790bdac3a 100644 --- a/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechService.kt +++ b/network/src/main/java/com/tangem/network/api/tangemTech/TangemTechService.kt @@ -15,15 +15,27 @@ class TangemTechService { private val headerInterceptors = mutableListOf( CacheControlHttpInterceptor(cacheMaxAge) ) - + private var api: TangemTechApi = createApi() suspend fun coins( contractAddress: String? = null, - networkId: String? = null, + networkIds: String? = null, active: Boolean? = null, + searchText: String? = null, + offset: Int? = null, + limit: Int? = null ): Result = withContext(Dispatchers.IO) { - performRequest { api.coins(contractAddress, networkId, active) } + performRequest { + api.coins( + contractAddress = contractAddress, + networkIds = networkIds, + active = active, + searchText = searchText, + offset = offset, + limit = limit + ) + } } suspend fun rates(