Interact with SmartContracts - NodeJs+HardHat
Here we are going to see, how to interact with smart contract to fetch the ABI and deployed contract address.
In our previous posts, we explained HardHat setup and basic contract deployment.
Please look into that, if you have any queries on setup and contract deployment.
Retrieve the ABI of the contract
ABI - Application Binary Interface
It is a collection of rules and definitions, which helps interact between program modules.
To fetch the ABI of the contract by hardhat
Ensure the contract has been compiled using hardhat, by running this command
npx hardhat compile
Here's the sample code to retrieve the ABI
const { ethers } = require("hardhat");
async function main() {
const contractName = "SimpleStorage";
const artifact = await ethers.getContractFactory(contractName);
const abi = artifact.interface.format("json");
console.log("ABI:", abi);
}
main();
By calling this function, we can see the fetch of the ABI of the contract.
Fetch the deployed contract address.
Contract address is the identifier of the deployed contract address on a blockchain network, by using the address we can contract with smart contracts.
After the hardhat compilation, execute this function to get the contract address.
const { ethers } = require("hardhat");
async function main() {
const SimpleContract = await ethers.getContractFactory("SimpleStorage");
const simpleContract = await SimpleContract.deploy();
const receipt = await simpleContract.waitForDeployment();
console.log("Contract deployed to:", await simpleContract.getAddress());
}
main();
Don't forget to add the hardhat config in the hardhat.config.json
require("@nomicfoundation/hardhat-toolbox");
module.exports = {
solidity: "0.8.27",
networks:{
sepolia: {
url: `https://sepolia.infura.io/v3/${Infura Key}`,
accounts: [`${Wallet Private Key}`],
chainId: 11155111, // Sepolia testnet chain ID
},
}
};