From e0dc5045178087a0c0fe2eb4af9d42cf900c8455 Mon Sep 17 00:00:00 2001 From: Stephen Heaps Date: Thu, 8 Feb 2024 09:48:07 -0500 Subject: [PATCH] Fix race condition when an account is added while balances & prices are being fetched --- .../BraveWallet/Crypto/Stores/AccountsStore.swift | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Sources/BraveWallet/Crypto/Stores/AccountsStore.swift b/Sources/BraveWallet/Crypto/Stores/AccountsStore.swift index ee508957c23..30eefb67221 100644 --- a/Sources/BraveWallet/Crypto/Stores/AccountsStore.swift +++ b/Sources/BraveWallet/Crypto/Stores/AccountsStore.swift @@ -88,12 +88,13 @@ class AccountsStore: ObservableObject, WalletObserverStore { walletServiceObserver = nil } + private var updateTask: Task<(), Never>? func update() { - Task { @MainActor in + updateTask?.cancel() + updateTask = Task { @MainActor in self.isLoading = true defer { self.isLoading = false } - let allAccounts = await keyringService.allAccounts() let allNetworks = await rpcService.allNetworksForSupportedCoins() let allTokensPerNetwork = userAssetManager.getAllUserAssetsInNetworkAssets( networks: allNetworks, @@ -107,18 +108,21 @@ class AccountsStore: ObservableObject, WalletObserverStore { } let tokens = allTokensPerNetwork.flatMap(\.tokens) - var accountDetails = buildAccountDetails(accounts: allAccounts.accounts, tokens: tokens) + var allAccounts = await keyringService.allAccounts().accounts + var accountDetails = buildAccountDetails(accounts: allAccounts, tokens: tokens) self.primaryAccounts = accountDetails .filter(\.account.isPrimary) self.importedAccounts = accountDetails .filter(\.account.isImported) await updateBalancesAndPrices( - for: allAccounts.accounts, + for: allAccounts, networkAssets: allTokensPerNetwork ) - accountDetails = buildAccountDetails(accounts: allAccounts.accounts, tokens: tokens) + // if new accounts added while balances were being fetched. + allAccounts = await keyringService.allAccounts().accounts + accountDetails = buildAccountDetails(accounts: allAccounts, tokens: tokens) self.primaryAccounts = accountDetails .filter(\.account.isPrimary) self.importedAccounts = accountDetails