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.
How to accomplish what i need?
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;
});
You can use environment and access via process.env
On Linux:
param1=some param2=thing npx hardhat run scripts/task-executor.ts
And print with:
console.log(process.env.param1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With