Skip to main content

Reading Data From a Contract

Interacting

On EVM the contracts may hold data in a private way, which means it is not accessible to the public. However, the contracts may have public methods to read the data. These methods are called view or pure methods. The view methods are the ones that read data from the blockchain, while the pure methods are the ones that do not read data from the blockchain. Both methods are free to use and do not require any signing.

To execute a read function, you need to instantiate a contract object and call the method you want to execute. In this chapter, we will show how to read the balanceOf method from the ERC20 contract using JsonRpcProvider as the provider for remote access to the blockchain.

Create the web3 provider

First, we need to create a web3 provider. In this example, we will use the JsonRpcProvider as the provider for remote access to the blockchain.

async web3Provider(): Promise<ethers.providers.Web3Provider> {
const RPC_ENDPOINT = {
protocol: 'https',
host: 'mainnet.telos.net',
port: 443,
path: '/evm',
};
const url = `${RPC_ENDPOINT.protocol}://${RPC_ENDPOINT.host}:${RPC_ENDPOINT.port}${RPC_ENDPOINT.path ?? ''}`;
const web3Provider = new ethers.providers.JsonRpcProvider(url);
await web3Provider.ready;
return web3Provider as ethers.providers.Web3Provider;
}

Create the contract object

Then, we need to create a contract object. In this example, we will use the ERC20 contract.

const provider = await this.web3Provider();
// you don't need the whole ABI, just the methods you want to call
const erc20Abi = [
'function balanceOf(address account) view returns (uint256)',
];
const erc20Contract = new ethers.Contract(token, erc20Abi, provider);

Call the method

Finally, we need to call the method. In this example, we will call the balanceOf method.

const balance: ethers.BigNumber = await erc20Contract.balanceOf(address);

// you can convert the balance to a number using the ethers.utils.formatUnits method
const tokenDecimals = 18;
const balanceNumber: number = ethers.utils.formatUnits(balance, tokenDecimals);

Conclusion

In this chapter we have shown how to read data from a contract using the view methods, performing a remote call to the blockchain endpoint through the JsonRpcProvider provider. You can execute any view or pure method from any contract using the same approach. All you need is a provider and the contract ABI.