0

I have a constant variable in my solidity:

address private constant MY_ADDRESS = 0x000000000

However, MY_ADDRESS may change for my tests, but in my contract I want to keep it as a constant.

How do I address this?

2 Answers 2

2

You'd need to swap out the byte code during your test, and then set the code.

const CONSTANT_VARIABLE_TO_REPLACE = "0xC1E088fC1323b20BCBee9bd1B9fC9546db5624C5"

async function swapOutConstant(contractAddress, newConstantVariable) {
  let contractJson = fs.readFileSync(
    `./artifacts/contracts/MyContract.sol/MyContract.json`
  );

  const constantToReplaceSubstring = CONSTANT_VARIABLE_TO_REPLACE.substring(2);

  await network.provider.send("hardhat_setCode", [
    contractAddress,
    JSON.parse(contractJson).deployedBytecode.replaceAll(
      constantToReplaceSubstring.toLowerCase(),
      newConstantVariable.substring(2).toLowerCase()
    ),
  ]);

  const myContract = await ethers.getContractAt("MyContract", contractAddress);
  return myContract;
}

Then, import this function in your test and set the contract you want to test to it.

In this example, we use substring because the bytecode of an address doesn't have the 0x, so we lop it off.

Note this gets harder when working with numbers that might be duplicated. It's easy with addresses since it's unlikely that address will show up in your bytecode when not referring to the address you're trying to replace.

Probably the ugliest thing on the planet. I think we should make a hardhat issue.

1
  • Thanks a ton for sharing this! Very helpful!
    – Intenex
    Commented Mar 28, 2023 at 20:41
0

You can't change the value of a constant as it's value is hardcoded.

See this.

Can you maybe set MY_ADDRESS in the constructor so it's dynamically set for each test?

3
  • But in our tests we want to be able to. See below. Commented Oct 15, 2022 at 3:23
  • Did you just make a post to answer your own question? Commented Oct 15, 2022 at 3:27
  • 1
    I do it all the time. Anytime I web search something and someone else hasn't asked the question, I make sure to document it. This way, when I learn something, the whole world can learn it as well instead of having to go through the same process of trial and error I did. I highly recommend everyone take up this practice. Commented Oct 15, 2022 at 3:36

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.