Error using Hardhat: TypeError:ethers.getContractFactory is not a function

I know ethers.getContractFactory is a function so am wondering what am missing. Maybe importing something?

:computer: Environment
Truffle v5.1.67 (core: 5.1.67)
Solidity v0.5.16 (solc-js)
Node v12.19.0
Web3.js v1.2.9


:1234: Code to reproduce
Here is the first part of the code, everything seems ok, no?

const { expect } = require('chai');

const { ethers } = require('ethers');

describe('Token contract', () => {

    let Token, token, owner, addr1, addr2;

    beforeEach(async () => {

        Token = await ethers.getContractFactory("Token");

        token = await Token.deploy();

        [owner, addr1, addr2, _] = await ethers.getSigners();


    describe('Deployment', () => {

        it('Should set the right owner', async () => {

            expect(await token.owner()).to.equal(owner.address);


        it('Should assign the total supply of tokens to the owner', async () => {

            const ownerBalance = await token.balanceOf(owner.address);

            expect(await token.totalSupply()).to.equal(ownerBalance);


1 Like

I think you should remove this line

const { ethers } = require('ethers');

thanks, can you explain why this line needs to be removed?

const { ethers } = require("ethers"); should be replaced by const { ethers } = require("hardhat"); or removed as it is available in the global scope.


Hi, welcome! :wave:

I think it is available in the global scope.

This worked for me…

const hre = require("hardhat");
const {
} = require('chai');

describe("NFT", () => {
  it("It should deploy the contract, mint a token, and resolve to the right URI", async () => {
    const NFT = await hre.ethers.getContractFactory("UkuNFT");
    const nft = await NFT.deploy();
    const URI = "ipfs://QmWJBNeQAm9Rh4YaW8GFRnSgwa4dN889VKm9poc2DQPBkv";
    await nft.deployed();
    await"0x09.............................", URI)
    expect(await nft.tokenURI(1)).to.equal(URI)

I got this same issue. This is because when you use “ethers” vscode automatically imports it into the file, which disrupts the global declaration.

1 Like

A post was merged into an existing topic: A contract that can't estimate gas while selling, but can buy Without issue