From 975dc4283f57f902db19f966f96f3d15767c02e6 Mon Sep 17 00:00:00 2001 From: Genaro Bonavita <98661193+genaroibc@users.noreply.github.com> Date: Wed, 17 Jan 2024 12:11:31 -0300 Subject: [PATCH] Fix v1/multicall balances (#276) * fix: get native balances using getBalance * fix: add kava to chains without multicall list --- src/services/getEvmBalances.ts | 49 ++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/src/services/getEvmBalances.ts b/src/services/getEvmBalances.ts index c8def5df..752c2baf 100644 --- a/src/services/getEvmBalances.ts +++ b/src/services/getEvmBalances.ts @@ -9,7 +9,7 @@ import { type ContractAddress = `0x${string}`; -const CHAINS_WITHOUT_MULTICALL = [314, 3141]; // Filecoin, & Filecoin testnet +const CHAINS_WITHOUT_MULTICALL = [314, 3141, 2222]; // Filecoin, Filecoin testnet and Kava const getTokensBalanceSupportingMultiCall = async ( tokens: TokenData[], @@ -94,23 +94,12 @@ const getTokensBalanceWithoutMultiCall = async ( ): Promise => { const balances: (TokenBalance | null)[] = await Promise.all( tokens.map(async t => { - let balance: TokenBalance | null; try { - if (t.address === NATIVE_EVM_TOKEN_ADDRESS) { - balance = await fetchBalance({ - token: t, - userAddress, - rpcUrl: rpcUrlsPerChain[t.chainId] - }); - } else { - balance = await fetchBalance({ - token: t, - userAddress, - rpcUrl: rpcUrlsPerChain[t.chainId] - }); - } - - return balance; + return await fetchBalance({ + token: t, + userAddress, + rpcUrl: rpcUrlsPerChain[t.chainId] + }); } catch (error) { return null; } @@ -199,6 +188,10 @@ async function fetchBalance({ userAddress, rpcUrl }: FetchBalanceParams): Promise { + if (token.address.toLowerCase() === NATIVE_EVM_TOKEN_ADDRESS.toLowerCase()) { + return fetchNativeBalance({ token, userAddress, rpcUrl }); + } + try { const provider = new ethers.providers.JsonRpcProvider(rpcUrl); @@ -228,3 +221,25 @@ async function fetchBalance({ return null; } } + +async function fetchNativeBalance({ + userAddress, + rpcUrl, + token +}: FetchBalanceParams) { + try { + const provider = new ethers.providers.JsonRpcProvider(rpcUrl); + const balance = await provider.getBalance(userAddress); + + return { + address: token.address, + balance: balance.toString(), + decimals: token.decimals, + symbol: token.symbol, + chainId: token.chainId + }; + } catch (error) { + console.error("Error fetching native token balance:", error); + return null; + } +}