-1

I need to display the different balances of supported chains when I am connected to my wallet using wagmi. Say, I connect using Metamask connector and in the supported chains array, and I have [polygon, base, optimism] as the array, I can only get the balance of my overall account using the useBalance() hook provided as shown below

import { useBalance } from 'wagmi'
 
function App() {
  const { data, isError, isLoading } = useBalance({
    address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
  })
 
  if (isLoading) return <div>Fetching balance…</div>
  if (isError) return <div>Error fetching balance</div>
  return (
    <div>
      Balance: {data?.formatted} {data?.symbol}
    </div>
  )
}

But I need to display the different balance of each chain as done in opensea website and shown aboveOpensea display of supported chains balance

I tried using the useAccount hook provided by Wagmi

const { address, isConnected, connector: activeConnector } = useAccount();

Then using it as:

      {activeConnector?.chains.map((chain) => {
                    if (chain.network !== "goerli") {
                      return (
                        <div key={chain.id} className={styles.chain}>
                          <div>
                            <ChainLogos chainId={chain.network} />
                            <div>
                              <p>{`${chain.network}`}</p>
                              <span>{chain.name}</span>
                            </div>
                          </div>

                          <div>
                            <div>
                              <p>0.324</p>
                              <span>$0.34 USD</span>
                            </div>

                            <BsThreeDotsVertical />
                          </div>
                        </div>
                      );
                    }

                    
            })} 

But the individual chains do not have a balance property that could display the balance of supported chain.

1 Answers1

0

Use fetchBalance method with the chainId for each network. For example:

import { fetchBalance } from '@wagmi/core'

const balance = await fetchBalance({
  address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
  chainId: 1,
})

Refer this for more: https://wagmi.sh/core/actions/fetchBalance#chainid-optional

bk7159
  • 1