# 使用 Hardhat 部署合约

**Hardhat** 是一个方便在以太坊上进行构建的任务运行器。使用它可以帮助开发人员管理和自动化构建智能合约和dApp的过程中固有的重复任务，以及轻松地围绕此工作流程引入更多功能。

**Hardhat** 还内置了**Hardhat network**，**Hardhat network** 是为开发而设计的本地以太坊网络。 用来部署合约，运行测试和调试代码。

为了提升 Conflux 的合约开发体验，官方最近推出了 `hardhat-conflux` 插件，集成了`js-conflux-sdk`，使开发者能够以简单的方式开发 Conflux 合约。

使用 Conflux-Truffle 部署合约，更多资料和相关信息:

* Hardhat 官方教程: <https://hardhat.org/tutorial>
* hardhat-conflux 安装使用说明: <https://github.com/conflux-chain/hardhat-conflux>
* hardhat-conflux-example: <https://github.com/Conflux-Chain/hardhat-conflux-example>

通过以下步骤安装并使用 `hardhat-conflux`:

#### 安装 Node.js

大多数以太坊库和工具都是用 JavaScript 编写的，Hardhat也是如此。Node.js 是一个基于 Chrome 的 V8 引擎构建的JavaScript runtime。Node.js 是在 web 浏览器之外运行 JavaScript 是最流行的解决方案，而Hardhat则构建在其之上。

Hardhat 官方提供了一个 Node.js 安装教程，详见: <https://hardhat.org/tutorial/setting-up-the-environment>

#### 创建 `hardhat-conflux` 项目

从 [hardhat-conflux-example](https://github.com/Conflux-Chain/hardhat-conflux-example) 下载范例项目文件。完成后在命令行终端进入项目文件夹，运行`npm install` 安装依赖包。

#### 配置 `hardhat.config.js`

范例项目已经帮你设置好了 Conflux 测试网的 RPC 网络，现在需要将 `PRIVATE_KEY1` 从环境变量中引入。

首先在命令行终端运行以下命令安装 dotenv 模块，它将环境变量从`.env`文件加载到[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env)。

`npm install dotenv -D`&#x20;

然后在项目根目录下创建 `.env` 文件，以 `PRIVATE_KEY1=0x123456......` 的形式保存你的私钥。

回到 hardhat.config.js 文件，引入 `.env` 文件中保存的环境变量:

`require("dotenv").config()`

最后，找到 `solidity: "0.8.4"`，在此处指定你要部署的合约所使用的 solc 编译器版本。

#### 编写和编译智能合约

在根目录下找到 contracts 文件夹，在其中新建你的合约。完成后在命令行终端运行 `npx hardhat compile` 进行编译。

#### 创建合约部署脚本

在根目录下找到 scripts 文件夹，创建你的合约部署脚本，内容可以参考 scripts 自带的`sample-conflux.js`。假设你的部署脚本被命名为`deploy.js`，运行以下命令进行部署:

`npx hardhat run scripts/deploy.js --network confluxTestnet`

如果使用`sample-conflux.js`脚本来部署范例自带的`Greeter.sol`合约，你将会在命令行终端看到如下输出:

`Greeter deployed to: cfxtest:xxxxxx......`

将输出的合约地址复制到 ConfluxScan 测试网 <https://testnet.confluxscan.io/> ，可以查看刚才部署的合约。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://conflux-technical-support.gitbook.io/conflux-nft-kai-fa-zhi-nan/step-4-zai-lian-shang-bu-shu-ni-de-he-yue/shi-yong-hardhat-bu-shu-he-yue.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
