From ed7f8c4f1733a8630637c72192e87effd650f9d9 Mon Sep 17 00:00:00 2001 From: Salman Dabbakuti Date: Sat, 13 Jul 2024 21:26:40 +0530 Subject: [PATCH] Initial commit --- .env.example | 5 ++ .github/workflows/ci.yml | 47 ++++++++++++++ .gitignore | 31 ++++++++++ LICENSE | 21 +++++++ README.md | 49 +++++++++++++++ contracts/Lock.sol | 34 +++++++++++ hardhat.config.ts | 95 ++++++++++++++++++++++++++++ package.json | 20 ++++++ scripts/deploy.ts | 31 ++++++++++ test/Lock.ts | 129 +++++++++++++++++++++++++++++++++++++++ tsconfig.json | 11 ++++ 11 files changed, 473 insertions(+) create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 contracts/Lock.sol create mode 100644 hardhat.config.ts create mode 100644 package.json create mode 100644 scripts/deploy.ts create mode 100644 test/Lock.ts create mode 100644 tsconfig.json diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0aa57ae --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +# Be aware. dont commit this file or any of theses keys to your repo. +PRIVATE_KEY= +POLYGON_MUMBAI_RPC_URL= +POLYGON_MAINNET_RPC_URL= +ETHERSCAN_API_KEY= \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..04e555a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +# adding tests +# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: Node.js CI + +on: + push: + branches: [main, develop, init, "feat/*"] + pull_request: + branches: [main, develop, init, "feat/*"] + +jobs: + e2e-test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + node-version: [18.x, 20.x, 21.x] + # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v4 + - name: Use Node.js ${{ matrix.node-version }} on ${{ matrix.os }} + uses: actions/setup-node@v4 + # uses: borales/actions-yarn@v3.0.0 + with: + node-version: ${{ matrix.node-version }} + - name: "Install packages with npm" + run: npm install + - name: "Copy .env.example to .env" + run: cp .env.example .env + - name: "Check for solidity linter errors" + run: npx hardhat check + - name: "Compile contracts" + run: npm run compile + - name: "Check solidity coverage" + run: npm run coverage + - name: "Start hardhat node" + run: npx hardhat node & sleep 5 + - name: "List accounts with balances" + run: npx hardhat accounts + - name: "Run tests" + run: npm run test + - name: "Deploy contracts" + run: npx hardhat run scripts/deploy.ts --network localhost diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5f82570 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Build and Release Folders +bin-debug/ +bin-release/ +[Oo]bj/ +[Bb]in/ + +# Other files and folders +.settings/ +node_modules/ +package-lock.json +yarn.lock + +# Executables +*.swf +*.air +*.ipa +*.apk +*.env + +# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` +# should NOT be excluded as they contain compiler settings and other important +# information for Eclipse / Flash Builder. +.DS_Store + +#Hardhat files +cache +artifacts/ +coverage/ +coverage.json +typechain/ +typechain-types/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f662fde --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Salman Dabbakuti + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b89f7db --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +# Hardhat Boilerplate + +This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts with balances. + +> Recommended to use Node.js v18+ and npm v8+ + +> Rename `env.example` to `.env` and add your env specific keys. + +Try running some of the following tasks: + +```bash +npm install + +# starts local node +npx hardhat node + +# list accounts with balances +npx hardhat accounts + +# show balance eth of specified account +npx hardhat balance --account '0x47a9...' + +# compile contracts +npx hardhat compile + +# deploy contract defined in tasks on specified network +npx hardhat deploy --network localhost + +# deploy contract in scripts/deploy.ts on specified network +npx hardhat run scripts/deploy.ts --network localhost + +#check linter issues using solhint plugin +npx hardhat check + +# check coverage using solidity-coverage plugin: supports hardhat network only +npx hardhat coverage --network hardhat + +# unit tests including gas usage +npx hardhat test + +# remove all compiled and deployed artifacts +npx hardhat clean + +# verify contract +npx hardhat verify --network "" "" + +# show help +npx hardhat help +``` diff --git a/contracts/Lock.sol b/contracts/Lock.sol new file mode 100644 index 0000000..50935f6 --- /dev/null +++ b/contracts/Lock.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.9; + +// Uncomment this line to use console.log +// 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 { + // 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); + } +} diff --git a/hardhat.config.ts b/hardhat.config.ts new file mode 100644 index 0000000..f3092dc --- /dev/null +++ b/hardhat.config.ts @@ -0,0 +1,95 @@ +import { HardhatUserConfig, task } from "hardhat/config"; +import "@nomicfoundation/hardhat-toolbox"; +import "dotenv/config"; + +const accounts = process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : []; + +// https://hardhat.org/guides/create-task.html +task( + "accounts", + "Prints the list of accounts with balances", + async (_, hre) => { + const accounts = await hre.ethers.getSigners(); + const provider = hre.ethers.provider; + + for (const account of accounts) { + const balance = await provider.getBalance(account.address); + console.log( + `${account.address} - ${hre.ethers.formatEther(balance)} ETH` + ); + } + } +); + +task("deploy", "Deploys Contract", async (_, hre) => { + const currentTimestampInSeconds = Math.round(Date.now() / 1000); + const unlockTime = currentTimestampInSeconds + 365 * 24 * 60 * 60; // 1 year from now + const lockedAmount = hre.ethers.parseEther("0.001"); + + const lockInstance = await hre.ethers.deployContract("Lock", [unlockTime], { + value: lockedAmount + }); + + await lockInstance.waitForDeployment(); + console.log("contract deployed at:", lockInstance.target); +}); + +task("balance", "Prints an account's balance") + .addParam("account", "The account's address") + .setAction(async ({ account }, hre) => { + const provider = hre.ethers.provider; + const balance = await provider.getBalance(account); + console.log(hre.ethers.formatEther(balance), "ETH"); + }); + +const config: HardhatUserConfig = { + defaultNetwork: "localhost", + networks: { + hardhat: { + chainId: 1337 + }, + localhost: { + url: "http://127.0.0.1:8545" + }, + mumbai: { + url: + process.env.POLYGON_MUMBAI_RPC_URL || + "https://rpc-mumbai.maticvigil.com", + accounts + }, + polygon: { + url: + process.env.POLYGON_MAINNET_RPC_URL || + "https://rpc-mainnet.maticvigil.com", + accounts + } + }, + etherscan: { + // API key for Polygonscan + apiKey: process.env.ETHERSCAN_API_KEY + }, + gasReporter: { + enabled: true, + currency: "USD" + }, + solidity: { + version: "0.8.19", + settings: { + optimizer: { + enabled: true, + runs: 200 + } + } + }, + paths: { + sources: "./contracts", + tests: "./test", + cache: "./cache", + artifacts: "./artifacts" + }, + mocha: { + timeout: 20000 + } +}; + +export default config; diff --git a/package.json b/package.json new file mode 100644 index 0000000..25f52e7 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "hardhat-boilerplate", + "version": "1.2.2", + "description": "Hardhat boilerplate for Dapp development", + "private": true, + "scripts": { + "test": "npx hardhat test", + "compile": "npx hardhat compile", + "deploy": "npx hardhat deploy", + "coverage": "npx hardhat coverage --network hardhat" + }, + "keywords": [], + "author": "Salman Dabbakuti", + "license": "ISC", + "devDependencies": { + "@nomicfoundation/hardhat-toolbox": "^4.0.0", + "dotenv": "^16.3.1", + "hardhat": "^2.19.1" + } +} diff --git a/scripts/deploy.ts b/scripts/deploy.ts new file mode 100644 index 0000000..2a1bc0c --- /dev/null +++ b/scripts/deploy.ts @@ -0,0 +1,31 @@ +import { ethers } from "hardhat"; + +async function main() { + const currentTimestampInSeconds = Math.round(Date.now() / 1000); + const unlockTime = currentTimestampInSeconds + 365 * 24 * 60 * 60; // 1 year from now + const lockedAmount = ethers.parseEther("0.001"); + + const lockInstance = await ethers.deployContract("Lock", [unlockTime], { + value: lockedAmount + }); + + await lockInstance.waitForDeployment(); + return lockInstance; +} + +main() + .then(async (lockInstance) => { + console.log("Lock Contract deployed to:", lockInstance.target); + // Read from the contract + const unlockTime = await lockInstance.unlockTime(); + console.log("Unlock time:", unlockTime.toString()); + + // Write to the contract + // const tx = await lockInstance.withdraw(); + // await tx.wait(); + // console.log("Withdrawn!"); + }) + .catch((error) => { + console.error(error); + process.exitCode = 1; + }); diff --git a/test/Lock.ts b/test/Lock.ts new file mode 100644 index 0000000..53e894b --- /dev/null +++ b/test/Lock.ts @@ -0,0 +1,129 @@ +import { + time, + loadFixture +} from "@nomicfoundation/hardhat-toolbox/network-helpers"; +import { anyValue } from "@nomicfoundation/hardhat-chai-matchers/withArgs"; +import { expect } from "chai"; +import { ethers } from "hardhat"; + +describe("Lock Contract Tests", function () { + // We define a fixture to reuse the same setup in every test. + // We use loadFixture to run this setup once, snapshot that state, + // and reset Hardhat Network to that snapshot in every test. + async function deployOneYearLockFixture() { + const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; + const ONE_GWEI = 1_000_000_000; + + const lockedAmount = ONE_GWEI; + const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; + + // Contracts are deployed using the first signer/account by default + const [owner, otherAccount] = await ethers.getSigners(); + + const lock = await ethers.deployContract("Lock", [unlockTime], { + value: lockedAmount + }); + await lock.waitForDeployment(); + + return { lock, unlockTime, lockedAmount, owner, otherAccount }; + } + + describe("Deployment", function () { + it("Should set the right unlockTime", async function () { + const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); + + expect(await lock.unlockTime()).to.equal(unlockTime); + }); + + it("Should set the right owner", async function () { + const { lock, owner } = await loadFixture(deployOneYearLockFixture); + + expect(await lock.owner()).to.equal(owner.address); + }); + + it("Should receive and store the funds to lock", async function () { + const { lock, lockedAmount } = await loadFixture( + deployOneYearLockFixture + ); + + expect(await ethers.provider.getBalance(lock.target)).to.equal( + lockedAmount + ); + }); + + it("Should fail if the unlockTime is not in the future", async function () { + // We don't use the fixture here because we want a different deployment + const latestTime = await time.latest(); + const Lock = await ethers.getContractFactory("Lock"); + await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( + "Unlock time should be in the future" + ); + }); + }); + + describe("Withdrawals", function () { + describe("Validations", function () { + it("Should revert with the right error if called too soon", async function () { + const { lock } = await loadFixture(deployOneYearLockFixture); + + await expect(lock.withdraw()).to.be.revertedWith( + "You can't withdraw yet" + ); + }); + + it("Should revert with the right error if called from another account", async function () { + const { lock, unlockTime, otherAccount } = await loadFixture( + deployOneYearLockFixture + ); + + // We can increase the time in Hardhat Network + await time.increaseTo(unlockTime); + + // We use lock.connect() to send a transaction from another account + await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( + "You aren't the owner" + ); + }); + + it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { + const { lock, unlockTime } = await loadFixture( + deployOneYearLockFixture + ); + + // Transactions are sent using the first signer by default + await time.increaseTo(unlockTime); + + await expect(lock.withdraw()).not.to.be.reverted; + }); + }); + + describe("Events", function () { + it("Should emit an event on withdrawals", async function () { + const { lock, unlockTime, lockedAmount } = await loadFixture( + deployOneYearLockFixture + ); + + await time.increaseTo(unlockTime); + + await expect(lock.withdraw()) + .to.emit(lock, "Withdrawal") + .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg + }); + }); + + describe("Transfers", function () { + it("Should transfer the funds to the owner", async function () { + const { lock, unlockTime, lockedAmount, owner } = await loadFixture( + deployOneYearLockFixture + ); + + await time.increaseTo(unlockTime); + + await expect(lock.withdraw()).to.changeEtherBalances( + [owner, lock], + [lockedAmount, -lockedAmount] + ); + }); + }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..574e785 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es2020", + "module": "commonjs", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "resolveJsonModule": true + } +}