# Using Hardhat

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2FmfeZAUJeAftTCUEHlzYi%2FUsing-Hardhat.jpg?alt=media&#x26;token=ec699184-acf4-4a39-a5c5-a6d7abf8e84f" alt=""><figcaption></figcaption></figure>

## Overview

This tutorial will teach you how to create, compile and deploy a smart contract on the KCC Testnet using Hardhat.

[**Hardhat**](https://hardhat.org) 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.

### What you will do[​](https://wiki.polygon.technology/docs/develop/hardhat#what-you-will-do) <a href="#what-you-will-do" id="what-you-will-do"></a>

* Set up Hardhat
* Create a simple smart contract
* Compile contract
* Test contract
* Deploy contract

## Setting up the development environment <a href="#setting-up-the-development-environment" id="setting-up-the-development-environment"></a>

There are a few technical requirements before we start.

### Pre-requisites[​](https://docs.bnbchain.org/docs/hardhat-new#pre-requisites) <a href="#pre-requisites" id="pre-requisites"></a>

There are a few technical requirements before we start, as listed below:

* [Node.js v10+ LTS and npm](https://nodejs.org/en/) (comes with Node)
* [Git](https://git-scm.com/)

Once we have those installed, you need to create an npm project by going to an empty folder, running `npm init --yes`, and following its instructions to install Hardhat. Once your project is ready, you should run the following:

```
npm install --save-dev hardhat
```

To create your Hardhat project, run `npx hardhat` in your project folder. Let’s create the sample project and follow these steps to try out a sample task and compile, test, and deploy the sample contract.

{% hint style="info" %}
**Note**

The sample project used here comes from the [Hardhat Quickstart guide](https://hardhat.org/getting-started/#quick-start), as well as its instructions.
{% endhint %}

## Creating a project <a href="#creating-a-project" id="creating-a-project"></a>

In your project folder, run `npx hardhat` to create a sample project. You should see the following prompt:

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2FGHqYb5LbhN7BQNrGRuW1%2Fimage.png?alt=media&#x26;token=72526519-2888-44b8-a7c0-e8e57a6c0341" alt=""><figcaption></figcaption></figure>

Choose the `TypeScript project` and The following prompt should appear:

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2FkWErA7qQQe3fdXKKwsMp%2Fimage.png?alt=media&#x26;token=9a0b53dc-8305-4a1c-9b7d-7872e3168dc9" alt=""><figcaption></figcaption></figure>

### Checking the Contract <a href="#create-smart-contract" id="create-smart-contract"></a>

A sample contract in the `contracts` folder is `Lock.sol`, which consists of a simple digital lock that allows users to withdraw funds only after a certain time has passed.

```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

// Import this file to use console.log
import "hardhat/console.sol";

contract Lock {
    uint public unlockTime;
    address payable public owner;

    event Withdrawal(uint amount, uint when);

    constructor(uint _unlockTime) payable {
        require(
            block.timestamp < _unlockTime,
            "Unlock time should be in the future"
        );

        unlockTime = _unlockTime;
        owner = payable(msg.sender);
    }

    function withdraw() public {
        // Uncomment this line to print a log in your terminal
        // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp);

        require(block.timestamp >= unlockTime, "You can't withdraw yet");
        require(msg.sender == owner, "You aren't the owner");

        emit Withdrawal(address(this).balance, block.timestamp);

        owner.transfer(address(this).balance);
    }
}

```

### Configure Hardhat for KCC <a href="#configure-hardhat-for-bsc" id="configure-hardhat-for-bsc"></a>

* Go to `hardhat.config.ts`
* Create `.env` file in the root to store your private key
* Add **KCC Explorer** API key to `.env` file to verify the contract on KCC explorer. You can generate an API key by [creating an account](https://explorer.kcc.io/en/account/login?step=2)

{% hint style="info" %}
**Note**

Use the KCC Explorer API key to verify the contract is only for **KCC mainnet**
{% endhint %}

```typescript
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import * as dotenv from "dotenv";

dotenv.config();

const config: HardhatUserConfig = {
    solidity: {
        compilers:[
            {
                version: "0.8.9",
                settings: {
                    optimizer: {
                        enabled: true,
                        runs: 200,
                    },
                },
            },
            {
                version: "0.4.18",
            }
        ]
    },

    networks: {
        ropsten: {
            url: process.env.ROPSTEN_URL || "",
            accounts:
                process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],
        },
        testnet: {
            url: "https://rpc-testnet.kcc.network",
            chainId: 322,
            accounts: process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],

        },
        mainnet: {
            url: "https://rpc-mainnet.kcc.network",
            chainId: 321,
            accounts: process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],

        },

        hardhat: {
            allowUnlimitedContractSize: true,
        },
    },
    etherscan: {
        apiKey: process.env.ETHERSCAN_API_KEY,
    },
};

export default config;

```

{% hint style="info" %}
**NOTE**

Note that the file above requires DOTENV, for managing environment variables and also ethers and etherscan. Make sure to install all those packages.

Find more instructions on how to use DOTENV on [this page](https://www.npmjs.com/package/dotenv).
{% endhint %}

Your deployment contract account's private key is located in the `.env` file.

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2F8EKZJLGpuNsN7OJoZCVU%2Fimage.png?alt=media&#x26;token=ff17a085-59a4-4067-bae3-3c2d5b6f7f5f" alt=""><figcaption></figcaption></figure>

### Compiling the contract <a href="#compiling-the-contract" id="compiling-the-contract"></a>

To compile a Hardhat project, change to the root of the directory where the project is located and you first need to install Hardhat Toolbox:

```
npm install --save-dev @nomicfoundation/hardhat-toolbox
```

&#x20;And then run to compile:

```
npx hardhat compile
```

### Testing the Contract <a href="#testing-the-contract" id="testing-the-contract"></a>

To run tests with Hardhat, you need to type the following:

```
npx hardhat test
```

And this is an expected output:

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2F0K9AF1hmBJJev0Tv4dkt%2Fimage.png?alt=media&#x26;token=641107e6-a12a-4418-82ff-f6f2d111153f" alt=""><figcaption></figcaption></figure>

### Deploying on KCC <a href="#deploying-on-polygon-network" id="deploying-on-polygon-network"></a>

Run this command in the root of the project directory:

```
npx hardhat run scripts/deploy.ts --network testnet
```

{% hint style="info" %}
**Note**

If you want to deploy your smart contract to **KCC Mainnet**, at the Deploying stage, you need to use mainnet instead of testnet after `--network`.
{% endhint %}

If you have enough amount of KCS you will see the sample output:

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2FipFxkul0MpUMMXb8JoeQ%2Fimage.png?alt=media&#x26;token=dab52b8f-65f6-4c85-9faf-dfc665063ca5" alt=""><figcaption></figcaption></figure>

The contract will be deployed on KCC Testnet, and you can check the deployment status here: <https://scan-testnet.kcc.network/>

**Congratulations! You have successfully deployed the `Lock` Smart Contract. The Smart Contract is now available for interaction.**

Besides, if you do not have the required amount of KCS, the output may look like this:

<figure><img src="https://2372007595-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0Tecsoe4KNURIiIXeVdO%2Fuploads%2FoEfvYQPiYQrX4VZaGMV2%2Fimage.png?alt=media&#x26;token=e1fe5030-efe1-4c38-b660-40d707c9b45e" alt=""><figcaption></figcaption></figure>

You can go to [KCC Testnet Faucet ](https://faucet-testnet.kcc.network/)to get more KCS for testing.
