3

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!

2

2 Answers 2

4

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();
1
  • Have my upvote, I was looking for this.
    – Iván
    Oct 28, 2023 at 13:22
1

You can deploy a contract, and get the new contract address, using Ethers.js' ContractFactory.

import { ContractFactory } from 'ethers';

const factory = new ContractFactory(contractAbi, contractByteCode);

// If your contract requires constructor args, you can specify them here
const contract = await factory.deploy(deployArgs);

console.log(contract.address);
console.log(contract.deployTransaction);

You can check out more about Contract Factory, from ethers, here: https://docs.ethers.io/v5/api/contract/contract-factory/

2
  • hmmm yes I understand how to deploy the contract but how do I get the contract if it is already deployed and I just dont have the address? Feb 17, 2023 at 15:05
  • In the provided example you are deploying the contract and getting the address (contract.address) afterwards. The error you see is because you are not referencing to an already deployed contract. Feb 17, 2023 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.