Skip to main content

Read contract

We will use an instance of an already deployed Watermelon ERC-20 token from our previous article.

note

If you want to test the ERC-20 transfers in the Write Contract section below – please go through the ERC-20 tutorial, and deploy your own Watermelon contract to mint tokens to your account and use them there.

For the quickstart you can just read through the code here:


Our goal is simple, call the balanceOf function on the ERC-20 contract to get our Watermelon balance:

dapp_read_contract

We do this by specifying the contract information:

import { erc20Abi } from 'viem';

const erc20Address = '0xF257a66Ddf715049E32aEe591Dc5Ef107B9d9340';
const contractConfig = {
abi: erc20Abi,
address: erc20Address,
};

note

The core part of it is the contract's ABI. If you don't know what is it and where to get it, please read these articles: 1, 2, 3. In simple terms, it allows communication with a contract and shows what its methods look like.

After that, we just need to add useReadContract Wagmi hook to call a balanceOf function:

export function ERC20Balance() {
...
const {
data: balance,
error,
isPending,
} = useReadContract({
...contractConfig,
functionName: 'balanceOf',
args: [address],
});

if (isPending) return <div>Loading...</div>;

if (error)
return (
<div>Error: {(error as BaseError).shortMessage || error.message}</div>
);

return (
<div className="container">
Your 🍉Watermelon🍉 Balance: {balance?.toString()}WTM
</div>
);
}