Hardhat is a flexible Ethereum development environment that allows developers to automate their workflows through custom tasks. Custom tasks are reusable scripts that you can execute from the command line, making it easier to perform repetitive actions like deploying contracts, checking balances, or running tests.
Step-by-Step Guide to Creating a Custom Task
Follow these steps to create a custom task in Hardhat:
- Set Up Your Hardhat Project: If you haven't already created a Hardhat project, you can do so by running the following commands:
mkdir my-hardhat-project
cd my-hardhat-project
npx hardhat
Follow the prompts to create a sample project.
1. Create the Tasks Directory
Inside your Hardhat project, create a new directory called tasks
if it doesn't already exist:
mkdir tasks
2. Define Your Custom Task
Next, create a new JavaScript file in the tasks
directory. For this example, we will create a task that retrieves and prints the balance of a specified Ethereum address. Create a file named getBalance.js
in the tasks
directory:
// tasks/getBalance.js
const { task } = require("hardhat/config");
task("getBalance", "Prints an account's balance")
.addParam("account", "The account's address")
.setAction(async (taskArgs, hre) => {
const balance = await hre.ethers.provider.getBalance(taskArgs.account);
console.log(`Balance of ${taskArgs.account}: ${hre.ethers.utils.formatEther(balance)} ETH`);
});
module.exports = {};
In this code:
- We import the
task
function fromhardhat/config
. - We define a new task named
getBalance
with a description. - We add a parameter called
tasks
0 to the task to specify the Ethereum address whose balance we want to check. - We use the
tasks
1 method to define the action that will be performed when the task is executed. Here, we retrieve the balance of the specified account and print it in Ether (ETH).
3. Running the Task
To run the custom task, you first need to ensure that you have a local Hardhat network running. In one terminal window, start the Hardhat node:
tasks
2
In another terminal window, you can execute your custom task using the following command:
tasks
3
Replace tasks
4 with the Ethereum address you want to check. This command will output the balance of the specified account.
4. Viewing All Available Tasks
To see all available tasks, including your custom tasks and built-in tasks, you can run:
tasks
5
This command will display a list of all tasks you can execute in your Hardhat project.
Conclusion
Creating custom tasks in Hardhat is a powerful way to automate your development workflow. By defining reusable scripts, you can simplify repetitive actions and enhance your productivity. Whether you are retrieving balances, deploying contracts, or performing other tasks, custom tasks provide a flexible solution tailored to your needs.