Writing scripts with Hardhat
In this guide, we’ll walk through creating a script with Hardhat. For a general overview of using Hardhat, refer to the getting started guide.
You can write your own custom scripts that use all of Hardhat’s functionality. For example, in this guide, we’ll create a script that prints the list of available accounts.
Writing a script
Section titled “Writing a script”Hardhat is designed as a library, so you can use it in any TypeScript or JavaScript file. All you need to do is import the Hardhat Runtime Environment like this:
import hre from "hardhat";This gives you access to all of Hardhat’s functionality.
Let’s try this out. Create a new directory called scripts in your project’s root directory, and inside it, create a file called accounts.ts with the following content:
import hre from "hardhat";
const { provider } = await hre.network.connect();const accounts = await provider.request({ method: "eth_accounts" });
if (accounts !== null) { for (const account of accounts) { console.log(account); }} else { console.log("No accounts found");}And you can run it like this:
npx hardhat run scripts/accounts.tspnpm hardhat run scripts/accounts.tsyarn hardhat run scripts/accounts.tsWhen you do this, Hardhat will compile your contracts before running the script.
Running a Hardhat script without the Hardhat CLI
Section titled “Running a Hardhat script without the Hardhat CLI”You can also run your scripts as standalone TypeScript files with Node.js, like this:
node scripts/accounts.tsThis lets you skip the Hardhat CLI if you want, and use Hardhat from other Node.js tools, like vitest.
Passing Global Option values to standalone scripts
Section titled “Passing Global Option values to standalone scripts”When running a standalone script, you can pass any Hardhat Global Option to the script by setting a HARDHAT_<GLOBAL_OPTION> environment variable:
-
HARDHAT_NETWORK: Sets the network to connect to -
HARDHAT_BUILD_PROFILE: Specifies which build profile to use -
HARDHAT_VERBOSITY: Sets the verbosity level that controls the execution traces shown when running the script
To view the full list of Global Options available in Hardhat, run:
npx hardhat --helppnpm hardhat --helpyarn hardhat --helpDebugging scripts with execution traces
Section titled “Debugging scripts with execution traces”When your script connects to a simulated network, you can use the --verbosity (or -v) flag to show execution traces. For example, -vvv shows traces for failing transactions:
npx hardhat run scripts/deploy.ts -vvvpnpm hardhat run scripts/deploy.ts -vvvyarn hardhat run scripts/deploy.ts -vvvTo see traces for all transactions, use -vvvvv:
npx hardhat run scripts/deploy.ts -vvvvvpnpm hardhat run scripts/deploy.ts -vvvvvyarn hardhat run scripts/deploy.ts -vvvvvExecution traces show the sequence of contract function calls, making it easier to debug deployment scripts and understand complex interactions. See the Displaying execution traces guide for more details.