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 interact.js
:
const { ethers } = require("hardhat");
async function main() {
// Replace with your deployed contract address
const tokenAddress = "YOUR_DEPLOYED_TOKEN_ADDRESS"; // e.g., "0x5B...B7D"
// Connect to the deployed contract
const Token = await ethers.getContractFactory("MyToken");
const token = Token.attach(tokenAddress);
// Read the name and symbol of the token
const name = await token.name();
const symbol = await token.symbol();
console.log(`Token Name: ${name}`);
console.log(`Token Symbol: ${symbol}`);
// Read the total supply
const totalSupply = await token.totalSupply();
console.log(`Total Supply: ${totalSupply.toString()}`);
// Send tokens (if you have more than one account in Hardhat)
const [owner, addr1] = await ethers.getSigners();
const amount = ethers.utils.parseUnits("100", 18); // 100 tokens
console.log(`Transferring ${amount.toString()} tokens from ${owner.address} to ${addr1.address}`);
const transferTx = await token.transfer(addr1.address, amount);
await transferTx.wait();
console.log(`Transfer successful!`);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
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:
npx hardhat run scripts/interact.js --network localhost
Make sure to replace YOUR_DEPLOYED_TOKEN_ADDRESS
in the interact.js
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.