Web3 frontend part-3
Now that we have created instances of the smart contract to interact with the smart contract on chain the next step is to actually start calling the functions inside the smart contract.
For that the syntax is pretty simple. Let us understand with the help of a small example.
In this example we are dealing with the concept of ERC20
// create a new instance of the token contract
const tokenContract = new
Contract(TOKEN_CONTRACT_ADDRESS,TOKEN_CONTRACT_ABI,signer);
//Now that we have the instance we call the balanceOf function of this smart contract
//Notice that the address is passed in the form of the string
//The readonly functions are need not be validated/approved by the miner or the staker and hence execute its smart contract method in the EVM without sending any transaction.
let balance = await tokencontract.balanceOf("address")
//The balance is returned as a BigNumber.For eg:{ BigNumber: "2413468059122458201631" }
//Now we call a function transfer
//As the transfer function syntax has the address and uint as parameters we pass the address in the form of the string and uint in the form of the BigNumber
//For that we have some functions available in the ethers utils library
//The parseUnits will parse a string representing ether, such as 1.1 into a BigNumber in wei, and is useful when a user types in a value, such as sending 1.1 ether. The formatUnits will format a BigNumberish into a string, which is useful when displaying a balance
//Here as we are transfering some amount of dai tokens hence we are actually making a transaction
//The 18 indicates that there are 18 decimal places for the token/ether
let dai=await ethers.utils.parseUnits('1.1',18)
let tx = await tokencontract.transfer("toaddress", dai);
//The tx.wait() is a function which basically waits for the transaction to be validated by the staker and included in the blockchain.
await tx.wait();
console.log("The transaction is completed successfully");
Therefore calling a function inside a smart contract is actually very simple. You create an instance and then just call the function by its name passing the appropriate parameters.