hardhat run with parameters

Viewed 3019

I need to run a particular ts script using hardhat from the command line but I need to specify parameters... Similar to this:

npx hardhat run --network rinkeby scripts/task-executor.ts param1 param2

Where the --network rinkeby is the parameter for the hardhat run
And param1 and param2 are parameters for the task-executor.ts script.
I couldn't find any post regarding this issue and I cannot make it work.

I also tried defining a hardhat task and added those parameters but if I try to execute it I get:

Error HH9: Error while loading Hardhat's configuration.    
You probably tried to import the "hardhat" module from your config or a file imported from it.
This is not possible, as Hardhat can't be initialized while its config is being defined.

Because I need to import hre or ethers from hardhat in that particular task.

Does anybody know how to accomplish what i need ??

Thanks a lot!!

2 Answers

According to Hardhat:

Hardhat scripts are useful for simple things that don't take user arguments, and for integrating with external tools that aren't well suited for the Hardhat CLI, like a Node.js debugger.

For scripts that require parameters, you should use Hardhat Tasks.

You can code the task in a different file than hardhat.config.ts. Here is an example task using positional parameters in the file sampleTask.ts:

import { task } from "hardhat/config";

task("sampleTask", "A sample task with params")
  .addPositionalParam("param1")
  .addPositionalParam("param2")
  .setAction(async (taskArgs) => {
    console.log(taskArgs);
  });

Remember to import it inside hardhat.config.ts:

import "./tasks/sampleTask";

Then run it with:

npx hardhat sampleTask hello world 

And it should print:

{ param1: 'hello', param2: 'world' }

You can read more about named, positional and optional parameters on tasks here.

If you need to use hre or ethers, you can get hre from the second parameter of the setAction function:

task("sampleTask", "A sample task with params")
  .addPositionalParam("param1")
  .addPositionalParam("param2")
  .setAction(async (taskArgs, hre) => {
    const ethers = hre.ethers;
  });

Usually it works like this:

const hre = require('hardhat'); 
const { ethers } = hre; 
Related