Interact with SmartContracts - NodeJs+HardHat

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.

  • Encoding the data while sent to Ethereum Machines.
  • Decoding the data when received back.
  • Listing all the functions of the contract including their return types and parameters.
  • Used for External app communication like dApps.


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.

ABI



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();
        


Deployed Contract Address

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
     },
  }
};


        


要查看或添加评论,请登录

Nanthakumar D的更多文章