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:
- Node.js v10+ LTS (with npm)
- Git
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 -yNext, 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 hardhatYou'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:
contracts/: Contains Solidity source files.scripts/: Holds deployment scripts.test/: For writing unit tests.hardhat.config.js: Main configuration file.
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:
- Accepts a future unlock timestamp during deployment.
- Only allows the owner to withdraw funds after that time has passed.
// 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 dotenvThen 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.envfiles to version control. Add.envto your.gitignore.
Compiling the Smart Contract
Hardhat simplifies compilation with built-in tasks. Run:
npx hardhat compileThis 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 testExpected output includes:
- Test suite execution results.
- Gas usage metrics.
- Pass/fail status for each assertion.
Testing ensures logic correctness before deployment—critical for avoiding costly bugs.
Why Test?
- Validate business logic.
- Simulate edge cases (e.g., early withdrawal attempts).
- Improve code reliability and audit readiness.
👉 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_amoyAfter 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:
- Public inspection of source code.
- ABI access for dApp frontends.
- Enhanced credibility for users and auditors.
Core Keywords
Throughout this guide, we've naturally integrated key terms vital for search visibility and technical accuracy:
- Hardhat
- Polygon Amoy testnet
- Smart contract deployment
- Solidity
- Etherscan verification
- Local blockchain testing
- Hardhat configuration
- Contract compilation
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.