Web3 by Example: Querying an ERC20 Token Smart Contract

Let's get an real erc20 contract on the mainnet and see how it goes.

Take a look at the WETH contract on Etherscan. If the contract is verified, etherscan will show you the source code, abi and some other information. You can download the abi from this link.

Save and load it in the code.

We use weth address, abi and provider to create a contract instance.

Get the information of the contract is easy.

Oh, vitalik has 0.05 WETH.


const { ethers } = require("ethers");
const abi = require("./weth-abi.json");
(async () => {
const weth = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const provider = new ethers.providers.AlchemyProvider();
const instance = new ethers.Contract(weth, abi, provider);
const name = await instance.name();
const symbol = await instance.symbol();
const totalSupply = await instance.totalSupply();
const decimals = await instance.decimals();
const balance = await instance.balanceOf("vitalik.eth");
const allowance = await instance.allowance("vitalik.eth", weth);
console.log("weth", {
totalSupply: totalSupply.toString(),
decimals: decimals.toString(),
balance: ethers.utils.formatEther(balance),
allowance: allowance.toString(),


➜ node query-erc20.js
weth {
name: 'Wrapped Ether',
symbol: 'WETH',
totalSupply: '7118802459538305134330420',
decimals: '18',
balance: '0.05',
allowance: '0'

Next example: Subscribing to Event Logs(TODO)