Developing your first app
Install Node.js and npm if not already installed
npm install --save-dev hardhat1
2
3
Writing and Deploying Your First Contract
1
Create a contract file
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, and the import of "hardhat/console.sol", 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);
}
}2
Create a deployment script
const hre = require("hardhat");
async function main() {
console.log("Deploying Lock contract...");
// Get the contract factory
const Lock = await hre.ethers.getContractFactory("Lock");
// Deploy the contract
// The constructor requires a timestamp for the unlock time
const unlockTime = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 365; // 1 year from now
const lock = await Lock.deploy(unlockTime);
// Wait for deployment to finish
await lock.waitForDeployment();
const lockAddress = await lock.getAddress();
console.log(`Lock contract deployed to: ${lockAddress}`);
// Wait for a few block confirmations before verifying
console.log("Waiting for block confirmations...");
await new Promise(resolve => setTimeout(resolve, 30000)); // Wait 30 seconds
// Verify the contract
console.log("Verifying contract...");
try {
await hre.run("verify:verify", {
address: lockAddress,
constructorArguments: [unlockTime],
});
console.log("Contract verified successfully");
} catch (error) {
if (error.message.includes("Already Verified")) {
console.log("Contract is already verified!");
} else {
console.error("Error verifying contract:", error);
}
}
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});3
Project structure
my-first-contract/
├── contracts/
│ └── Lock.sol
├── scripts/
│ └── deploy.js
├── .env
├── hardhat.config.js
└── package.json
