fix(@desktop/wallet): Switching networks doesn't change assets

fixes #13137, #13144
This commit is contained in:
Khushboo Mehta 2024-01-05 21:17:58 +05:30 committed by Khushboo-dev-cpp
parent 4510bc1e18
commit fb39c8c3b8
14 changed files with 71 additions and 63 deletions

View File

@ -59,10 +59,16 @@ QtObject:
result = newQVariant(self.balancesPerChain[index.row]) result = newQVariant(self.balancesPerChain[index.row])
proc modelsAboutToUpdate*(self: Model) = proc modelsAboutToUpdate*(self: Model) =
self.balancesPerChain = @[]
self.beginResetModel() self.beginResetModel()
proc modelsUpdated*(self: Model) = proc modelsUpdated*(self: Model) =
for i in countup(0, (self.delegate.getGroupedAccountsAssetsList().len-1)): let lengthOfGroupedAssets = self.delegate.getGroupedAccountsAssetsList().len
self.balancesPerChain.add(newBalancesModel(self.delegate, i)) let balancesPerChainLen = self.balancesPerChain.len
let diff = abs(lengthOfGroupedAssets - balancesPerChainLen)
if lengthOfGroupedAssets > balancesPerChainLen:
for i in countup(0, diff-1):
self.balancesPerChain.add(newBalancesModel(self.delegate, balancesPerChainLen+i))
elif lengthOfGroupedAssets < balancesPerChainLen:
self.balancesPerChain.delete(balancesPerChainLen - diff, balancesPerChainLen-1)
self.endResetModel() self.endResetModel()
self.countChanged()

View File

@ -60,7 +60,6 @@ method load*(self: Module) =
self.events.on(SIGNAL_WALLET_ACCOUNT_TOKENS_REBUILT) do(e:Args): self.events.on(SIGNAL_WALLET_ACCOUNT_TOKENS_REBUILT) do(e:Args):
let arg = TokensPerAccountArgs(e) let arg = TokensPerAccountArgs(e)
self.view.modelsUpdated() self.view.modelsUpdated()
self.view.setAssetsLoading(false)
self.view.setHasBalanceCache(self.controller.getHasBalanceCache()) self.view.setHasBalanceCache(self.controller.getHasBalanceCache())
self.view.setHasMarketValuesCache(self.controller.getHasMarketValuesCache()) self.view.setHasMarketValuesCache(self.controller.getHasMarketValuesCache())
@ -105,7 +104,6 @@ method filterChanged*(self: Module, addresses: seq[string], chainIds: seq[int])
let walletAccounts = self.controller.getWalletAccountsByAddresses(addresses) let walletAccounts = self.controller.getWalletAccountsByAddresses(addresses)
if walletAccounts[0].assetsLoading: if walletAccounts[0].assetsLoading:
self.view.setAssetsLoading(true)
self.setLoadingAssets() self.setLoadingAssets()
else: else:
let walletTokens = self.controller.getWalletTokensByAddresses(addresses) let walletTokens = self.controller.getWalletTokensByAddresses(addresses)

View File

@ -11,7 +11,6 @@ QtObject:
delegate: io_interface.AccessInterface delegate: io_interface.AccessInterface
assets: token_model.Model assets: token_model.Model
groupedAccountAssetsModel: grouped_account_assets_model.Model groupedAccountAssetsModel: grouped_account_assets_model.Model
assetsLoading: bool
hasBalanceCache: bool hasBalanceCache: bool
hasMarketValuesCache: bool hasMarketValuesCache: bool
@ -49,18 +48,6 @@ QtObject:
read = getGroupedAccountAssetsModel read = getGroupedAccountAssetsModel
notify = groupedAccountAssetsModelChanged notify = groupedAccountAssetsModelChanged
proc getAssetsLoading(self: View): QVariant {.slot.} =
return newQVariant(self.assetsLoading)
proc assetsLoadingChanged(self: View) {.signal.}
QtProperty[QVariant] assetsLoading:
read = getAssetsLoading
notify = assetsLoadingChanged
proc setAssetsLoading*(self:View, assetLoading: bool) =
if assetLoading != self.assetsLoading:
self.assetsLoading = assetLoading
self.assetsLoadingChanged()
proc getHasBalanceCache(self: View): QVariant {.slot.} = proc getHasBalanceCache(self: View): QVariant {.slot.} =
return newQVariant(self.hasBalanceCache) return newQVariant(self.hasBalanceCache)
proc hasBalanceCacheChanged(self: View) {.signal.} proc hasBalanceCacheChanged(self: View) {.signal.}

View File

@ -185,6 +185,7 @@ proc notifyFilterChanged(self: Module) =
self.activityController.globalFilterChanged(self.filter.addresses, self.filter.allAddresses, self.filter.chainIds, self.filter.allChainsEnabled) self.activityController.globalFilterChanged(self.filter.addresses, self.filter.allAddresses, self.filter.chainIds, self.filter.allChainsEnabled)
self.collectiblesController.setFilterAddressesAndChains(self.filter.addresses, self.filter.chainIds) self.collectiblesController.setFilterAddressesAndChains(self.filter.addresses, self.filter.chainIds)
self.allTokensModule.filterChanged(self.filter.addresses) self.allTokensModule.filterChanged(self.filter.addresses)
self.view.setAddressFilters(self.filter.addresses.join(":"))
if self.filter.addresses.len > 0: if self.filter.addresses.len > 0:
self.view.filterChanged(self.filter.addresses[0], self.filter.allAddresses) self.view.filterChanged(self.filter.addresses[0], self.filter.allAddresses)
@ -273,6 +274,10 @@ method load*(self: Module) =
self.notifyFilterChanged() self.notifyFilterChanged()
self.setTotalCurrencyBalance() self.setTotalCurrencyBalance()
self.events.on(SIGNAL_CURRENCY_UPDATED) do(e:Args):
let args = SettingsTextValueArgs(e)
self.view.setCurrentCurrency(args.value)
self.controller.init() self.controller.init()
self.view.load() self.view.load()
self.accountsModule.load() self.accountsModule.load()

View File

@ -25,6 +25,7 @@ QtObject:
wcController: wcc.Controller wcController: wcc.Controller
walletReady: bool walletReady: bool
addressFilters: string addressFilters: string
currentCurrency: string
proc setup(self: View) = proc setup(self: View) =
self.QObject.setup self.QObject.setup
@ -46,12 +47,17 @@ QtObject:
proc load*(self: View) = proc load*(self: View) =
self.delegate.viewDidLoad() self.delegate.viewDidLoad()
proc currentCurrencyChanged*(self: View) {.signal.}
proc updateCurrency*(self: View, currency: string) {.slot.} = proc updateCurrency*(self: View, currency: string) {.slot.} =
self.delegate.updateCurrency(currency) self.delegate.updateCurrency(currency)
proc setCurrentCurrency*(self: View, currency: string) =
self.currentCurrency = currency
self.currentCurrencyChanged()
proc getCurrentCurrency(self: View): string {.slot.} = proc getCurrentCurrency(self: View): string {.slot.} =
return self.delegate.getCurrentCurrency() return self.delegate.getCurrentCurrency()
QtProperty[string] currentCurrency: QtProperty[string] currentCurrency:
read = getCurrentCurrency read = getCurrentCurrency
notify = currentCurrencyChanged
proc filterChanged*(self: View, addresses: string, allAddresses: bool) {.signal.} proc filterChanged*(self: View, addresses: string, allAddresses: bool) {.signal.}
@ -77,7 +83,7 @@ QtObject:
read = getIsMnemonicBackedUp read = getIsMnemonicBackedUp
proc addressFiltersChanged*(self: View) {.signal.} proc addressFiltersChanged*(self: View) {.signal.}
proc setAddressFilters(self: View, address: string) = proc setAddressFilters*(self: View, address: string) =
self.addressFilters = address self.addressFilters = address
self.addressFiltersChanged() self.addressFiltersChanged()
proc getAddressFilters(self: View): string {.slot.} = proc getAddressFilters(self: View): string {.slot.} =
@ -87,11 +93,9 @@ QtObject:
notify = addressFiltersChanged notify = addressFiltersChanged
proc setFilterAddress(self: View, address: string) {.slot.} = proc setFilterAddress(self: View, address: string) {.slot.} =
self.setAddressFilters(address)
self.delegate.setFilterAddress(address) self.delegate.setFilterAddress(address)
proc setFillterAllAddresses(self: View) {.slot.} = proc setFillterAllAddresses(self: View) {.slot.} =
self.setAddressFilters("")
self.delegate.setFillterAllAddresses() self.delegate.setFillterAllAddresses()
proc setTotalCurrencyBalance*(self: View, totalCurrencyBalance: CurrencyAmount) = proc setTotalCurrencyBalance*(self: View, totalCurrencyBalance: CurrencyAmount) =

View File

@ -450,7 +450,6 @@ QtObject:
if symbols.len > 0: if symbols.len > 0:
self.fetchTokensMarketValues(symbols) self.fetchTokensMarketValues(symbols)
self.fetchTokensPrices(symbols) self.fetchTokensPrices(symbols)
self.fetchTokensDetails(symbols)
proc getTokenByFlatTokensKey*(self: Service, key: string): TokenItem = proc getTokenByFlatTokensKey*(self: Service, key: string): TokenItem =
for t in self.flatTokenList: for t in self.flatTokenList:

View File

@ -1,24 +1,6 @@
import stint,strformat import stint, strformat
type type BalanceItem* = ref object of RootObj
AccountTokenItem* = object
key*: string
flatTokensKey*: string
symbol*: string
account*: string
chainId*: int
balance*: Uint256
proc `$`*(self: AccountTokenItem): string =
result = fmt"""AccountTokenItem[
key: {self.key},
flatTokensKey: {self.flatTokensKey},
symbol: {self.symbol},
account: {self.account},
chainId: {self.chainId},
balance: {self.balance}]"""
type BalanceItem* = object
account*: string account*: string
chainId*: int chainId*: int
balance*: Uint256 balance*: Uint256
@ -30,7 +12,7 @@ proc `$`*(self: BalanceItem): string =
balance: {self.balance}]""" balance: {self.balance}]"""
type type
GroupedTokenItem* = object GroupedTokenItem* = ref object of RootObj
tokensKey*: string tokensKey*: string
symbol*: string symbol*: string
balancesPerAccount*: seq[BalanceItem] balancesPerAccount*: seq[BalanceItem]

View File

@ -47,7 +47,7 @@ QtObject:
keypairs: Table[string, KeypairDto] ## [keyUid, KeypairDto] keypairs: Table[string, KeypairDto] ## [keyUid, KeypairDto]
accountsTokens*: Table[string, seq[WalletTokenDto]] ## [address, seq[WalletTokenDto]] accountsTokens*: Table[string, seq[WalletTokenDto]] ## [address, seq[WalletTokenDto]]
flatAccountTokensList: seq[AccountTokenItem] groupedAccountsTokensTable: Table[string, GroupedTokenItem]
groupedAccountsTokensList: seq[GroupedTokenItem] groupedAccountsTokensList: seq[GroupedTokenItem]
hasBalanceCache: bool hasBalanceCache: bool

View File

@ -173,10 +173,16 @@ proc init*(self: Service) =
of "wallet-tick-reload": of "wallet-tick-reload":
let addresses = self.getWalletAddresses() let addresses = self.getWalletAddresses()
self.buildAllTokens(addresses, store = true) self.buildAllTokens(addresses, store = true)
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.newBuildAllTokens(addresses, store = true)
self.checkRecentHistory(addresses) self.checkRecentHistory(addresses)
self.events.on(SIGNAL_CURRENCY_UPDATED) do(e:Args): self.events.on(SIGNAL_CURRENCY_UPDATED) do(e:Args):
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(self.getWalletAddresses(), store = true) self.buildAllTokens(self.getWalletAddresses(), store = true)
self.newBuildAllTokens(self.getWalletAddresses(), store = true)
self.events.on(SIGNAL_IMPORT_PARTIALLY_OPERABLE_ACCOUNTS) do(e: Args): self.events.on(SIGNAL_IMPORT_PARTIALLY_OPERABLE_ACCOUNTS) do(e: Args):
let args = ImportAccountsArgs(e) let args = ImportAccountsArgs(e)
@ -197,7 +203,10 @@ proc addNewKeypairsAccountsToLocalStoreAndNotify(self: Service, notify: bool = t
continue continue
woAccDb.ens = getEnsName(woAccDb.address, chainId) woAccDb.ens = getEnsName(woAccDb.address, chainId)
self.storeWatchOnlyAccount(woAccDb) self.storeWatchOnlyAccount(woAccDb)
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(@[woAccDb.address], store = true) self.buildAllTokens(@[woAccDb.address], store = true)
self.newBuildAllTokens(@[woAccDb.address], store = true)
if notify: if notify:
self.events.emit(SIGNAL_WALLET_ACCOUNT_SAVED, AccountArgs(account: woAccDb)) self.events.emit(SIGNAL_WALLET_ACCOUNT_SAVED, AccountArgs(account: woAccDb))
# check if there is new keypair or any account added to an existing keypair # check if there is new keypair or any account added to an existing keypair
@ -207,7 +216,10 @@ proc addNewKeypairsAccountsToLocalStoreAndNotify(self: Service, notify: bool = t
if localKp.isNil: if localKp.isNil:
self.storeKeypair(kpDb) self.storeKeypair(kpDb)
let addresses = kpDb.accounts.map(a => a.address) let addresses = kpDb.accounts.map(a => a.address)
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(addresses, store = true) self.buildAllTokens(addresses, store = true)
self.newBuildAllTokens(addresses, store = true)
for acc in kpDb.accounts: for acc in kpDb.accounts:
acc.ens = getEnsName(acc.address, chainId) acc.ens = getEnsName(acc.address, chainId)
if acc.isChat: if acc.isChat:
@ -227,7 +239,10 @@ proc addNewKeypairsAccountsToLocalStoreAndNotify(self: Service, notify: bool = t
self.storeAccountToKeypair(accDb) self.storeAccountToKeypair(accDb)
if accDb.isChat: if accDb.isChat:
continue continue
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(@[accDb.address], store = true) self.buildAllTokens(@[accDb.address], store = true)
self.newBuildAllTokens(@[accDb.address], store = true)
if notify: if notify:
self.events.emit(SIGNAL_WALLET_ACCOUNT_SAVED, AccountArgs(account: accDb)) self.events.emit(SIGNAL_WALLET_ACCOUNT_SAVED, AccountArgs(account: accDb))
@ -525,7 +540,10 @@ proc setNetworksState*(self: Service, chainIds: seq[int], enabled: bool) =
proc toggleTestNetworksEnabled*(self: Service) = proc toggleTestNetworksEnabled*(self: Service) =
discard self.settingsService.toggleTestNetworksEnabled() discard self.settingsService.toggleTestNetworksEnabled()
let addresses = self.getWalletAddresses() let addresses = self.getWalletAddresses()
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(addresses, store = true) self.buildAllTokens(addresses, store = true)
self.newBuildAllTokens(addresses, store = true)
self.tokenService.loadData() self.tokenService.loadData()
self.checkRecentHistory(addresses) self.checkRecentHistory(addresses)
self.events.emit(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED, Args()) self.events.emit(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED, Args())
@ -534,7 +552,10 @@ proc toggleIsSepoliaEnabled*(self: Service) =
discard self.settingsService.toggleIsSepoliaEnabled() discard self.settingsService.toggleIsSepoliaEnabled()
self.networkService.resetNetworks() self.networkService.resetNetworks()
let addresses = self.getWalletAddresses() let addresses = self.getWalletAddresses()
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(addresses, store = true) self.buildAllTokens(addresses, store = true)
self.newBuildAllTokens(addresses, store = true)
self.tokenService.loadData() self.tokenService.loadData()
self.checkRecentHistory(addresses) self.checkRecentHistory(addresses)
self.events.emit(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED, Args()) self.events.emit(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED, Args())

View File

@ -100,7 +100,10 @@ proc checkRecentHistory*(self: Service, addresses: seq[string]) =
proc reloadAccountTokens*(self: Service) = proc reloadAccountTokens*(self: Service) =
let addresses = self.getWalletAddresses() let addresses = self.getWalletAddresses()
# TODO: Only the newBuildAllTokens will remain after task -
# https://github.com/status-im/status-desktop/issues/13142
self.buildAllTokens(addresses, store = true) self.buildAllTokens(addresses, store = true)
self.newBuildAllTokens(addresses, store = true)
self.checkRecentHistory(addresses) self.checkRecentHistory(addresses)
proc getCurrency*(self: Service): string = proc getCurrency*(self: Service): string =

View File

@ -8,11 +8,22 @@ proc onNewAllTokensBuilt*(self: Service, response: string) {.slot.} =
discard responseObj.getProp("storeResult", storeResult) discard responseObj.getProp("storeResult", storeResult)
discard responseObj.getProp("result", resultObj) discard responseObj.getProp("result", resultObj)
var accountsTokensBalances: seq[AccountTokenItem] = @[] var groupedAccountsTokensBalances = self.groupedAccountsTokensTable
var groupedAccountsTokensBalances: Table[string, GroupedTokenItem] = initTable[string, GroupedTokenItem]()
var allTokensHaveError: bool = true var allTokensHaveError: bool = true
if resultObj.kind == JObject: if resultObj.kind == JObject:
for accountAddress, tokensDetailsObj in resultObj: for accountAddress, tokensDetailsObj in resultObj:
# Delete all existing entries for the account for whom assets were requested,
# for a new account the balances per address per chain will simply be appended later
var tokensToBeDeleted: seq[string] = @[]
for tokenkey, token in groupedAccountsTokensBalances:
token.balancesPerAccount = token.balancesPerAccount.filter(balanceItem => balanceItem.account != accountAddress)
if token.balancesPerAccount.len == 0:
tokensToBeDeleted.add(tokenkey)
for t in tokensToBeDeleted:
groupedAccountsTokensBalances.del(t)
if tokensDetailsObj.kind == JArray: if tokensDetailsObj.kind == JArray:
for token in tokensDetailsObj.getElems(): for token in tokensDetailsObj.getElems():
@ -47,22 +58,12 @@ proc onNewAllTokensBuilt*(self: Service, response: string) {.slot.} =
balancesPerAccount: @[BalanceItem(account:accountAddress, chainId: chainId, balance: rawBalance)] balancesPerAccount: @[BalanceItem(account:accountAddress, chainId: chainId, balance: rawBalance)]
) )
accountsTokensBalances.add(AccountTokenItem(
key: flatTokensKey & accountAddress,
symbol: symbol,
flatTokensKey: flatTokensKey,
account: accountAddress,
chainId: chainId,
balance: rawBalance
))
# set assetsLoading to false once the tokens are loaded # set assetsLoading to false once the tokens are loaded
self.updateAssetsLoadingState(accountAddress, false) self.updateAssetsLoadingState(accountAddress, false)
if storeResult and not allTokensHaveError: if storeResult and not allTokensHaveError:
self.hasBalanceCache = true self.hasBalanceCache = true
self.flatAccountTokensList = accountsTokensBalances self.groupedAccountsTokensTable = groupedAccountsTokensBalances
self.groupedAccountsTokensList = toSeq(groupedAccountsTokensBalances.values) self.groupedAccountsTokensList = toSeq(groupedAccountsTokensBalances.values)
except Exception as e: except Exception as e:
error "error: ", procName="onAllTokensBuilt", errName = e.name, errDesription = e.msg error "error: ", procName="onAllTokensBuilt", errName = e.name, errDesription = e.msg
@ -89,7 +90,7 @@ proc newBuildAllTokens*(self: Service, accounts: seq[string], store: bool) =
proc getTotalCurrencyBalance*(self: Service, addresses: seq[string], chainIds: seq[int]): float64 = proc getTotalCurrencyBalance*(self: Service, addresses: seq[string], chainIds: seq[int]): float64 =
var totalBalance: float64 = 0.0 var totalBalance: float64 = 0.0
for token in self.groupedAccountsTokensList: for tokensKey, token in self.groupedAccountsTokensList:
let price = self.tokenService.getPriceBySymbol(token.symbol) let price = self.tokenService.getPriceBySymbol(token.symbol)
let balances = token.balancesPerAccount.filter(a => addresses.contains(a.account) and chainIds.contains(a.chainId)) let balances = token.balancesPerAccount.filter(a => addresses.contains(a.account) and chainIds.contains(a.chainId))
for balance in balances: for balance in balances:

View File

@ -37,7 +37,6 @@ QtObject {
property string backButtonName: "" property string backButtonName: ""
property var overview: walletSectionOverview property var overview: walletSectionOverview
property var assets: walletSectionAssets.assets property var assets: walletSectionAssets.assets
property bool assetsLoading: walletSectionAssets.assetsLoading
property bool balanceLoading: overview.balanceLoading property bool balanceLoading: overview.balanceLoading
property var accounts: walletSectionAccounts.accounts property var accounts: walletSectionAccounts.accounts
property var receiveAccounts: walletSectionSend.accounts property var receiveAccounts: walletSectionSend.accounts

View File

@ -128,7 +128,7 @@ RightTabBaseView {
currentIndex: walletTabBar.currentIndex currentIndex: walletTabBar.currentIndex
AssetsView { AssetsView {
areAssetsLoading: RootStore.assetsLoading areAssetsLoading: RootStore.overview.balanceLoading
assets: RootStore.walletAssetsStore.groupedAccountAssetsModel assets: RootStore.walletAssetsStore.groupedAccountAssetsModel
networkFilters: RootStore.networkFilters networkFilters: RootStore.networkFilters
addressFilters: RootStore.addressFilters addressFilters: RootStore.addressFilters

View File

@ -82,7 +82,7 @@ ColumnLayout {
root.networkFilters root.networkFilters
root.addressFilters root.addressFilters
return root.networkFilters.split(":").includes(model.chainId+"") && return root.networkFilters.split(":").includes(model.chainId+"") &&
(!!root.addressFilters ? root.addressFilters.toUpperCase() === model.account.toUpperCase() : true) root.addressFilters.split(":").includes(model.account)
} }
expectedRoles: ["chainId", "account"] expectedRoles: ["chainId", "account"]
} }
@ -110,7 +110,10 @@ ColumnLayout {
name: "currentCurrencyBalance" name: "currentCurrencyBalance"
expression: { expression: {
if(!model.communityId) { if(!model.communityId) {
return model.currentBalance * model.marketDetails.currencyPrice.amount if (!!model.marketDetails) {
return model.currentBalance * model.marketDetails.currencyPrice.amount
}
return 0
} }
else { else {
return model.currentBalance return model.currentBalance