Skip to content

Calling read only functions (from the browser)

Course: Client side ETH - chapter 5

Ref - https://wagmi.sh/react/guides/read-from-contract

https://etherscan.io/address/0xdac17f958d2ee523a2206206994597c13d831ec7#code

We first need to get the abi of the contract. For the USDT contract, the ABI looks like this -

$1b

We can trim it down to just the functions we need (contract.ts) -

export const contract = {
address: '0xdac17f958d2ee523a2206206994597c13d831ec7',
abi: [
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
}

The **[useReadContract](https://wagmi.sh/react/api/hooks/useReadContract)** Hook allows you to read data on a smart contract, from a view or pure (read-only) function. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.

Create TotalBalance.tsx

import { useReadContract } from 'wagmi'
import { contract } from './contract'
export function TotalBalance() {
const { data, isLoading, error } = useReadContract({
address: '0xdac17f958d2ee523a2206206994597c13d831ec7',
abi: [
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
],
functionName: 'totalSupply',
})
return (
<div>
Total supply - {JSON.stringify(data?.toString())}
</div>
)
}
curl \
-X POST \
-H "Content-Type: application/json" \
--data '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [
{
"to": "0xdac17f958d2ee523a2206206994597c13d831ec7",
"data": "0x18160ddd"
},
"latest"
],
"id": 1
}' \
https://eth-mainnet.g.alchemy.com/v2/nnY0qPUQLYsUvb5BKJM5bh81sI6O0PQG
Can you figure out how to get the balance of a user ?
import { useReadContract } from 'wagmi'
import { contract } from './contract'
export function TotalBalance() {
const { data, isLoading, error } = useReadContract({
address: '0xdac17f958d2ee523a2206206994597c13d831ec7',
abi: [
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "balance",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
],
functionName: 'balanceOf',
args: ["0x587EFaEe4f308aB2795ca35A27Dff8c1dfAF9e3f"]
})
return (
<div>
Balance - {JSON.stringify(data?.toString())}
</div>
)
}