3

I'm working with hardhat's local network, and I want to get the address of a deployed contract. I want to avoid deploying the contract again just to get the new address; I want to get the existing contract address, and then interact with it (so basically I have one script to deploy it, another one to interact with it).

In Truffle, the artifacts contain this contract address field, but not in hardhat. I reviewed the transactions manually (using eth_getTransactionByHash and eth_getBlockByNumber) but I get all the information needed except the contract address.

Shouldn't it be possible to get it somehow?

3 Answers 3

2

I'm not sure how you could get it afterwards.

What I do in my depoyment script is that I save the address to a JSON file for frontend to use. My (a bit cleaned up) is like this:

async function saveFrontendFiles(tokenAddr: string) {
  const contractsDir = __dirname + "/../website/src/contracts";

  if (!fs.existsSync(contractsDir)) {
    fs.mkdirSync(contractsDir);
  }

  fs.writeFileSync(
    contractsDir + "/contract-address.json",
    JSON.stringify(
      {
        Token: tokenAddr
      },
      undefined,
      2
    )
  );

  const TokenArtifact = artifacts.readArtifactSync("MyTokenMock");

  fs.writeFileSync(
    contractsDir + "/Token.json",
    JSON.stringify(TokenArtifact, null, 2)
  );
}
1
  • I see, that could work in my set up, thanks!
    – bakeiro
    Commented Feb 1, 2022 at 15:03
0

I encountered the same problem. It is now possible out of the box. (as far as I know)

While writing a custom solution where I would store the addresses of the deployed contract in a .json file (like in Truffle), I discovered that there is a plugin called hardhat-deploy that is able to do this.

2
0

Not entirely sure this answers your question, but I was looking back a project I had deployed a while back and figuring out the contract address for it. When I deployed it at the time using hardhat, you have to write the abi and contract into a .json file. This will be something you code into your deployment script. Something like:

await xxxx.deployed();

//Pull the address and ABI out while you deploy, since that will be key in interacting with the smart contract later
const data = {
    address: xxxx.address,
    abi: JSON.parse(xxxx.interface.format("json")),
  };

fs.writeFileSync("./src/xxxx.json", JSON.stringify(data));

So for an existing project, look for what json you produced through your deployment script. The first key for the json file will be the contract address.

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.