Hardhat 使用

566 阅读1分钟

安装

在项目文件中执行 npm init 之后安装 hardhat

npm install --save-dev hardhat

创建项目

执行 npx hardhat 创建项目

过程中可以选择Create a sample project 快速创建项目

编译合约

npx hardhat compile

执行命令之后回编译 contract 文件下面的合约

启动测试网络

npx hardhat node

会启动本地测试节点

hardhat.config.js 文件中配置

networks:{
    loaclhost:{
        url:"http://127.0.0.1:8545/",
        accounts:['测试账号的私钥']
    }
}

运行测试脚本

在 scripts/里面,你会发现 sample-script.js 运行

npx hardhat run scripts/sample-script.js --network localhost

这样我们将在本地测试节点运行脚本

部署合约

现在hardhat还有没有办法直接部署合约还是要通过脚本,可以参考测试脚本的部署合约的代码 需要在hardhat.config.js 文件中配置想要部署的地址和私钥,注意私钥的安全

async function main() {
  // 获得将要部署的合约
  const Greeter = await ethers.getContractFactory("Greeter");
  const greeter = await Greeter.deploy("Hello, Hardhat!");

  console.log("Greeter deployed to:", greeter.address);
}

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