Deploying Smart Contracts – Changing Deployment Address in Ethers and Hardhat Local Network

ethers.jshardhatsolidity

I want to change the account deploying contracts on my local hardhat network using ethers.
Current Code:

const main = async () => {
  const [owner, addr1, addr2] = await ethers.getSigners();
  addr1.connect(ethers.provider);
  const BFactory = await ethers.getContractFactory('B');
  const b = await BFactory.deploy({
    value: ethers.utils.parseEther('0.1'),
  });

  await b.deployed();

  console.log('Contract deployed to:', b.address);

  await b.onlyMe();
};

Deploy Script:
npx hardhat run scripts/deploy.ts

Result

Error: cannot alter JSON-RPC Signer connection (operation="connect", code=UNSUPPORTED_OPERATION, version=providers/5.6.8)

Best Answer

First, specify the private key of the account you want to use and then connect to the contract to deploy it with such wallet.

const main = async () => {
   const signer = new ethers.Wallet(your_private_key_string);
   const BFactory = await ethers.getContractFactory('B');
   const b = await BFactory.connect(signer).deploy({
    value: ethers.utils.parseEther('0.1'),
   });

  await b.deployed();

  console.log('Contract deployed to:', b.address);

  await b.onlyMe();
}
Related Topic