# 使用hardhat开发、测试web3项目

下载vscode安装包

```plaintext
https://vscode.download.prss.microsoft.com/dbazure/download/stable/dfaf44141ea9deb3b4096f7cd6d24e00c147a4b1/code_1.101.0-1749655245_amd64.deb
```

安装

$ sudo dpkg -i code\_1.101.0-1749655245\_amd64.deb

**<mark>vscode设置字体，安装插件</mark>**

**<mark>solidity hardhat</mark>**

**<mark>javascript</mark>**

**<mark>Prettier Code formatter增强代码易读性</mark>**

---

创建项目文件夹Web3Tutorial

$ mkdir Web3Tutorial

npm初始化

$ npm init

```plaintext
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (web3tutorial) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
```

一律默认回车

---

新建hardhat项目

$ npx hardhat

```plaintext
Need to install the following packages:
hardhat@2.24.3
Ok to proceed? (y) y
```

选第一个创建javascript项目

```plaintext
Welcome to Hardhat v2.24.3
? What do you want to do? 
? Create a JavaScript project
  Create a TypeScript project
  Create a TypeScript project (with Viem)
  Create an empty hardhat.config.js
  Quit
```

又会要求选择，全部默认回车，等待安装创建

---

在项目文件夹下打开vscode

**<mark>hardhat.config.js是hardhat配置</mark>**

**<mark>.gitignore是git不需要上传的文件</mark>**

配置git全局文件，把当前文件夹纳入git管理

$ git init

已重新初始化已存在的 Git 仓库于 /home/zhangyu/Web3Tutorial/.git/

查看git状态

$ git status

位于分支 master 尚无提交未跟踪的文件: （使用 "git add &lt;文件&gt;..." 以包含要提交的内容）

添加全部文件

$ git add .

$ git status

位于分支 master 尚无提交 要提交的变更： （使用 "git rm --cached &lt;文件&gt;..." 以取消暂存）

$ git commit -m "project init"

\[master（根提交） c9b3d14\] project init 9 files changed, 8062 insertions(+)

想要忽略任何文件/文件夹，就把它加入到.gitignore

---

[https://github.com/smartcontractkit/Web3\_tutorial\_Chinese/](https://github.com/smartcontractkit/Web3_tutorial_Chinese/)

contracts文件夹下新建FundMe.sol文件

把源代码全部复制进来

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

chainlink/contracts找不到所以显示红色线 命令行

cnpm安装chainlink/contracts，等待安装完成

$ cnpm install @chainlink/contracts --save-dev

```plaintext
? Linked 1 latest versions fallback to /home/zhangyu/Web3Tutorial/node_modules/.store/node_modules
? Installed 1 packages on /home/zhangyu/Web3Tutorial
? All packages installed (used 2s(network 2s), speed 0B/s, json 0(0B), tarball 0B, manifests cache hit 1, etag hit 1 / miss 0)
devDependencies:
+ @chainlink/contracts ^1.3.0
```

回到vscode看到package.json文件的devDependencies下已经多了 "@chainlink/contracts": "^1.3.0"

再回到FundMe.sol文件 import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol" 的红色线已经消失

在项目文件夹内使用hardhat编译

$ npx hardhat compile

Error HH404: File @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol, imported from contracts/FundMe.sol, not found.

报错还是找不到这个导入文件

来到chainlink的github代码，文件路径发生变化

在代码仓库搜索AggregatorV3Interface.sol 当前路径加了shared

修改合约开头导入文件的路径，再次编译成功

$ npx hardhat compile

Compiled 3 Solidity files successfully (evm target: paris).

生成artifacts和cache文件夹

---

编译之后就是部署，使用脚本部署

新建文件夹scripts，并在文件夹内新建文件deployFundMe.js

首先导入ethers.js，再创建主函数，最后执行主函数 运行脚本错误

$ npx hardhat run scripts/deployFundMe.js

contract is deploying

Error: incorrect number of arguments to constructor

构造函数需要传入参数 \_locktime取值设为10 再次运行脚本成功

$ npx hardhat run scripts/deployFundMe.js

contract is deploying

contract has been deployed successfully, contract address is 0x5FbDB2315678afecb367f032d93F642f64180aa3

以上是部署在hardhat本地网络 这是hardhat自带内置的网络，即本地的ethereum网络

---

在hardhat.config.js文件里配置defaultNetwork

module.exports = { defaultNetwork:"hardhat",...}

在部署脚本的时候，加参数，即部署到默认网络，成功

$ npx hardhat run scripts/deployFundMe.js --network hardhat

contract is deploying

contract has been deployed successfully, contract address is 0x5FbDB2315678afecb367f032d93F642f64180aa3

只有默认网络不是hardhat，才需要修改配置文件和加参数

---

下面把部署的网络参数写到配置文件里

使用alchemy服务商取得url 通过邮箱和密码登录之后，在主界面Apps里创建应用，选择ethereum链和sepolia测试网，选择https协议，复制url 把url粘贴到hardhar.config.js文件的network

下面填写accounts的钱包私钥

选择某个钱包地址对应的私钥，粘贴到accounts\[""\]里

由于暂时未取得测试币，所以报错。即便更换holesky网络也不行

$ npx hardhat run scripts/deployFundMe.js --network sepolia

contract is deploying

ProviderError: insufficient funds for gas \* price + value: have 0 want 1485678494676

---

下面配置.env敏感信息文件。**<mark>一定要在根目录下创建.env文件[否则报错找不到环境变量]</mark>**

在.env文件里，设置变量名分别保存敏感信息

SEPOLIA\_URL=

PRIVATE\_KEY=

把之前hardhat.congfig.js文件中sepolia网络参数粘贴过来

为了能在config.js文件中调用.env需要安装dotenv 直接使用npm安装还是太慢，仍然使用cnpm安装，速度飞快

$ npm install -g cnpm --registry=[https://registry.npmmirror.com](https://registry.npmmirror.com)

changed 66 packages in 28s

59 packages are looking for funding

$ cnpm install --save-dev dotenv

```plaintext
? Linked 1 latest versions fallback to /home/zhangyu/Web3Tutorial/node_modules/.store/node_modules
? Installed 1 packages on /home/zhangyu/Web3Tutorial
? All packages installed 
devDependencies:
+ dotenv ^16.5.0
```

在package.json文件的"devDependencies"也看到"dotenv": "^16.5.0"安装

在config.js文件开头引入dotenv.config()方法，再运行变量设置为常量

把sepolia网络配置参数替换为常量，可以运行

---

虽然敏感信息保存在.env文件，但还是明文。现在使用env-enc包对敏感信息加密

仍然使用cnpm安装

$ cnpm install --save-dev @chainlink/env-enc

```plaintext
All packages installed
devDependencies:
+ @chainlink/env-enc ^1.0.5
```

回到package.json文件，看到"@chainlink/env-enc": "^1.0.5"确实安装成功

现在使用env-enc对敏感信息加密，先要设置密码

$ npx env-enc set-pw

Enter the password (input will be hidden):\*\*\*\*\*

再把变量加密

$ npx env-enc set

```plaintext
Please enter the variable name (or press ENTER to finish): 
SEPOLIA_URL
Please enter the variable value (input will be hidden): 
*********************************************************************
Would you like to set another variable? Please enter the variable name (or press ENTER to finish): 
PRIVATE_KEY
Please enter the variable value (input will be hidden): 
******************************************************************
Would you like to set another variable? Please enter the variable name (or press ENTER to finish):
```

回到vscode，在根目录下多了.env.enc文件，保存的就是加密后的敏感变量

SEPOLIA\_URL: ENCRYPTED|

PRIVATE\_KEY: ENCRYPTED|

在config.js文件中，引入的不再是dotenv而是chainlink/env.enc

$ npx hardhat run scripts/deployFundMe.js --network sepolia

contract is deploying

ProviderError: insufficient funds for gas \* price + value: have 0 want 1238079237144

此时可以删除.env文件，只保留加密后的文件.env.enc，并把.gitignore文件加入.env.enc

---

使用hardhat对合约进行验证，需要安装插件@nomicfoundation/hardhat-verify

[https://hardhat.org/hardhat-runner/plugins/nomicfoundation-hardhat-verify](https://hardhat.org/hardhat-runner/plugins/nomicfoundation-hardhat-verify) 有详细说明

安装hardhat-verify

$ cnpm install @nomicfoundation/hardhat-verify --save-dev

```plaintext
All packages installed
devDependencies:
+ @nomicfoundation/hardhat-verify ^2.0.14
```

安装完成后，在config.js文件出现"@nomicfoundation/hardhat-verify": "^2.0.14"
