Hardhat – How to Modify and Deploy Contract to a New Address

contract-deploymenthardhat

I am new to solidity and I am using hardhat as a developing environment.
I want to change my contract code and deploy with a new address just for development purposes but every time I change some code and deploy it using npx hardhat run --network hardhat scripts/deploy.js. hardhat gives me the same contract address and I know my modifications didn't apply in the new contract.
can someone explain how to do this?

this is my deploy script:

async function main() {
  const NFTMarket = await hre.ethers.getContractFactory("NFTMarket");
  const nftMarket = await NFTMarket.deploy();
  await nftMarket.deployed();
  console.log("nftMarket deployed to:", nftMarket.address);

  const NFT = await hre.ethers.getContractFactory("NFT");
  const nft = await NFT.deploy(nftMarket.address);
  await nft.deployed();
  console.log("nft deployed to:", nft.address);

  let config = `
  export const nftmarketaddress = "${nftMarket.address}"
  export const nftaddress = "${nft.address}"
  `

  let data = JSON.stringify(config)
  fs.writeFileSync('config.js', JSON.parse(data))
}

and this is the address I get for my contracts every time(same every time):

  export const nftmarketaddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3"
  export const nftaddress = "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512"

Best Answer

Contract address is not determined by its content; it is deterministically computed from the address of the sender and the nonce of the transaction.

Each time you run your script, you are using the same sender (test address) with the same nonce (0), so the same address is computed.

If you use a separate node, let's say geth in dev mode, that remains running between multiple executions of your deploy script, you will see different addresses created each time, because the same user is used to deploy a new smart contract and the nonce increases.

See How is the address of an Ethereum contract computed? for more details.

Related Topic