Back

blockchain - !!! hardhat:本地开发、测试eth的工具 , web3.js

发布时间: 2022-01-07 00:20:00

参考:https://hardhat.org/getting-started/

hardhat 提供了非常方便的ETH开发环境,内置了blockchain

2024.3.28 更新: 由于hardhat方便部署contract, 内置的节点不出错(兼容性稳定性比truffle的ganache要好),所以建议选择这个。

安装

node 13, 14, 16

我用的是  16.13.1 

$ nvm install v16.13.1

$ npm install --save-dev hardhat

使用

npx hardhat

看到输入一堆符号后,就成功安装了

888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

Welcome to Hardhat v2.8.1

✔ What do you want to do? · Create a basic sample project
✔ Hardhat project root: · /workspace/test_hardhat
✔ Do you want to add a .gitignore? (Y/n) · y
✔ Help us improve Hardhat with anonymous crash reports & basic usage data? (Y/n) · true
✔ Do you want to install this sample project's dependencies with npm (hardhat @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers)? (Y/n) · y

这样就会生成一个ETH contract的项目,包含了一个智能合约。

(可选) 也可以自行创建一个contract, 内容如下:

 cat contracts/SayHi.sol
pragma solidity ^0.8.0;

contract SayHi {
  uint256 number;
  function store(uint256 num) public {
    number = num;
  }

  function get() public view returns (uint256){
    return number;
  }
}

编译:

npx hardhat compile

部署

scripts/sample-script.js 内容如下;

const hre = require("hardhat");

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

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

npx hardhat run scripts/sample-script.js 

就可以看到contract部署到了本地。

npx hardhat run scripts/sample-script.js
SayHi deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3

npx hardhat node   在本地运行 模拟的ETH节点

运行上面的命令, 就可以看到提示:

Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/

使用 web3.js 进行查询

引入web3.js : npm install web 

创建一个文件: (当前目录下) run.js

var Web3 = require('web3')
var web3 = new Web3('ws://localhost:8545')
web3.eth.getAccounts()
    .then(console.log);

可以查询该 节点下的所有account:

curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}' localhost:8545

{"jsonrpc":"2.0","id":1,"result":["0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","0x70997970c51812dc3a010c7d01b50e0d17dc79c8","0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc","0x90f79bf6eb2c4f870365e785982e1f101e93b906","0x15d34aaf54267db7d7c367839aaf71a00a2c6a65","0x9965507d1a55bcc2695c58ba16fb37d819b0a4dc","0x976ea74026e726554db657fa54763abd0c3a0aa9","0x14dc79964da2c08b23698b3d3cc7ca32193d9955","0x23618e81e3f5cdf7f54c3d65f7fbc0abf5b21e8f","0xa0ee7a142d267c1f36714e4a8f75612f20a79720","0xbcd4042de499d14e55001ccbb24a551f3b954096","0x71be63f3384f5fb98995898a86b02fb2426c5788","0xfabb0ac9d68b0b445fb7357272ff202c5651694a","0x1cbd3b2770909d4e10f157cabc84c7264073c9ec","0xdf3e18d64bc6a983f673ab319ccae4f1a57c7097","0xcd3b766ccdd6ae721141f452c550ca635964ce71","0x2546bcd3c84621e976d8185a91a922ae77ecec30","0xbda5747bfd65f08deb54cb465eb87d40e51b197e","0xdd2fd4581271e230360230f9337d5c0430bf44c0","0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199"]}

查询当前的gas price:

$ curl -X POST -H "Content-Type: application/json:[],"id":1}' localhost:8545 method":"eth_gasPrice","params":
{"jsonrpc":"2.0","id":1,"result":"0x6fc23ac0"}

irb(main):001:0> 0x6fc23ac0   => 1875000000   1.8gwei

不可以创建钱包:(没有加载personal 方法)

查看区块高度:

curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' localhost:8545
{"jsonrpc":"2.0","id":1,"result":"0x0"}

查看账户余额:

curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "latest"],"id":1}' 127.0.0.1:8545
{"jsonrpc":"2.0","id":1,"result":"0x21e19e0c9bab2400000"}

上面的account是默认自带的。非常好用。 里面大概有10000个ETH

与智能合约的交互:

abi等等需要自己生成。

估计要使用大量的代码了

切换网络

npx hardhat run scripts/whitelist.js --network localhost --show-stack-traces

设置网络

配置文件  hardhat.config.ts

require('@nomiclabs/hardhat-waffle');
require('@nomiclabs/hardhat-etherscan');
require('hardhat-gas-reporter');

const dotenv = require('dotenv');

dotenv.config();

/**
 * @type import('hardhat/config').HardhatUserConfig
 */

const { PRIVATE_KEY, ETHERSCAN_API_KEY } = process.env;

module.exports = {
  solidity: '0.8.4',
  networks: {
    localhost: { },
    ropsten: {
      url: process.env.ROPSTEN_URL || "",
      accounts:
        process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY, process.env.OTHER_KEY || ""] : [],
    },
    fuji: {
      url: `https://api.avax-test.network/ext/bc/C/rpc`,
      accounts:
        process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY, process.env.OTHER_KEY || ""] : [],
      timeout: 3600000
    },
    polygon: {
      url: `https://polygon-rpc.com/`,
      accounts:
        process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY, process.env.OTHER_KEY || ""] : [],
      timeout: 3600000
    },
  },
};

Back