From 28f50a10c64ce09116e26fc6ae388fbf99a7fda2 Mon Sep 17 00:00:00 2001 From: Nathan Seva Date: Wed, 5 Jun 2024 12:13:48 -0500 Subject: [PATCH] perf: getAssetsData fetch async --- internal/handler/wallet/get_all_assets.go | 42 +++++++++++++++++------ 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/internal/handler/wallet/get_all_assets.go b/internal/handler/wallet/get_all_assets.go index 47895934d..7904d0fcb 100644 --- a/internal/handler/wallet/get_all_assets.go +++ b/internal/handler/wallet/get_all_assets.go @@ -3,6 +3,7 @@ package wallet import ( "fmt" "sort" + "sync" "github.com/go-openapi/runtime/middleware" "github.com/massalabs/station-massa-wallet/api/server/models" @@ -111,21 +112,42 @@ func (g *getAllAssets) getAssetsData(acc *account.Account) ([]*assets.AssetInfoW assetsInfo := g.AssetsStore.All(acc.Nickname) assetsWithBalance := make([]*assets.AssetInfoWithBalances, 0) + var wg sync.WaitGroup + mu := &sync.Mutex{} + resultsCh := make(chan *assets.AssetInfoWithBalances) // Retrieve all assets from the selected nickname for _, asset := range assetsInfo { - // First, check if the asset exists in the network - if !g.massaClient.AssetExistInNetwork(asset.AssetInfo.Address) { - logger.Infof("Asset %s does not exist in the network", asset.AssetInfo.Address) - continue - } + wg.Add(1) + + go func(asset *assets.AssetInfoWithBalances) { + defer wg.Done() + + // First, check if the asset exists in the network + if !g.massaClient.AssetExistInNetwork(asset.AssetInfo.Address) { + logger.Infof("Asset %s does not exist in the network", asset.AssetInfo.Address) + return + } + + // Fetch the balance for the current asset + balance, dollarValue := g.fetchAssetData(asset, acc) + + asset.Balance = balance + asset.DollarValue = dollarValue + + resultsCh <- asset + }(asset) + } - // Fetch the balance for the current asset - balance, dollarValue := g.fetchAssetData(asset, acc) + go func() { + wg.Wait() + close(resultsCh) + }() - asset.Balance = balance - asset.DollarValue = dollarValue - assetsWithBalance = append(assetsWithBalance, asset) + for result := range resultsCh { + mu.Lock() + assetsWithBalance = append(assetsWithBalance, result) + mu.Unlock() } return assetsWithBalance, nil