Get the tokens balances of a wallet
In this blog post we will see how to get and display the balance of particular tokens in a wallet. We will see how to do it in cliend side and server side.
We will use the the code from the previous post to get started. If you haven't read it yet, you can find it here.
The useBalance hook
Fetching balance of a token on client side is pretty straightforward. We just need to use the useBalance hook from the wagmi package.
Like this :
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>
)
The data result contains the followings props :
formatted : the balance formatted with the correct number of decimals
symbol : the symbol of the token
decimals : the number of decimals of the token
balance : the balance as a BigNumber
The hook also allow to fetch balance of others tokens than ETH and allow to fetch the token's balance on other chains. To do so we need to provide the address of the token's contract and the chainId of the chain.
const { data, isError, isLoading } = useBalance({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
token: '0x539bdE0d7Dbd336b79148AA742883198BBF60342',
chainId: 42161,
})
This sample code fetch the balance of the Magic token on the Arbitrum chain. To be able to do that, we need configure the chains in the wagmi config.
We did this on the _app.tsx
file.
const { chains, provider } = configureChains(
[mainnet, arbitrum],
[
alchemyProvider({ apiKey: process.env.ALCHEMY_ID as string }),
publicProvider(),
]
)
Fetch balance on server side
We can also fetch the token balance from the server side using ethers.js and Alchemy.
First we need to add an api route to our app. We will use the api folder for that.
Create a file named api/getBalance.ts
and add the following code :
import type { NextApiRequest, NextApiResponse } from 'next'
import { erc20ABI } from 'wagmi'
import { formatEther } from 'ethers/lib/utils.js'
type Data = {
balance: string
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const provider = new ethers.providers.AlchemyProvider(
'arbitrum',
process.env.ALCHEMY_ID
)
const magicContract = new ethers.Contract(
'0x539bdE0d7Dbd336b79148AA742883198BBF60342',
erc20ABI,
provider
)
const balance = await magicContract.balanceOf(req.query.address)
res.status(200).json({ balance: formatEther(balance) })
}
In this function we fetch the balance of the Magic token of the address provided in the query params. First we need to create a provider for the Arbitrum chain. We use the Alchemy provider for that. Then we create a contract instance of the Magic token and call the balanceOf method to get the balance of the address. And because the value is returned in wei, we need to format it with the formatEther to get the number formatted correctly.
You can now call this api route from the client side to get the balance of a wallet.
const [magicBalance, setMagicBalance] = useState<string | undefined>(undefined)
useEffect(() => {
fetch('/api/getBalance?address=0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')
.then((response) => response.json())
.then((data) => setMagicBalance(data.balance))
}, [])
Conclusion
We have seen how to fetch the balance of a wallet on client side and server side. You can now take this code as a base to build your own app and improve it to fit your needs. You can find the code of this post on github