Skip to content

Commit

Permalink
Merge pull request #1717 from novasamatech/fix/portfolio-view-bugs
Browse files Browse the repository at this point in the history
Fix/portfolio view bugs
  • Loading branch information
antonijzelinskij authored Nov 11, 2024
2 parents e52aa1d + ae93275 commit eb89b09
Show file tree
Hide file tree
Showing 42 changed files with 186 additions and 100 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ inline fun <T> withFlowScope(crossinline block: suspend (scope: CoroutineScope)

fun <T1, T2> combineToPair(flow1: Flow<T1>, flow2: Flow<T2>): Flow<Pair<T1, T2>> = combine(flow1, flow2, ::Pair)

fun <T1, T2, T3> combineToTriple(flow1: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>): Flow<Triple<T1, T2, T3>> = combine(flow1, flow2, flow3, ::Triple)

/**
* Modifies flow so that it firstly emits [LoadingState.Loading] state for each element from upstream.
* Then, it constructs new source via [sourceSupplier] and emits all of its items wrapped into [LoadingState.Loaded] state
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ package io.novafoundation.nova.common.utils.formatting
import java.lang.Integer.max
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat
import kotlin.math.min

class DynamicPrecisionFormatter(
private val minScale: Int,
private val minPrecision: Int,
) : NumberFormatter {

private val patternCache = mutableMapOf<Int, DecimalFormat>()

override fun format(number: BigDecimal, roundingMode: RoundingMode): String {
// scale() - total amount of digits after 0.,
// precision() - amount of non-zero digits in decimal part
Expand All @@ -18,6 +21,11 @@ class DynamicPrecisionFormatter(

val formattingPrecision = max(minScale, requiredPrecision)

return decimalFormatterFor(patternWith(formattingPrecision), roundingMode).format(number)
val formatter = patternCache.getOrPut(formattingPrecision) { decimalFormatterFor(patternWith(formattingPrecision)) }
if (formatter.roundingMode != roundingMode) {
formatter.roundingMode = roundingMode
}

return formatter.format(number)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ import java.math.RoundingMode

class FixedPrecisionFormatter(private val precision: Int) : NumberFormatter {

private val delegate = decimalFormatterFor(patternWith(precision))

override fun format(number: BigDecimal, roundingMode: RoundingMode): String {
val delegate = decimalFormatterFor(patternWith(precision), roundingMode)
if (delegate.roundingMode != roundingMode) {
delegate.roundingMode = roundingMode
}

return delegate.format(number)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ fun formatDateISO_8601_NoMs(date: Date): String {
return dateTimeFormatISO_8601_NoMs.format(date)
}

fun decimalFormatterFor(pattern: String, roundingMode: RoundingMode): DecimalFormat {
fun decimalFormatterFor(pattern: String): DecimalFormat {
return DecimalFormat(pattern).apply {
val symbols = decimalFormatSymbols

Expand All @@ -178,7 +178,6 @@ fun decimalFormatterFor(pattern: String, roundingMode: RoundingMode): DecimalFor

decimalFormatSymbols = symbols

this.roundingMode = roundingMode
decimalFormatSymbols = decimalFormatSymbols
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class QrCodeView @JvmOverloads constructor(
private var overlayBackground: Drawable? = null

private val overlaySize = 64.dp
private val overlayQuiteZone = 4.dp
private val overlayQuiteZone = 0
private val qrPadding = 16.dpF

private val centerRect: RectF = RectF()
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Pistas no disponibles</string>
<string name="select_ledger_location_enable_request_message">Nova necesita que la ubicación esté habilitada para poder realizar el escaneo bluetooth y encontrar tu dispositivo Ledger</string>
<string name="select_ledger_location_enable_request_title">Por favor, habilita la geolocalización en las configuraciones del dispositivo</string>
<string name="select_network_title">Seleccionar red</string>
<string name="select_tracks_for">Seleccione pistas para</string>
<string name="selected_tracks_quantity" formatted="false">%d de %d</string>
<string name="send_address_hint">Dirección o w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-fr-rFR/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Chemins non disponibles</string>
<string name="select_ledger_location_enable_request_message">Nova a besoin que la localisation soit activée pour pouvoir effectuer un balayage Bluetooth afin de trouver votre appareil Ledger</string>
<string name="select_ledger_location_enable_request_title">Veuillez activer la géolocalisation dans les paramètres de l\'appareil</string>
<string name="select_network_title">Sélectionner un réseau</string>
<string name="select_tracks_for">Sélectionner des pistes pour</string>
<string name="selected_tracks_quantity" formatted="false">%d sur %d</string>
<string name="send_address_hint">Adresse ou w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-in/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Unavailable tracks</string>
<string name="select_ledger_location_enable_request_message">Nova needs location to be enabled to be able to perform bluetooth scanning to find your Ledger device</string>
<string name="select_ledger_location_enable_request_title">Please enable geo-location in device settings</string>
<string name="select_network_title">Pilih jaringan</string>
<string name="select_tracks_for">Select tracks for</string>
<string name="selected_tracks_quantity" formatted="false">%d of %d</string>
<string name="send_address_hint">Address or w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Tracce non disponibili</string>
<string name="select_ledger_location_enable_request_message">Nova ha bisogno che la posizione sia attivata per poter effettuare la scansione Bluetooth per trovare il tuo dispositivo Ledger</string>
<string name="select_ledger_location_enable_request_title">Si prega di abilitare la geolocalizzazione nelle impostazioni del dispositivo</string>
<string name="select_network_title">Seleziona rete</string>
<string name="select_tracks_for">Seleziona brani per</string>
<string name="selected_tracks_quantity" formatted="false">%d di %d</string>
<string name="send_address_hint">Indirizzo o w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-ja/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,7 @@
<string name="select_delegation_tracks_unavailable_tracks">利用不可のトラック</string>
<string name="select_ledger_location_enable_request_message">Novaは、Ledgerデバイスを見つけるためにBluetoothスキャンを実行するために位置情報の有効化が必要です</string>
<string name="select_ledger_location_enable_request_title">デバイス設定で位置情報を有効にしてください</string>
<string name="select_network_title">ネットワークを選択</string>
<string name="select_tracks_for">トラックを選択</string>
<string name="selected_tracks_quantity" formatted="false">%d / %d</string>
<string name="send_address_hint">アドレスまたはw3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-ko/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,7 @@
<string name="select_delegation_tracks_unavailable_tracks">사용할 수 없는 트랙</string>
<string name="select_ledger_location_enable_request_message">Ledger 장치를 찾기 위해 블루투스 스캔을 수행하려면 Nova는 위치 기능을 활성화해야 합니다.</string>
<string name="select_ledger_location_enable_request_title">기기 설정에서 지리적 위치를 활성화해주세요.</string>
<string name="select_network_title">네트워크 선택</string>
<string name="select_tracks_for">트랙 선택</string>
<string name="selected_tracks_quantity" formatted="false">%d 중 %d</string>
<string name="send_address_hint">주소 또는 w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-pl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Niedostępne trasy</string>
<string name="select_ledger_location_enable_request_message">Nova wymaga włączenia lokalizacji, aby móc przeprowadzać skanowanie Bluetooth w celu znalezienia urządzenia Ledger</string>
<string name="select_ledger_location_enable_request_title">Proszę włączyć geolokalizację w ustawieniach urządzenia</string>
<string name="select_network_title">Wybierz sieć</string>
<string name="select_tracks_for">Wybierz trasy dla</string>
<string name="selected_tracks_quantity" formatted="false">%d z %d</string>
<string name="send_address_hint">Adres lub w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-pt/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Faixas indisponíveis</string>
<string name="select_ledger_location_enable_request_message">Nova precisa que a localização seja ativada para poder realizar a varredura Bluetooth para encontrar seu dispositivo Ledger</string>
<string name="select_ledger_location_enable_request_title">Por favor, ative a localização geográfica nas configurações do dispositivo</string>
<string name="select_network_title">Selecionar rede</string>
<string name="select_tracks_for">Selecione faixas para</string>
<string name="selected_tracks_quantity" formatted="false">%d de %d</string>
<string name="send_address_hint">Endereço ou w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Недоступные треки</string>
<string name="select_ledger_location_enable_request_message">Nova нуждается в включении местоположения, чтобы иметь возможность выполнять сканирование Bluetooth для поиска вашего устройства Ledger</string>
<string name="select_ledger_location_enable_request_title">Пожалуйста, включите геолокацию в настройках устройства</string>
<string name="select_network_title">Выберите сеть</string>
<string name="select_tracks_for">Выберите треки для</string>
<string name="selected_tracks_quantity" formatted="false">%d из %d</string>
<string name="send_address_hint">Адрес или w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-tr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Ulaşılamayan yollar</string>
<string name="select_ledger_location_enable_request_message">Nova\'nın Bluetooth taraması yaparak Ledger cihazınızı bulabilmesi için konumun etkinleştirilmesi gerekiyor</string>
<string name="select_ledger_location_enable_request_title">Lütfen cihaz ayarlarında coğrafi konumu etkinleştirin</string>
<string name="select_network_title">Ağ seç</string>
<string name="select_tracks_for">İçin şarkıları seçin</string>
<string name="selected_tracks_quantity" formatted="false">%d / %d</string>
<string name="send_address_hint">Adres veya w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-vi/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,7 @@
<string name="select_delegation_tracks_unavailable_tracks">Track không có sẵn</string>
<string name="select_ledger_location_enable_request_message">Nova cần bật định vị để có thể thực hiện quét Bluetooth để tìm thiết bị Ledger của bạn</string>
<string name="select_ledger_location_enable_request_title">Vui lòng bật định vị địa lý trong cài đặt thiết bị</string>
<string name="select_network_title">Chọn mạng</string>
<string name="select_tracks_for">Chọn track cho</string>
<string name="selected_tracks_quantity" formatted="false">%d trong %d</string>
<string name="send_address_hint">Địa chỉ hoặc w3n</string>
Expand Down
1 change: 1 addition & 0 deletions common/src/main/res/values-zh-rCN/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,7 @@
<string name="select_delegation_tracks_unavailable_tracks">不可用的轨道</string>
<string name="select_ledger_location_enable_request_message">Nova需要启用地理位置,以便能够进行蓝牙扫描查找您的Ledger设备</string>
<string name="select_ledger_location_enable_request_title">请在设备设置中启用地理位置</string>
<string name="select_network_title">选择网络</string>
<string name="select_tracks_for">选择曲目</string>
<string name="selected_tracks_quantity" formatted="false">%d / %d</string>
<string name="send_address_hint">地址或w3n</string>
Expand Down
2 changes: 2 additions & 0 deletions common/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyEllipsis">

<string name="select_network_title">Select network</string>

<string name="assets_search_token_hint">Search by token</string>

<string name="receive_screen_copy_address">Copy Address</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,16 @@ class ByTokensAssetSearchInteractor(
externalBalancesFlow: Flow<List<ExternalBalance>>,
coroutineScope: CoroutineScope
): Flow<AssetsByViewModeResult> {
val filterFlow = assetSearchUseCase.getAvailableSwapAssets(forAsset, coroutineScope).map { availableAssetsForSwap ->
val filter: AssetSearchFilter = { asset ->
val chainAsset = asset.token.configuration
val filterFlow = assetSearchUseCase.getAvailableSwapAssets(forAsset, coroutineScope)
.map { availableAssetsForSwap ->
val filter: AssetSearchFilter = { asset ->
val chainAsset = asset.token.configuration

chainAsset.fullId in availableAssetsForSwap
}
chainAsset.fullId in availableAssetsForSwap
}

filter
}
filter
}

return searchAssetsByTokensInternalFlow(queryFlow, externalBalancesFlow, filterFlow = filterFlow)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ fun groupAndSortAssetsByToken(
.map { asset -> AssetWithNetwork(chainsById.getValue(asset.token.configuration.chainId), asset, asset.totalWithOffChain(externalBalances)) }
.groupBy { mapToTokenGroup(it) }
.mapValues { (_, assets) -> assets.sortedWith(assetComparator) }
.mapKeys { (token, assets) ->
.mapKeys { (tokenWrapper, assets) ->
TokenAssetGroup(
token = token,
token = tokenWrapper.token,
groupBalance = assets.fold(AssetBalance.ZERO) { acc, element -> acc + element.balanceWithOffChain },
itemsCount = assets.size
)
Expand All @@ -61,6 +61,7 @@ fun getTokenAssetBaseComparator(
return compareByDescending(comparing)
.thenByDescending { it.asset.token.configuration.isUtilityAsset } // utility assets first
.thenBy { it.asset.token.configuration.symbol.value }
.then(Chain.defaultComparatorFrom(AssetWithNetwork::chain))
}

fun getTokenAssetGroupBaseComparator(
Expand All @@ -71,9 +72,23 @@ fun getTokenAssetGroupBaseComparator(
.then(TokenSymbol.defaultComparatorFrom { it.token.symbol })
}

private fun mapToTokenGroup(it: AssetWithNetwork) = TokenAssetGroup.Token(
it.asset.token.configuration.icon,
it.asset.token.configuration.symbol.normalize(),
it.asset.token.currency,
it.asset.token.coinRate
private fun mapToTokenGroup(it: AssetWithNetwork) = TokenGroupWrapper(
TokenAssetGroup.Token(
it.asset.token.configuration.icon,
it.asset.token.configuration.symbol.normalize(),
it.asset.token.currency,
it.asset.token.coinRate
)
)

// Helper class to group items by symbol only
private class TokenGroupWrapper(val token: TokenAssetGroup.Token) {

override fun equals(other: Any?): Boolean {
return other is TokenGroupWrapper && token.symbol == other.token.symbol
}

override fun hashCode(): Int {
return token.symbol.hashCode()
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package io.novafoundation.nova.feature_assets.presentation.balance.common

import io.novafoundation.nova.common.data.model.AssetViewMode
import io.novafoundation.nova.common.utils.combineToPair
import io.novafoundation.nova.common.utils.shareInBackground
import io.novafoundation.nova.common.utils.throttleLast
import io.novafoundation.nova.feature_assets.domain.WalletInteractor
import io.novafoundation.nova.feature_assets.domain.assets.ExternalBalancesInteractor
import io.novafoundation.nova.feature_assets.domain.assets.list.AssetsListInteractor
Expand All @@ -15,6 +17,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.combine
import kotlin.time.Duration.Companion.milliseconds

class AssetListMixinFactory(
private val walletInteractor: WalletInteractor,
Expand Down Expand Up @@ -67,11 +70,13 @@ class RealAssetListMixin(
override val assetsViewModeFlow = assetsListInteractor.assetsViewModeFlow()
.shareInBackground()

private val throttledBalance = combineToPair(filteredAssetsFlow, externalBalancesFlow)
.throttleLast(300.milliseconds)

private val assetsByViewMode = combine(
filteredAssetsFlow,
externalBalancesFlow,
throttledBalance,
assetsViewModeFlow
) { assets, externalBalances, viewMode ->
) { (assets, externalBalances), viewMode ->
when (viewMode) {
AssetViewMode.NETWORKS -> walletInteractor.groupAssetsByNetwork(assets, externalBalances).byNetworks()
AssetViewMode.TOKENS -> walletInteractor.groupAssetsByToken(assets, externalBalances).byTokens()
Expand Down
Loading

0 comments on commit eb89b09

Please sign in to comment.