Interacting with deployed smart contracts is a crucial part of Ethereum development. Hardhat provides a straightforward way to connect to and interact with your contracts after deployment. In this guide, we will cover how to interact with deployed contracts using Hardhat, including reading data from contracts and sending transactions.

1. Prerequisites

Before you begin, ensure that you have the following:

  • A Hardhat project set up with at least one deployed smart contract.
  • The ethers library, which is included with Hardhat.

2. Deploying a Sample Contract

For demonstration purposes, let’s create a simple ERC20 token contract. First, create a new contract file in the contracts directory, e.g., MyToken.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
constructor(string memory name, string memory symbol, uint256 initialSupply) ERC20(name, symbol) {
_mint(msg.sender, initialSupply * (10 ** uint256(decimals())));
}
}

Next, create a deployment script in the scripts directory named deploy.js:

const { ethers } = require("hardhat");

async function main() {
const Token = await ethers.getContractFactory("MyToken");
const token = await Token.deploy("MyToken", "MTK", 1000000);
await token.deployed();
console.log(`Token deployed to: ${token.address}`);
}

main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

Run the deployment script:

npx hardhat run scripts/deploy.js --network localhost

Make sure to keep the Hardhat network running in another terminal using:

npx hardhat node

3. Interacting with the Deployed Contract

Now that we have a deployed contract, let’s interact with it. Create a new script in the scripts directory named contracts0:

contracts1

In this script, we:

  • Connect to the deployed contract using its address.
  • Read the token's name, symbol, and total supply.
  • Transfer tokens from one account to another.

4. Running the Interaction Script

To run the interaction script, execute the following command in your terminal:

contracts2

Make sure to replace contracts3 in the contracts0 script with the actual address of your deployed token from the deploy.js output. You should see the token's name, symbol, total supply, and a confirmation of the token transfer in the console output.

Conclusion

Interacting with deployed contracts using Hardhat is a straightforward process that allows developers to read data and send transactions easily. By following the steps outlined in this guide, you can effectively manage your smart contracts and perform various operations on them. This capability is essential for building decentralized applications (dApps) and ensuring that your contracts function as intended in a live environment.