> ## Documentation Index
> Fetch the complete documentation index at: https://injectivelabs-docs-ai-sdk.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 设置 Hardhat 并编译智能合约

## 前置条件

确保你已安装较新版本的 NodeJs。
你可以使用以下命令检查：

```shell theme={null}
node -v
```

本指南使用的版本为：

```text theme={null}
v22.16.0
```

如果你尚未安装 NodeJs，请使用以下方式安装：

* Linux 或 Mac: [NVM](https://github.com/nvm-sh/nvm)
* Windows: [NVM for Windows](https://github.com/coreybutler/nvm-windows)

你需要一个钱包，以及一个已充值 Testnet INJ 的账户。

<Callout icon="info" color="#07C1FF" iconType="regular">
  你可以从 [Injective Testnet faucet](https://testnet.faucet.injective.network/) 申请 EVM testnet 资金。
</Callout>

创建账户后，请务必将私钥复制到可访问的位置，因为你需要它来完成本教程。

<Callout icon="info" color="#07C1FF" iconType="regular">
  请注意，私钥应谨慎处理。
  此处的说明仅适用于本地开发和 Testnet。
  但是，这些方法对于 Mainnet 上使用的私钥来说**不够**安全。
  请确保在 Mainnet 上遵循密钥安全的最佳实践，并且不要在 Mainnet 和其他网络之间重复使用相同的密钥/账户。
</Callout>

## 设置新的 Hardhat 项目

使用 git 克隆演示仓库，该仓库已为你完全设置好项目。

```shell theme={null}
git clone https://github.com/injective-dev/hardhat-inj
```

从 npm 安装依赖：

```shell theme={null}
npm install
```

## 项目结构

在等待 npm 下载和安装时，在代码编辑器/IDE 中打开仓库，查看目录结构。

```text theme={null}
hardhat-inj/
  contracts/
    Counter.sol → 智能合约 Solidity 代码
  script/
    deploy.js → 部署脚本
  test/
    Counter.test.js → 测试用例
  hardhat.config.js → 配置文件
  .example.env
```

`hardhat.config.js` 文件已预配置为连接到 Injective EVM Testnet。
在继续之前，你只需要提供 Injective Testnet 账户的私钥。

```shell theme={null}
cp .example.env .env
```

编辑 `.env` 文件以添加私钥。
你也可以选择更新为其他 JSON-RPC endpoints。

```shell theme={null}
PRIVATE_KEY=你的私钥（不带 0x 前缀）
INJ_TESTNET_RPC_URL=https://k8s.testnet.json-rpc.injective.network/

```

## 编辑智能合约

此演示中包含的智能合约非常基础。它：

* 存储一个 `value`，这是一个数字。
* 暴露一个 `value()` 查询方法。
* 暴露一个 `increment(num)` 交易方法。

打开文件：`contracts/Counter.sol`

```solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract Counter {
    uint256 public value = 0;

    function increment(uint256 num) external {
        value += num;
    }
}

```

## 编译智能合约

运行以下命令：

```shell theme={null}
npx hardhat compile
```

Hardhat 将自动下载并运行在 `hardhat.config.js` 文件中配置的 Solidity 编译器（`solc`）版本。

## 检查编译输出

编译器完成后，你应该在项目目录中看到额外的目录：

```text theme={null}
hardhat-inj/
  artifacts/
    build-info/
      ...
    contracts/
      Counter.sol/
        Counter.json → 打开此文件
        ...
  cache/
    ...
```

打开 `Counter.json` 文件（`artifacts/contracts/Counter.sol/Counter.json`）。
在其中，你应该看到编译器输出，包括 `abi` 和 `bytecode` 字段。
这些 artifacts 将在后续所有步骤（测试、部署、验证和交互）中使用。

## 下一步

现在你已经设置了 Hardhat 项目并编译了智能合约，你可以开始测试该智能合约了！
接下来请查看[使用 Hardhat 测试智能合约](./test-hardhat/)教程。
