> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hedera.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy and Verify a Smart Contract with Hardhat

## Deploying a Contract Using Hardhat Scripts

This tutorial will walk you through writing and compiling an ERC-721 Solidity smart contract. You'll then deploy and interact with it on the Hedera network using the [Hedera Smart Contract Service (HSCS)](/support/glossary#hedera-smart-contract-service-hscs) and familiar EVM tools like Ethers.js, connecting via the [JSON-RPC relay](/evm/development/json-rpc).

<Tip>
  **Developing or running CI?** [Solo](https://solo.hiero.org/docs/) runs a full Hedera network locally, no testnet rate limits, faucet, or resets, and works with the same EVM tooling. See the [Solo quickstart](https://solo.hiero.org/docs/simple-solo-setup/quickstart/) and [Using Solo with EVM tools](https://solo.hiero.org/docs/using-solo/using-solo-with-evm-tools/).
</Tip>

#### What you will accomplish

By the end of this tutorial, you will be able to:

* Compile and deploy a smart contract using Hardhat
* Interact with a smart contract using Hardhat

<Info>
  **Note:** This tutorial is currently supported only in the Getting Started [JavaScript](https://github.com/hedera-dev/hello-future-world-js) series and is not available for other languages.
</Info>

***

## Prerequisites

Before you begin, you should have **completed** the following tutorial:

* [Create and Fund a Testnet Account via the Hedera Faucet](/evm/quickstart/get-test-hbar)

***

## Table of Contents

1. [Step 1: Project Setup](#step-1%3A-project-setup)
2. [Step 2: Creating the ERC-721 Contract](#step-2%3A-creating-the-erc-721-contract)
3. [Step 3: Deploy Your ERC-721 Smart Contract](#step-3%3A-deploy-your-erc-721-smart-contract)
4. [Step 4: Minting an ERC-721 Token](#step-4%3A-minting-an-erc-721-token)
5. [Step 5: Verify Your Smart Contract with Hardhat](#step-5%3A-verify-your-smart-contract-with-hardhat)

***

## Step 1: Project Setup

#### Initialize Project

Set up your project by initializing the hardhat project:

```bash theme={null}
mkdir hardhat-erc-721-mint
cd hardhat-erc-721-mint
npx hardhat --init
```

Make sure to select "**Hardhat 3 → Typescript Hardhat Project using Mocha and Ethers.js"** and accept the default values. Hardhat will configure your project correctly and install the required dependencies.

<Accordion title="🚧 What's new: Hardhat 2 → 3 ">
  Key differences in Hardhat 3:

  * **compile → build**\
    `npx hardhat compile` is now `npx hardhat build`. This is the big one. The v3 migration guide explicitly shows using the `build` task.

  * **project init switch**\
    v2 commonly used `npx hardhat` or `npx hardhat init` to bootstrap. In v3 it’s `npx hardhat --init`.

  * **keystore helper commands are new**\
    v3’s recommended flow includes a keystore plugin with commands like `npx hardhat keystore set HEDERA_RPC_URL` and `npx hardhat keystore set HEDERA_PRIVATE_KEY`. These weren’t standard in v2.

  * **Foundry-compatiable Solidity tests**\
    In addition to offering Javascript/Typescript integration tests, Hardhat v3 also integrates Foundry-compatible Solidity tests that allows developers to write unit tests directly in Solidity

  * **Enhanced Network Management**\
    v3 allows tasks to create and manage multiple network connections simultaneously which is a significant improvement over the single, fixed connection available in version 2. This provides greater flexibility for scripts and tests that interact with multiple networks.

  *📚 Learn more from the official* [*Hardhat documentation*](https://hardhat.org/docs/getting-started)*.*
</Accordion>

#### Install Dependencies

Next, install the required dependencies:

```bash theme={null}
npm install @openzeppelin/contracts
```

Before we make any changes to our Hardhat configuration file, let's set some configuration variables we will be referring to within the file later.

<Note>
  When you set up your keystore for the first time, you’ll be asked to create a keystore password. Save this password securely because you’ll need it anytime you set or reset a variable.
</Note>

```bash theme={null}
# If you have already set this before, please use the --force flag
npx hardhat keystore set HEDERA_RPC_URL
```

For `HEDERA_RPC_URL`, we'll have `https://testnet.hashio.io/api`

```bash theme={null}
# If you have already set this before, please use the --force flag
npx hardhat keystore set HEDERA_PRIVATE_KEY
```

For `HEDERA_PRIVATE_KEY`, enter the **HEX Encoded Private Key for your ECDSA account** from the [Hedera Portal.](https://portal.hedera.com/)

<Danger>
  #### Note

  [*Hashio*](https://www.hashgraph.com/hashio/) *is intended for development and testing purposes only. For production use cases, it's recommended to use commercial-grade JSON-RPC Relay or host your own instance of the* [*Hiero JSON-RPC Relay*](https://github.com/hiero-ledger/hiero-json-rpc-relay)*.*
</Danger>

#### Configure Hardhat

Update your `hardhat.config.ts` file in the root directory of your project. This file contains the network settings so Hardhat knows how to interact with the Hedera Testnet. We'll use the variables you've stored in your `.env` file.

```typescript hardhat.config.ts theme={null}
import type { HardhatUserConfig } from "hardhat/config";

import hardhatToolboxMochaEthersPlugin from "@nomicfoundation/hardhat-toolbox-mocha-ethers";
import { configVariable } from "hardhat/config";

const config: HardhatUserConfig = {
  plugins: [hardhatToolboxMochaEthersPlugin],
  solidity: {
    profiles: {
      default: {
        version: "0.8.28",
      },
      production: {
        version: "0.8.28",
        settings: {
          optimizer: {
            enabled: true,
            runs: 200,
          },
        },
      },
    },
  },
  networks: {
    testnet: {
      type: "http",
      url: configVariable("HEDERA_RPC_URL"),
      accounts: [configVariable("HEDERA_PRIVATE_KEY")],
    },
  },
};

export default config;
```

You can verify the connection by running:

```bash theme={null}
npx hardhat console --network testnet
```

This command launches an interactive JavaScript console connected directly to the Hedera testnet, providing access to the [Ethers.js library](https://docs.ethers.org/v6/) for blockchain interactions. If you successfully enter this interactive environment, your Hardhat configuration is correct. To exit the interactive console, press `ctrl + c` twice.

We won't be using `ignition` and we will be removing the default contracts that come with the Hardhat default project, so we will remove all the unnecessary directories and files first:

```bash theme={null}
rm -rf contracts/* scripts/* test/*
rm -rf ignition
```

***

## Step 2: Creating the ERC-721 Contract

Create a new Solidity file (`MyToken.sol`) in our `contracts` directory:

```solidity contracts/MyToken.sol theme={null}
// SPDX-License-Identifier: MIT
// Compatible with OpenZeppelin Contracts ^5.0.0
pragma solidity ^0.8.28;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyToken is ERC721, Ownable {
    uint256 private _nextTokenId;

    constructor(address initialOwner)
        ERC721("MyToken", "MTK")
        Ownable(initialOwner)
    {}

    function safeMint(address to) public onlyOwner returns (uint256) {
        uint256 tokenId = _nextTokenId++;
        _safeMint(to, tokenId);
        return tokenId;
    }
}
```

This contract was created using the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/#erc721) and OpenZeppelin's ERC-721 standard implementation with an ownership model. The ERC-721 token's name has been set to "MyToken." The contract implements the `safeMint` function, which accepts the address of the owner of the new token and uses auto-increment IDs, starting from 0.

Let's compile this contract by running:

```bash theme={null}
npx hardhat build
```

This command will generate the smart contract artifacts, including the [ABI](/evm/development/compiling). We are now ready to deploy the smart contract.

***

## Step 3: Deploy Your ERC-721 Smart Contract

Create a deployment script (`deploy.ts`) in `scripts` directory:

```typescript scripts/deploy.ts theme={null}
import { network } from "hardhat";

const { ethers } = await network.connect({
  network: "testnet",
});

async function main() {
  // Get the signer of the tx and address for minting the token
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contract with the account:", deployer.address);

  // The deployer will also be the owner of our NFT contract
  const MyToken = await ethers.getContractFactory("MyToken", deployer);
  const contract = await MyToken.deploy(deployer.address);

  await contract.waitForDeployment();

  const address = await contract.getAddress();
  console.log("Contract deployed at:", address);
}

main().catch(console.error);
```

In this script, we first retrieve your account (the deployer) using Ethers.js. This account will own the deployed smart contract. Next, we use this account to deploy the contract by calling `MyToken.deploy(deployer.address)`. This passes your account address as the initial owner and signer of the deployment transaction.

Deploy your contract by executing the script:

```bash theme={null}
npx hardhat run scripts/deploy.ts --network testnet
```

<Check>
  Copy the deployed address. You'll need this in subsequent steps.
</Check>

The output looks like this:

```bash theme={null}
~/projects/hardhat-erc-721-mint-burn >> npx hardhat run scripts/deploy.ts --network testnet
Compiling your Solidity contracts...
Compiled 1 Solidity file with solc 0.8.28 (evm target: cancun)

Deploying contract with the account: 0xA98556A4deeB07f21f8a66093989078eF86faa30
Contract deployed at: 0x6035bA3BCa9595637B463Aa514c3a1cE3f67f3de
```

***

## Step 4: Minting an ERC-721 Token

Create a `mint.ts` script in your `scripts` directory to mint an NFT. Don't forget to replace the `<your-contract-address>` with the address you've just copied.

```typescript scripts/mint.ts theme={null}
import { network } from "hardhat";

const { ethers } = await network.connect({
  network: "testnet",
});

async function main() {
  const [deployer] = await ethers.getSigners();

  // Get the ContractFactory of your MyToken ERC-721 contract
  const MyToken = await ethers.getContractFactory("MyToken", deployer);

  // Connect to the deployed contract
  // (REPLACE WITH YOUR CONTRACT ADDRESS)
  const contractAddress = "<your-contract-address>";
  const contract = MyToken.attach(contractAddress);

  // Mint a token to ourselves
  const mintTx = await contract.safeMint(deployer.address);
  const receipt = await mintTx.wait();
  console.log("receipt: ", JSON.stringify(receipt, null, 2));
  const mintedTokenId = receipt?.logs[0].topics[3];
  console.log("Minted token ID:", mintedTokenId);

  // Check the balance of the token
  const balance = await contract.balanceOf(deployer.address);
  console.log("Balance:", balance.toString(), "NFTs");
}

main().catch(console.error);
```

The code mints a new NFT to your account ( `deployer.address` ). Then we verify the balance to see if we own an ERC-721 token of type `MyToken`.

**Mint an NFT:**

```bash theme={null}
npx hardhat run scripts/mint.ts --network testnet
```

**Expected output:**

```json wrap theme={null}
~/projects/hardhat-erc-721-mint-burn >> npx hardhat run scripts/mint.ts --network testnet
Compiling your Solidity contracts...

Nothing to compile

receipt:  {
  "_type": "TransactionReceipt",
  "blockHash": "0x110b2de909e2f4d515b76de4ffd7a8a9f4c3e68c79f8aa083f9baf2a7d082a5c",
  "blockNumber": 23836191,
  "contractAddress": "0x6035bA3BCa9595637B463Aa514c3a1cE3f67f3de",
  "cumulativeGasUsed": "800000",
  "from": "0xA98556A4deeB07f21f8a66093989078eF86faa30",
  "gasPrice": "350000000000",
  "blobGasUsed": null,
  "blobGasPrice": null,
  "gasUsed": "800000",
  "hash": "0xb0a67ee89e224208599b29a71bc5de1abc5aba4cf64553893aaf0aeb051f7a91",
  "index": 9,
  "logs": [
    {
      "_type": "log",
      "address": "0x6035bA3BCa9595637B463Aa514c3a1cE3f67f3de",
      "blockHash": "0x110b2de909e2f4d515b76de4ffd7a8a9f4c3e68c79f8aa083f9baf2a7d082a5c",
      "blockNumber": 23836191,
      "data": "0x",
      "index": 0,
      "topics": [
        "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
        "0x0000000000000000000000000000000000000000000000000000000000000000",
        "0x000000000000000000000000a98556a4deeb07f21f8a66093989078ef86faa30",
        "0x0000000000000000000000000000000000000000000000000000000000000000"
      ],
      "transactionHash": "0xb0a67ee89e224208599b29a71bc5de1abc5aba4cf64553893aaf0aeb051f7a91",
      "transactionIndex": 9
    }
  ],
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000002001000000000000000000000000000000020000000000000000000800000000000000000000000010000000000000000000000400000000020000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000",
  "root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  "status": 1,
  "to": "0x6035bA3BCa9595637B463Aa514c3a1cE3f67f3de"
}
Minted token ID: 0x0000000000000000000000000000000000000000000000000000000000000000
Balance: 1 NFTs
```

***

## Step 5: Verify Your Smart Contract with Hardhat

After deploying your smart contract, you can verify the source code programmatically from Hardhat. Programmatic verification is the most reliable and efficient method, especially for complex or upgradeable contracts, because Hardhat already knows your exact compilation settings, dependency graph, and deployment artifacts.

Hardhat submits the verification request to [Sourcify](https://sourcify.dev), which natively supports Hedera Mainnet (chain ID `295`) and Testnet (chain ID `296`). Once Sourcify accepts the match, the verified status surfaces automatically on [HashScan](https://hashscan.io/) and any other explorer that reads from Sourcify.

### Install the Verification Plugin

Hardhat's official [`@nomicfoundation/hardhat-verify`](https://hardhat.org/hardhat-runner/plugins/nomicfoundation-hardhat-verify) plugin supports Sourcify out of the box.

Install the plugin in your project:

```bash theme={null}
npm i -D @nomicfoundation/hardhat-verify
```

### Configure Hardhat for Verification

Import the plugin in your `hardhat.config.ts` file and enable Sourcify verification. Because Hedera is supported on the default Sourcify server (`https://sourcify.dev/server`), no custom `apiUrl` is needed.

```typescript theme={null}
import hardhatVerify from "@nomicfoundation/hardhat-verify"; // <--- ADD THIS LINE

import type { HardhatUserConfig } from "hardhat/config";
import hardhatToolboxMochaEthersPlugin from "@nomicfoundation/hardhat-toolbox-mocha-ethers";
import { configVariable } from "hardhat/config";

const config: HardhatUserConfig = {
  plugins: [hardhatToolboxMochaEthersPlugin, hardhatVerify], // ADD TO PLUGIN LIST
  solidity: {
    profiles: {
      default: {
        version: "0.8.28"
      },
      production: {
        version: "0.8.28",
        settings: {
          optimizer: {
            enabled: true,
            runs: 200
          }
        }
      }
    }
  },
  networks: {
    testnet: {
      type: "http",
      url: configVariable("HEDERA_RPC_URL"),
      accounts: [configVariable("HEDERA_PRIVATE_KEY")],
      chainId: 296
    }
  },
  sourcify: {
    enabled: true
  }
};

export default config;
```

### Run the Verification Command

The plugin adds the `verify` task to Hardhat. The basic command structure is:

```bash theme={null}
npx hardhat verify --network <NETWORK_NAME> <CONTRACT_ADDRESS> [constructor_args...]
```

### Example: Verifying Your MyToken Contract

Using the contract address from your deployment, pass the deployer address (the `initialOwner` constructor argument) at the end of the command:

```bash theme={null}
# Replace with your actual deployed contract address
CONTRACT_ADDRESS="0x6035bA3BCa9595637B463Aa514c3a1cE3f67f3de"
DEPLOYER_ADDRESS="0xA98556A4deeB07f21f8a66093989078eF86faa30"

npx hardhat verify --network testnet "$CONTRACT_ADDRESS" "$DEPLOYER_ADDRESS"
```

The plugin uploads the source code and metadata to Sourcify and you should receive a **Full Match** verification status. The verified contract will then appear on HashScan automatically.

**Troubleshooting Verification**

| **Issue**                        | **Solution**                                                                                                                                                                                   |
| :------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Verification Fails/Mismatch      | Ensure your local compilation settings (Solidity version, optimizer runs, viaIR) exactly match the settings used for deployment. Run `npx hardhat clean && npx hardhat build` before retrying. |
| Constructor Arguments Error      | If your contract has constructor arguments, pass them as positional arguments after the contract address in the verification command.                                                          |
| Hardhat Keystore Password Prompt | The task may prompt for your Hardhat keystore password if it needs to sign a transaction to read deployment details. Enter it when prompted.                                                   |

**Congratulations! 🎉 You have successfully learned how to deploy and verify an ERC-721 smart contract using Hardhat, OpenZeppelin, and Ethers. Feel free to reach out in** [**Discord**](https://hedera.com/discord)**!**

***

## Next Steps

* Learn how to add [Access Control, Pause, and Transfer ERC-721 ](/evm/tutorials/advanced/erc721-hardhat/part2-access-control)tokens
* Check out [OpenZeppelin ERC-721 Documentation](https://docs.openzeppelin.com/contracts/5.x/erc721)
* See the full code in the [Hedera-Code-Snippets Repository](https://github.com/hedera-dev/hedera-code-snippets/tree/main/hardhat-erc-721-mint-burn)

<Columns cols={2}>
  <Card title="Writer: Kiran, Developer Advocate">
    [Github](https://github.com/kpachhai) | [Linkedin](https://www.linkedin.com/in/kiranpachhai/)
  </Card>

  <Card title="Editor: Luke, DevRel Engineer">
    [GitHub](https://github.com/LukeForrest-Hashgraph) | [X](https://x.com/_LukeForrest)
  </Card>

  <Card title="Editor: Krystal, Senior DX Engineer">
    [Github](https://github.com/theekrystallee) | [X](https://x.com/theekrystallee)
  </Card>

  <Card title="Editor: Logan, Senior Software Engineer" arrow>
    [GitHub](https://github.com/quiet-node) | [LinkedIn](https://www.linkedin.com/in/logann131/)
  </Card>

  <Card title="Editor: Jake, Senior DevRel Engineer" arrow>
    [GitHub](https://github.com/jaycoolh) | [X](https://x.com/jaycoolh)
  </Card>

  <Card title="Editor: Michiel, DevRel Engineer" arrow>
    [GitHub](https://github.com/michielmulders) |
    [LinkedIn](https://www.linkedin.com/in/michielmulders/)
  </Card>
</Columns>
