Ethers.js – How to Get Deployed Contract Address with Ethers

ethers.jshardhathardhat-deploytypechaintypescript

I using hardhat deploy (TypeScript) and am deploying two contracts: the first is a mock ERC20 token and a second is a crowdfunding contract that uses the mock when on a hardhat chain/localhost.

I am trying to get the address of the MockToken contract for my Crowdfund contract.

I used to just use:

mockToken: MockToken = await ethers.getContract('MockToken');
mockTokenAddress = mockToken.address

Now I am getting the error in TS that "Property 'getContract' does not exist on type" for ethers

Does anyone have any clue how to solve this? The scripts are labeled 00__deployMockToken and 01__deployCrowdfund so the mock is always deployed before the Crowdfund.

Thanks!

Best Answer

The answer by @AlexanderHerranz is for ethers v5, for newer versions of hardhat that use ethers v6 you can get the deployed address using the async getAddress() method as shown below:

const MyContractFactory = await ethers.getContractFactory("MyContract")

const myContract = (await MyContractFactory.connect(signer).deploy());
await myContract.waitForDeployment();
const myContractDeployedAddress = await myContract.getAddress();