> For the complete documentation index, see [llms.txt](https://docs.giwa.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.giwa.io/get-started/smart-contract/develop/hardhat.md).

# Hardhat으로 개발하기

{% hint style="info" %}
Hardhat은 Ethereum Application을 개발할 때 유용하게 사용할 수 있는 Node.js 기반 Toolkit 이에요. 유연하고 확장 가능하다는 특징을 가지고 있어요.
{% endhint %}

## 요구사항

### Node v22+

이 튜토리얼은 Node 버전 22 이상이 설치되어 있어야 해요.

* [Node v22+](https://nodejs.org/en/download) 다운로드

`nvm`으로 Node 버전을 관리하는 경우 `nvm install 22` 명령어를 실행하면 돼요.

***

## 개발 환경 세팅

&#x20;[Hardhat](https://hardhat.org/)을 설치하고 프로젝트를 생성해요.

```bash
mkdir giwa-project
cd giwa-project

npx hardhat --init
npm install --save-dev @nomicfoundation/hardhat-verify
```

생성된 프로젝트 구조는 아래와 같아요.

```
giwa_project/
├── hardhat.config.ts # 프로젝트 설정 파일
├── contracts         # 프로젝트 소스 코드 디렉토리
├── test              # 작성한 컨트랙트 테스트 디렉토리
├── ignition          # Hardhat Ignition 배포 스크립트
└── scripts           # 배포/시뮬레이션용 스크립트
```

***

## Hardhat을 GIWA 체인에 연결하기

GIWA 체인에 스마트 컨트랙트를 배포하려면 `hardhat.config.ts` 파일에 GIWA 체인을 추가해야 해요.

```typescript
import type { HardhatUserConfig } from "hardhat/config";

import hardhatToolboxViemPlugin from "@nomicfoundation/hardhat-toolbox-viem";
import hardhatVerify from "@nomicfoundation/hardhat-verify";
import 'dotenv/config'

const config: HardhatUserConfig = {
  plugins: [hardhatToolboxViemPlugin, hardhatVerify],
  solidity: {
    profiles: {
      default: {
        version: "0.8.28",
      },
      production: {
        version: "0.8.28",
        settings: {
          optimizer: {
            enabled: true,
            runs: 200,
          },
        },
      },
    },
  },
  networks: {
    giwaSepolia: {
      type: "http",
      chainType: "op",
      url: "https://sepolia-rpc.giwa.io",
      accounts: [process.env.PRIVATE_KEY as string]
    },
  },
  chainDescriptors: {
    91342: {
      name: "Giwa Sepolia",
      blockExplorers: {
        blockscout: {
          name: "Giwa Sepolia Explorer",
          url: "https://sepolia-explorer.giwa.io",
          apiUrl: "https://sepolia-explorer.giwa.io/api",
        },
      },
    },
  },
};

export default config;
```

### 환경 변수 불러오기 <a href="#loading-environment-variables" id="loading-environment-variables"></a>

위 설정은 [dotenv](https://www.npmjs.com/package/dotenv)를 사용해서 `.env` 파일의 `PRIVATE_KEY` 환경 변수를 읽어와요. 절대 소스 코드에 개인 키를 하드코딩하지 마세요.

`dotenv`를 설치하려면 아래처럼 입력해요:

```
npm install --save dotenv
```

`dotenv`가 설치되었다면, `.env` 파일을 만들고 아래와 같이 채워넣어요.

```
PRIVATE_KEY=<YOUR_PRIVATE_KEY>
```

`<YOUR_PRIVATE_KEY>` 는 배포에 사용할 지갑의 개인키(Private Key)로 교체하세요.

{% hint style="warning" %}
`PRIVATE_KEY`는 컨트랙트를 배포할 때 사용할 지갑의 개인키(Private Key)예요.
{% endhint %}

***

## 컨트랙트 작성하기

아주 간단한 컨트랙트부터 작성해볼까요? 먼저, 프로젝트 생성 시에 같이 생성된 `contracts/` 폴더 안의 `Counter.sol`, `Counter.t.sol` 파일과 `test/` 폴더 안에 `Counter.ts` 파일, 그리고 `ignition/modules/Counter.ts`을 지워주고, 아래처럼 새로운 컨트랙트를 작성해요.

{% code title="contracts/Giwa.sol" lineNumbers="true" fullWidth="false" %}

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

contract Giwa {
    event HelloGiwa();

    function helloGiwa() public {
        emit HelloGiwa();
    }
}
```

{% endcode %}

위 스마트 컨트랙트 코드는 `Giwa` 라는 이름의 컨트랙트이고, `helloGiwa` 라는 함수와 `HelloGiwa`라는 이벤트를 가진 컨트랙트예요.&#x20;

Hardhat을 통해 컴파일하려면 아래와 같이 입력하면 돼요.

```bash
npx hardhat compile
```

### 테스트 코드 작성하기

작성한 컨트랙트가 의도한대로 동작하는지 확인하기 위해 테스트 코드를 작성해요. Hardhat은 [viem](https://viem.sh/)을 사용해서 TypeScript/JavaScript 형태로 테스트 코드를 작성할 수도 있고, Solidity로도 유닛 테스트 코드를 작성할 수 있어요. 이번 예제에서는 viem을 사용해서 작성해볼게요.

{% code title="test/Giwa.ts" lineNumbers="true" %}

```typescript
import { describe, it } from "node:test";

import { network } from "hardhat";

describe("Giwa", async function () {
  const { viem } = await network.connect();

  it("Should emit the HelloGiwa event when calling the helloGiwa() function", async function () {
    const giwa = await viem.deployContract("Giwa");

    await viem.assertions.emit(
      giwa.write.helloGiwa(),
      giwa,
      "HelloGiwa"
    );
  });
});

```

{% endcode %}

결과를 확인하려면 아래와 같이 입력하면 돼요.

```bash
npx hardhat test
```

***

## 컨트랙트 배포하기

스마트 컨트랙트가 성공적으로 컴파일되면, 해당 컨트랙트를 GIWA Sepolia 테스트 네트워크에 배포할 수 있어요.

Hardhat을 통해서 컨트랙트를 배포하는 방법 중에 하나는 Hardhat Ignition 이라는 툴을 활용하는 거예요. 아래와 같이 코드를 작성해서 시작할 수 있어요.

{% code title="ignition/modules/Giwa.ts" lineNumbers="true" %}

```typescript
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";

export default buildModule("GiwaModule", (m) => {
  const giwa = m.contract("Giwa");

  m.call(giwa, "helloGiwa", []);

  return { giwa };
});

```

{% endcode %}

작성이 완료되었다면, 아래와 같이 입력해서 GIWA Sepolia 테스트 네트워크에 배포할 수 있어요.

```
npx hardhat ignition deploy ignition/modules/Giwa.ts --network giwaSepolia
```

{% hint style="info" %}
가스비가 부족한가요? [테스트 ETH](/get-started/faucets.md)를 클레임하세요.
{% endhint %}

아래와 같이 결과가 나왔다면, 블록체인 세상에 여러분의 스마트 컨트랙트가 배포되어 누구든지 상호작용할 수 있게 된 거예요.

```
Hardhat Ignition 🚀

Resuming existing deployment from ./ignition/deployments/chain-91342

Deploying [ GiwaModule ]

Batch #1
  Executed GiwaModule#Giwa

Batch #2
  Executed GiwaModule#Giwa.helloGiwa

[ GiwaModule ] successfully deployed 🚀

Deployed Addresses

GiwaModule#Giwa - 0x여러분이_배포한_컨트랙트의_주소

```

***

## 컨트랙트 검증하고 익스플로러에서 상호작용하기

블록 익스플로러에서 컨트랙트와 상호작용하려면, 여러분이나 다른 누군가가 먼저 이를 검증해야 해요.&#x20;

위에서 배포된 컨트랙트 주소를 확인하고, 아래와 같이 입력해요.

```
npx hardhat verify --network giwaSepolia <배포된-컨트랙트-주소>
```

아래처럼 응답이 나왔다면 블록 익스플로러에 들어가서 여러분이 작성한 코드와 상호작용할 수 있어요.

```
=== Blockscout ===

📤 Submitted source code for verification on Giwa Sepolia Explorer:

  contracts/Giwa.sol:Giwa
  Address: <배포된-컨트랙트-주소>

⏳ Waiting for verification result...


✅ Contract verified successfully on Giwa Sepolia Explorer!

  contracts/Giwa.sol:Giwa
```

<div data-full-width="false"><figure><img src="/files/KLXXnCc9hc8ueunmLglu" alt=""><figcaption></figcaption></figure></div>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.giwa.io/get-started/smart-contract/develop/hardhat.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
