Using the Hardhat console
The built-in console task starts a REPL that can be used to experiment with your contracts and the Hardhat Runtime Environment (HRE).
Starting the console
Section titled “Starting the console”To start a Hardhat console, run the following command:
npx hardhat consolepnpm hardhat consoleyarn hardhat consoleThe console tasks starts a Node.js REPL similar to the one you get when you run node in your terminal, but with some added features:
- The HRE and some of its properties are globally available
- Your project is built before the REPL starts
- It maintains a separate command history for each project
For example, you can deploy one of your contracts and interact with it within the console:
> const { viem } = await network.connect()> const counter = await viem.deployContract("Counter")> await counter.write.inc()> await counter.read.x()1nIf you don’t want to compile your project before starting the console, you can pass the --no-compile flag:
npx hardhat console --no-compilepnpm hardhat console --no-compileyarn hardhat console --no-compileRunning commands on startup
Section titled “Running commands on startup”The console task accepts an optional list of positional arguments. If provided, each of these arguments will be executed as a command immediately after the REPL starts. This can be useful for running a series of commands automatically:
npx hardhat console "const { viem } = await network.connect();" />pnpm hardhat console "const { viem } = await network.connect();" />yarn hardhat console "const { viem } = await network.connect();" />Make sure to wrap each command in quotes to avoid issues with your shell interpreting special characters.
You can also define a separate task that runs the console task with some predefined commands. For example:
import hardhatToolboxViemPlugin from "@nomicfoundation/hardhat-toolbox-viem";import { defineConfig, task } from "hardhat/config";
const myConsole = task( "my-console", "Starts a console with predefined commands",) .setAction(() => import("./tasks/my-console.js")) .build();
export default defineConfig({ plugins: [hardhatToolboxViemPlugin], solidity: "0.8.28", tasks: [myConsole],});export default function myConsoleTask(_, hre) { return hre.tasks.getTask("console").run({ commands: ["const { viem } = await network.connect();"], });}