A task vs a script in Hardhat

particle4dev

Nam Hoang

Posted on March 25, 2024

A task vs a script in Hardhat

Understanding the Distinctions Between Tasks and Scripts in Hardhat

It's crucial to grasp that nearly everything achievable with a task can also be accomplished with a script, and vice versa. However, there are nuances: certain actions are exclusive to tasks or scripts, and some tasks are more suited to one or the other.

Tasks:

One fundamental capability exclusive to tasks is the ability to override another task. For instance, consider augmenting your test workflow:

task("test", async (args, hre, runSuper) => {
  // Perform additional actions
  return runSuper();
})
Enter fullscreen mode Exit fullscreen mode

What about custom tasks? In this scenario, tasks and scripts are essentially interchangeable. The primary advantage of utilizing a task lies in integrating with Hardhat's argument parser. For instance, when developing a token and needing to verify an address's balance on a specific network, you might execute:

hh balance --address 00x4403B5d2Fed270D18b6d83122C818c2413D9BC05 --network mainnet
Enter fullscreen mode Exit fullscreen mode

(Where 'hh' represents the Hardhat shorthand.)

Scripts:

One distinctive feature of scripts is their executability directly via Node.js. Instead of:

hh run my-script.js
Enter fullscreen mode Exit fullscreen mode

You have the option to use:

node my-script.js
Enter fullscreen mode Exit fullscreen mode

This flexibility enables additional functionalities such as passing extra flags to the Node.js binary. Furthermore, it facilitates execution with alternative binaries like ts-node, ndb, or mocha.

It's worth noting that when adopting this approach, explicit importation of the Hardhat Runtime Environment is necessary:

const hre = require("hardhat");
Enter fullscreen mode Exit fullscreen mode

Alternatively, utilize:

node --require hardhat/register my-scripts.js
Enter fullscreen mode Exit fullscreen mode

to ensure the availability of globally scoped variables, akin to those accessible when using 'hh run'.

Another rationale for employing scripts is the ability to leverage alternative argument-parsing libraries like commander, rather than relying on Hardhat's built-in parser.

However, bear in mind that this approach forfeits the ability to specify the network using the '--network' parameter. In such cases, setting the 'HARDHAT_NETWORK' environment variable becomes necessary:

HARDHAT_NETWORK=rinkeby node my-scripts.js
Enter fullscreen mode Exit fullscreen mode

Understanding these distinctions empowers developers to choose the appropriate tool—task or script—based on the specific requirements of their development workflow.

References:

💖 💪 🙅 🚩
particle4dev
Nam Hoang

Posted on March 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

A task vs a script in Hardhat
hardhat A task vs a script in Hardhat

March 25, 2024