Getting Started with Hardhat for Smart Contract Development on Polygon

·

Hardhat is a powerful Ethereum development environment that empowers developers to build, test, deploy, and debug smart contracts efficiently. Designed with flexibility and extensibility in mind, Hardhat has become a go-to framework for blockchain developers—especially those targeting EVM-compatible networks like Polygon.

In this comprehensive guide, you’ll learn how to set up Hardhat from scratch, create a simple smart contract, compile and test it locally, and deploy it to the Polygon Amoy testnet. Whether you're building decentralized applications (dApps) or experimenting with Solidity, mastering Hardhat is a critical step toward professional blockchain development.

Setting Up Your Development Environment

Before diving into coding, ensure your machine meets the prerequisites:

These tools are essential for managing dependencies and version control in modern development workflows.

Initialize Your Project

Start by creating a new directory and initializing an npm project:

mkdir hardhat-test
cd hardhat-test
npm init -y

Next, install Hardhat as a development dependency:

npm install --save-dev hardhat

👉 Get started with advanced blockchain tools to streamline your smart contract workflow.

Creating a Hardhat Project

With Hardhat installed, generate a starter project using:

npx hardhat

You'll be prompted to choose a project type. Select "JavaScript Project" to proceed. This scaffolds essential files including sample contracts, scripts, and configuration files.

The generated structure includes:

Exploring the Sample Contract

Inside the contracts folder, you’ll find Lock.sol, a basic smart contract demonstrating time-locked fund withdrawal.

Here’s what the contract does:

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

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 {
        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);
    }
}

This contract introduces core concepts such as state variables, modifiers (implicitly via require), events, and Ether transfers—making it ideal for learning.

Configuring Hardhat for Polygon Amoy Testnet

To deploy on Polygon’s Amoy testnet, update your hardhat.config.js with network settings and API integrations.

First, install required plugins:

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

Then configure hardhat.config.js:

require('dotenv').config();
require("@nomicfoundation/hardhat-toolbox");

module.exports = {
  defaultNetwork: "polygon_amoy",
  networks: {
    hardhat: {},
    polygon_amoy: {
      url: "https://rpc-amoy.polygon.technology",
      accounts: [process.env.PRIVATE_KEY]
    }
  },
  etherscan: {
    apiKey: process.env.POLYGONSCAN_API_KEY
  },
  solidity: {
    version: "0.8.9",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  }
};

Create a .env file in the root directory to securely store sensitive data:

PRIVATE_KEY=your_wallet_private_key_here
POLYGONSCAN_API_KEY=your_polygonscan_api_key
🔐 Never commit .env files to version control. Add .env to your .gitignore.

Compiling the Smart Contract

Hardhat simplifies compilation with built-in tasks. Run:

npx hardhat compile

This compiles all Solidity contracts under contracts/, generating artifacts in the artifacts/ folder. These JSON files contain ABI and bytecode—essential for interaction and deployment.

Testing the Contract Locally

Hardhat includes a built-in Ethereum network for fast testing. Write tests in JavaScript or TypeScript under the test/ folder.

Run tests with:

npx hardhat test

Expected output includes:

Testing ensures logic correctness before deployment—critical for avoiding costly bugs.

Why Test?

👉 Discover how top developers accelerate testing and deployment cycles.

Deploying to the Polygon Amoy Testnet

Once tested, deploy your contract using a script. Modify scripts/deploy.js to instantiate and send the contract:

const hre = require("hardhat");

async function main() {
  const Lock = await hre.ethers.getContractFactory("Lock");
  const unlockTime = Math.floor(Date.now() / 1000) + 60; // 1 minute from now
  const lockedAmount = hre.ethers.utils.parseEther("0.001");

  const lock = await Lock.deploy(unlockTime, { value: lockedAmount });

  await lock.deployed();
  console.log(`Lock contract deployed to: ${lock.address}`);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Deploy with:

npx hardhat run scripts/deploy.js --network polygon_amoy

After successful deployment, verify the transaction on Amoy Polygonscan.

Verifying Contracts on Polygonscan

Source code verification increases transparency and trust. Use Hardhat Etherscan plugin:

npx hardhat verify --network polygon_amoy DEPLOYED_CONTRACT_ADDRESS "constructorArg1"

Replace DEPLOYED_CONTRACT_ADDRESS with your actual address and include constructor arguments if applicable.

Verification enables:

Core Keywords

Throughout this guide, we've naturally integrated key terms vital for search visibility and technical accuracy:

These keywords align with common developer search queries and support strong SEO performance without keyword stuffing.


Frequently Asked Questions (FAQ)

Q: What is Hardhat used for?
A: Hardhat is an Ethereum development environment used for compiling, testing, debugging, and deploying smart contracts. It's highly extensible and supports EVM-compatible chains like Polygon.

Q: Can I use Hardhat with Polygon?
A: Yes. By configuring custom RPC endpoints in hardhat.config.js, you can deploy and interact with contracts on both Polygon’s mainnet and testnets like Amoy.

Q: How do I secure my private key when using Hardhat?
A: Store your private key in a .env file and use the dotenv package. Never share or commit this file to public repositories.

Q: Why should I verify my contract on Polygonscan?
A: Verification allows others to view your contract’s source code, improving transparency, trust, and integration ease for other developers.

Q: What tools does Hardhat integrate with?
A: Hardhat works seamlessly with MetaMask, Etherscan/Polygonscan, Waffle, TypeChain, and various testing libraries—making it ideal for full-stack dApp development.

Q: Is Hardhat better than Truffle?
A: While both are Solidity development environments, Hardhat offers superior debugging, TypeScript support, and plugin architecture—making it more modern and developer-friendly.


With Hardhat configured and your first contract live on Polygon Amoy, you're well on your way to mastering decentralized development. Continue exploring advanced patterns like upgradeable contracts, gas optimization, and frontend integration to build production-ready dApps.