Robert's Homepage

Troubleshoot - The Hardhat Deploy Blues

#hardhat #ethereum #solidity

Error: Cannot find deployed hardhat-deploy contracts

Background

Problem Statement

When attempting to write a Hardhat task in hardhat.config.js to interact with the deployed contract sing the getContract helper from hardhat-deploy plugin, ethers.getContract("MyTokenContract") throws an error saying “MyTokenContract does not exist”

Solution

When you execute a task in Hardhat, an in-process Hardhat network is started automatically which is NOT your standalone instance. This instance is specified via –network hardhat.

To interact with contracts deployed to your standalone (e.g. npx hardhat node) instance you need to provide the --network localhost argument.

Explanation

Hardhat comes with a local “Hardhat Network”, which according to the documentation :

When Hardhat executes your tests, scripts or tasks, an in-processHardhat Network node is started automatically, and all of Hardhat’s plugins (ethers.js, web3.js, Waffle, Truffle, etc) will connect directly to this node’s provider.

When you are running npx hardhat node, you create a standalone JSON-RPC server that runs on localhost rather than in-process. If you want hardhat to connect to this localhost instance you must provide the --network localhost argument. Otherwise, the in-process instance (--network hardhat) will be used by default instead which is transient.

Therefore, if you simply want to quickly verify compilation, deployment, etc, you can use the default hardhat network option (i.e. no --network parameter). However, if you want to test persistent state behaviour (like a Docker container instance running a Postgres database), you need to provide –network localhost to the hardhat task runner. This will ensure hardhat is pointed to the right network.