hardhat开发dapp初始化操作

前言

入门的话可以通过Remix开发工具完成solidity项目的编写、编译、部署等操作。专业点的开发工具有 TruffleHardhat,先看一看hardhat的简介:

Hardhat is a development environment for Ethereum software. It consists of different components for editing, compiling, debugging and deploying your smart contracts and dApps, all of which work together to create a complete development environment.

开发工具的话,常用的还有一个本地模拟节点的Ganache(Ganache属于truffle),因为链上包括主网和测试网调试比较慢,可以先在本地测试。

常用开发模式:

  1. 初级:Metamask + Remix + Ganache
  2. 进阶:Truffle / Hardhat

Hardhat基本操作

npm (npx) version 8.5.5
node version 16.13.1

新手第一次如下:

  1. 创建新文件夹,初始化一个npm项目:npm init -y,此时目录中会生成package.json文件。
  2. 安装hardhat : npm install --save-dev hardhat
  3. 初始化hardhat: npx hardhat ,会出现终端选项自行选择。

如果安装过hardhat,以上不用执行,直接运行 npx hardhat init

  1. 以下是常用的包:
    npm install --save-dev hardhat@^2.9.3 @nomiclabs/hardhat-waffle@^2.0.0 ethereum-waffle@^3.0.0 chai@^4.2.0 @nomiclabs/hardhat-ethers@^2.0.0 ethers@^5.0.0
    npm install --save dotenv@^16.0.0
    npm install --save @openzeppelin/contracts

安装以上包的package.json文件如下:

{
  "name": "yourdappname",
  "version": "version",
  "description": "",
  "main": "yourmain.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@nomiclabs/hardhat-ethers": "^2.0.0",
    "@nomiclabs/hardhat-waffle": "^2.0.0",
    "chai": "^4.2.0",
    "ethereum-waffle": "^3.0.0",
    "ethers": "^5.0.0",
    "hardhat": "^2.9.3"
  },
  "dependencies": {
    "dotenv": "^16.0.0",
    "@openzeppelin/contracts": "^4.7.3"
  }
}

生成目录结构如下:

.
├── README.md
├── contracts
├── hardhat.config.js
├── node_modules
├── .env 手动创建,用于放置privateKey,需安装dotenv包
├── package-lock.json
├── package.json
├── scripts
└── test
  • contracts - 编写合约
  • scripts - 编写js代码
  • hardhat.config.js - 配置solidity版本等信息

通过js代码连接以太坊有两个框架 Web3jsEthers.js,一般要通过http或者wss代理去连接,比如通过alchemy或者infura等节点供应商提供的api去连接。

  1. npx hardhat compile 编译solidity
  2. npx hardhat test 测试tests目录下js文件
  3. npx hardhat run或者npx hardhat run scripts/deploy.ts 运行js ,默认在本地网络运行。注意指定网络:npx hardhat run scripts/deploy.js --network mumbai

参考:Road to WEB3 - buymeacoffee

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
)">
下一篇>>