11import { createAsyncThunk } from '@reduxjs/toolkit'
2- import { BigNumberish , Contract } from 'ethers'
2+ import { Contract } from 'ethers'
33import { BALANCE_STALE_TIME } from 'src/config/consts'
44import { TokenId , getTokenAddress , getTokenOptionsByChainId } from 'src/config/tokens'
55import { getProvider } from 'src/features/providers'
@@ -8,6 +8,8 @@ import { validateAddress } from 'src/utils/addresses'
88import { isStale } from 'src/utils/time'
99import { erc20ABI } from 'wagmi'
1010
11+ import { logger } from '../../utils/logger'
12+
1113interface FetchBalancesParams {
1214 address : string
1315 chainId : number
@@ -30,15 +32,34 @@ export const fetchBalances = createAsyncThunk<
3032 }
3133} )
3234
33- async function _fetchBalances ( address : string , chainId : number ) {
35+ async function _fetchBalances ( address : string , chainId : number ) : Promise < Record < TokenId , string > > {
3436 validateAddress ( address , 'fetchBalances' )
3537 const tokenBalances : Partial < Record < TokenId , string > > = { }
36- for ( const tokenId of getTokenOptionsByChainId ( chainId ) ) {
37- const tokenAddr = getTokenAddress ( tokenId , chainId )
38- const provider = getProvider ( chainId )
39- const tokenContract = new Contract ( tokenAddr , erc20ABI , provider )
40- const balance : BigNumberish = await tokenContract . balanceOf ( address )
41- tokenBalances [ tokenId ] = balance . toString ( )
38+ for ( const tokenSymbol of getTokenOptionsByChainId ( chainId ) ) {
39+ tokenBalances [ tokenSymbol ] = await getTokenBalance ( { address, chainId, tokenSymbol } )
4240 }
4341 return tokenBalances as Record < TokenId , string >
4442}
43+
44+ async function getTokenBalance ( {
45+ address,
46+ chainId,
47+ tokenSymbol,
48+ } : IGetTokenBalance ) : Promise < string | undefined > {
49+ const tokenAddress = getTokenAddress ( tokenSymbol , chainId )
50+ const provider = getProvider ( chainId )
51+ try {
52+ const tokenContract = new Contract ( tokenAddress , erc20ABI , provider )
53+ return ( await tokenContract . balanceOf ( address ) ) . toString ( )
54+ } catch ( error ) {
55+ // todo: Send such error to Sentry
56+ logger . error ( `Error on getting balance of '${ tokenSymbol } ' token.` , { error } )
57+ return undefined
58+ }
59+ }
60+
61+ interface IGetTokenBalance {
62+ address : string
63+ chainId : number
64+ tokenSymbol : TokenId
65+ }
0 commit comments