Hello, everybody.
If you’re a developer looking to deploy your first smart contract using Hardhat, this guide is for you. I’ll walk you through the process step-by-step, from setting up your project to deploying your contract on the Ethereum network.
Step 1: Project Setup
Create a new project directory:
mkdir smart-contract-guide
cd smart-contract-guide
- Initialize a Node.js project and install Hardhat:
npm init -y
npm install --save-dev hardhat
Step 2: Write the Smart Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract BasicNft is ERC721 {
string public constant TOKEN_URI =
"ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json";
uint256 private s_tokenCounter;
constructor() ERC721("Dogie", "DOG") {
s_tokenCounter = 0;
}
function mintNft() public returns (uint256) {
_safeMint(msg.sender, s_tokenCounter);
s_tokenCounter = s_tokenCounter + 1;
return s_tokenCounter;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
// require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return TOKEN_URI;
}
function getTokenCounter() public view returns (uint256) {
return s_tokenCounter;
}
}
Step 3: Deployment using ignition module.
Inside the ignition/module directory, create a file named BasicNft.ts:
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";
const DeployMyTokenModule = buildModule("DeployMyTokenModule", (m) => {
const myToken = m.contract("BasicNft");
return { myToken };
});
export default DeployMyTokenModule;
Step 4: Configure Hardhat
Create a file named hardhat.config.js:
module.exports = {
solidity: "0.8.0",
networks: {
// Define your networks here, such as "sepolia", "goerli", "mainnet", etc.
// Example:
// sepolia: {
// url: "<SEPOLIA_RPC_URL>",
// accounts: ["0xYOUR_PRIVATE_KEY"],
// },
},
};
Step 5: Test Your Contract
Step 6: Deploy Your Contract
npx hardhat ignition deploy ./ignition/modules/BasicNft.ts --network <networkname>
Congratulations! 🎉 You’ve completed the guide on deploying and interacting with a simple smart contract using Hardhat. This hands-on experience sets you on the path to exploring more complex contract functionality and advanced features.
Keep exploring the exciting world of Ethereum smart contracts and enjoy your coding journey! 💡🚀
Top comments (2)
Thank you so much for the post!
I really found it quite interesting and well-written. You explained them very well, which really helped in clarifying concepts.
I'm looking forward to reading your future posts!
Oh, Thanks.