Writing Hardhat tasks
At its core, Hardhat is a task runner that lets you automate your development workflow. It comes with built-in tasks like compile and test, but you can also add your own custom tasks.
This guide will show you how to extend Hardhat’s functionality using tasks. It assumes you’ve initialized a sample project. If you haven’t, please read the getting started guide first.
Writing a task
Section titled “Writing a task”Let’s write a simple task that prints the list of available accounts. This will help you understand how tasks work and how to create your own.
First, copy and paste the following code into your Hardhat config file:
import { defineConfig, task } from "hardhat/config";
const printAccounts = task("accounts", "Print the accounts") .setAction(() => import("./tasks/accounts.js")) .build();Now let’s create a tasks/accounts.ts file with the task action, which contains the logic that the task will run:
import { HardhatRuntimeEnvironment } from "hardhat/types/hre";
interface AccountTaskArguments { // No argument in this case}
export default async function ( taskArguments: AccountTaskArguments, hre: HardhatRuntimeEnvironment,) { const { provider } = await hre.network.connect(); console.log(await provider.request({ method: "eth_accounts" }));}Next, add the printAccounts task to the exported configuration object in your Hardhat config file:
export default defineConfig({ // ... rest of the config tasks: [printAccounts],});Now you should be able to run it:
npx hardhat accountspnpm hardhat accountsyarn hardhat accountsWe’re using the task function to define our new task. Its first argument is the name of the task, which is what we use on the command line to run it. The second argument is the description, which appears when you run hardhat help.
The task function returns a task builder object that lets you further configure the task. In this case, we use the setAction method to define the task’s behavior by providing a function that lazy loads another module.
That module exports the action function itself. You can do anything you want in this function. In this case, we send a request to the network provider to get all the configured accounts and print their addresses.
You can add parameters to your tasks, and Hardhat will handle their parsing and validation for you. You can also override existing tasks, which lets you customize how different parts of Hardhat work.