How can I get the private key of the address of the underlying contract through HardHat?

Viewed 2331

I have smartcontract from HardHat tutorial https://hardhat.org/tutorial/writing-and-compiling-contracts.html

and I successfully deployed it.

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

  console.log("Deploying contracts with the account:", deployer.address);

  console.log("Account balance:", (await deployer.getBalance()).toString());

  const Token = await ethers.getContractFactory("Token");
  const token = await Token.deploy();

  console.log("Token address:", token.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

But only the address of the contact is returned to me and its private key is not.

  console.log("Deploying contracts with the account:", deployer.address);

How can I get the private key in this way? I need it for the method

web3.eth.accounts.wallet.add('0x<private_key>');

Because otherwise I can't call the transfer method on the smart contract.

2 Answers

Not possible by design.

A contract address is determined from the deployment transaction params. Specifically, the ethers deploy() function is using the CREATE opcode by default, so the contract address is determined from the deployer address and the deploying transaction nonce param.

But the private key to the contract address is never generated during the deployment - so it can't be returned. Just the address.


Because otherwise I can't call the transfer method on the smart contract.

Correct. If you want to transfer funds out of the contract, you need to implement a function to be able to do that.

pragma solidity ^0.8;

contract MyContract {

    // transfers the entire balance of this contract to the `msg.sender`
    function widthdraw() external {
        require(msg.sender == address(0x123), "Not authorized");
        payable(msg.sender).transfer(address(this).balance);
    }
}

Let's assume you know the private key, and you make a lending smart contract, everybody can pool their money on the contract and lend money from the contract. One day you feel greedy, and you just use your private key transfer all the pool to your private wallet. Does this sound good? By design even the deployer should never have access to the private key of the contract, that's the point of the ethereum and the point of the dapp and dao, without it basically the deployer still is the "center" who controls everything.

Related