DEV Community

Jeremy Ikwuje for Monierate Engineering Blog

Posted on

Fix: ethers.getContract is not a function Hardhat Solidity

When you are trying to run a Solidity contract with hardhat run scripts/deploy.js you may experience getting the error "ethers.getContract is not a function".

To fix the error "ethers.getContract is not a function, ensure you install the package by running yarn add --dev hardhat @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers on your project terminal.

Open your terminal and run the following command:

yarn add --dev hardhat @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers
Enter fullscreen mode Exit fullscreen mode

If the "ethers.getContract is not a function" error is not resolved, or a new error emerges, try updating your scripts/deploy.js to the latest codes.

Assuming I have the following MyName.sol contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyName {
    function name() public pure returns(string memory) {
        return "Jeremy Ikwuje";
    }
}
Enter fullscreen mode Exit fullscreen mode

My deploy scripts will look like this:

const hre = require("hardhat");

async function main() {
  const MyName = await hre.ethers.getContractFactory("MyName");
  const name = await MyName.deploy();

  await name.deployed();

  console.log(await name.name());
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Saving this script as scripts/deploy-name.js, I will then go ahead and run the command below:

 npx hardhat run scripts/deploy-name.js
Enter fullscreen mode Exit fullscreen mode

That should work!

Conclusion

When trying to run a Solidity contract with hardhat run scripts/deploy.js you may experience getting the error "ethers.getContract is not a function". To fix the error, ensure you install the package by running yarn add --dev hardhat @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers on your project terminal. If a new error emerges, try updating your scripts/deploy.js to the latest codes on the documentation.

Top comments (0)