[Ethereum] Find address of a contract before deployment in Hardhat and Ethers.js

ethers.jshardhatnodejs

I have 2 contracts which take each other's addresses as constructor arguments. Here's the pseudocode,

constructor A(address B)
constructor B(address A)

I am deploying contracts using

const Contract = await ethers.getContractFactory(contractName)
const contract = await Contract.deploy(...args)
await contract.deployed()

console.log(contract.address) // I want to find address before, not after deployment

How to find the contract address before deployment?

Best Answer

@ethersproject/address provides a getContractAddress() function to find future deployment address.

const { ethers } = require('hardhat')
const { getContractAddress } = require('@ethersproject/address')

async function main() {
  const [owner] = await ethers.getSigners()

  const transactionCount = await owner.getTransactionCount()

  const futureAddress = getContractAddress({
    from: owner.address,
    nonce: transactionCount
  })
}
Related Topic