【问题标题】:如何通过HardHat获取底层合约地址的私钥?
【发布时间】:2022-01-20 10:46:33
【问题描述】:

我有来自 HardHat 教程https://hardhat.org/tutorial/writing-and-compiling-contracts.html的智能合约

我成功部署了它。

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);
  });

但是只有联系人的地址返回给我,它的私钥没有。

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

我怎样才能以这种方式获取私钥? 我需要它的方法

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

因为否则我无法调用智能合约上的转账方法。

【问题讨论】:

    标签: javascript ethereum smartcontracts web3js hardhat


    【解决方案1】:

    设计上不可能。

    合约地址由部署交易参数确定。具体来说,ethersdeploy()函数默认使用CREATE操作码,所以合约地址由部署者地址和部署交易nonce参数确定。

    但合约地址的私钥在部署期间永远不会生成 - 因此无法返回。只是地址。


    因为否则我无法调用智能合约上的转账方法。

    正确。如果你想从合约中转出资金,你需要实现一个函数来做到这一点。

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2022-08-13
      • 2017-07-03
      • 2021-06-12
      相关资源
      最近更新 更多