📖
Notes
  • 🙌Welcome!
  • CyberSecurity
    • Penetration Testing
      • ELearnSecurity
        • eJPT
          • Footprinting & Scanning
            • Port Scanning
            • Mapping Networks
          • Information Gathering
            • Subdomain Enumeration
          • Network Attacks
            • Arp Poisoning
            • Null Sessions
            • Windows Shares
            • Authentication Cracking
          • Networking
            • Python Server to Receive Exfiltrated Data
            • CLI Tool to interact with HTTP/HTTPS
          • Programming
            • C++ Keylogger
            • C++ Information Stealer
          • System Attacks
            • Pivoting
            • Backdoor
          • Vulnerability Assessment
          • Web Attacks
            • SQL Injection
            • HTTP Verbs
            • Web Server Fingerprinting
      • PortSwigger
        • Cross-origin resource sharing (CORS)
          • Access-Control-Allow-Origin response header
          • Vulnerabilities arising from Misconfigurations
            • Server-generated ACAO header from client-specified Origin header
            • Errors parsing Origin headers
            • Whitelisted null origin value
            • Exploiting XSS via CORS trust relationships
            • Breaking TLS with poorly configured CORS
            • Intranets and CORS without credentials
            • Mitigations
        • Sql Injection
          • Examining the database
          • Retrieving data from other database tables
          • Blind SQL injection
          • Mitigation
      • TryHackMe
        • Main Methodology
          • 1. Reconnaissance
            • Google Dorking
            • Metadata Reader/Writer
            • Steghide - Stegnography
            • OSINT Framework
          • 2. Enumeration/Scanning
            • NFS Enumeration Tools
            • NMAP - Port Scanning
            • Web Enumeration Tools
            • SMB Enumeration Tools
            • SMTP Enumeration Tools
            • Shodan - IOT Search Engine
            • FTP Enumeration Tools
            • Wordpress Enumeration Tools
            • OWASP ZAP - WebApp Testing
            • BurpSuite - WebApp Testing
            • MySQL Enumeration Tools
            • Wordlists
          • 3. Gaining Access / Exploitation
            • Buffer Overflow
              • 1. Immunity Debugger
              • 2. Mona Setup
              • 3. Spiking
              • 4. Fuzzing
              • 5. Crash Replication & Controlling EIP
              • 6. Finding Bad Characters
              • 7. Find a Jump Point
              • 8. Generate Payload
              • 9. Prepend NOPs
              • 10. Final Buffer
            • Cryptography
              • Hash Crack Tools
              • Online Password Cracking Tools
              • Encryption
              • John the Ripper
            • Evasion Techniques
            • Shells
              • Powershell
              • Msfvenom
              • Meterpreter
              • Metasploit -- multi/handler
              • Netcat
              • Socat
            • Web Applications
              • OWASP Top 10
              • File Upload Vulnerabilities
              • Authentication Vulnerability
              • XML External Entity (XXE)
              • Cross-Site Scripting (XSS)
              • ZTH: Obscure Web Vulns
              • Server Side Request Forgery (SSRF)
              • Insecure Direct Object Reference (IDOR)
              • ZTH : Continued
              • File Inclusion Vulnerability
                • Local File Inclusion (LFI)
                • Log Poisoning Attack (LFI to RCE via Log files)
            • Windows Applications
              • Jenkins
              • Windows Active Directory
                • Impacket's secretsdump.py
                • Kerberos
                  • Enumerating Users with Kerbrute
                  • Enumerating SPN Accounts with Powershell
                  • Get SPN Account Ticket with Invoke-Kerberoast
                  • Kerberoasting with Rubeus & Impacket
                  • AS-REP Roasting with Rubeus/GetNPUsers.py
                  • Pass the Ticket with mimikatz
                  • Golden/Silver Ticket Attacks with mimikatz
                  • Kerberos Backdoors with mimikatz
                  • Harvesting and Brute-Forcing with Rubeus
                  • Conclusion and Resources
          • 4. Post Exploitation
            • Privilege Escalation
              • Linux
                • 1. Introduction
                • 2. Scripts
                • 3. Kernel Exploits
                • 4. Service Exploits
                • 5. Weak File Permissions
                • 6. Sudo
                • 7. Cron jobs
                • 8. SUID/SGID Executable
                • 9. CAP_SETUID Capabilities Executable
                • 10. Passwords & Keys
                • 11. NFS
                • PrivEsc CTF Checklists
              • Windows
                • Token Impersonation
                • PrivEsc CTF Checklists
                • Permission
                • Scripts
                • Unquoted Service Path
            • Tools
              • Meterpreter Modules
              • Impacket's Psexec
              • Impacket's mssqlclient.py
              • Firefox Decryptor
              • Socat - Reverse TCP Tunnel
            • Windows Active Directory
              • Enumeration with Powerview
              • Enumeration with Bloodhound (GUI)
              • Dumping Hashes with mimikatz
              • Golden Ticket Attacks with mimikatz
              • Enumeration with Server Manager
              • Maintaining Access
              • Additional Resources
          • 5. Covering Tracks
          • 6. Reporting
        • Networking Concepts
          • SSH Reverse Tunnels
        • Scripting
          • Curl
          • Powershell
            • Basic Powershell Commands
            • Enumeration
        • Web Extensions
          • Shodan
          • Wappalyzer
      • Miscellaneous
        • SMTP Enumeration
        • Nmap Advanced Scanning
        • Persistence via Meterpreter
        • DNS Enumeration
        • NetBIOS & SMB
        • DHCP Starvation
        • Packet Manipulation
        • Hash Cracking
        • MITM
        • Msfvenom Payload in APK (Manual Embedding)
    • Blue Teaming
      • Digital Forensics & Incidence Response
        • Memory Acquisition with LIME
        • Disk Analysis with Autopsy
        • Data and Memory Collection with FireEye Redline
        • Memory Forensice with Volatility
      • Intrusion Detection
        • Intrusion Detection Systems (IDS)
        • Threat Monitoring with Security Information & Event Management (SIEM)
        • Security Event Monitoring
        • Host Based Intrusion Detection System (HIDS) - OSSEC
      • Miscellaneous
        • Docker Image Security Analysis with Trivy
  • DevOps
    • Infrastructure as a Code (IaC)
      • Ansible
        • 1. Playbooks
        • 2. Modules
        • 3. Inventory
        • 4. Roles
        • 5. Ansible Tower
      • Terraform
        • 1. Overview
        • 2. Modify Resources
        • 3. Delete Resources
        • 4. Reference Resources
        • 5. Terraform Files
        • 6. Terraform State Commands
        • 7. Terraform Output
        • 8. Target Resources
        • 9. Terraform Variables
        • 10. Expressions + Functions
        • 11. Meta-Arguments
        • 12. Modules
        • 13. Managing Multiple Environments
        • 14. Testing Terraform Code
        • 15. Final Thoughts
    • Orchestration
      • Kubernetes
        • 1. Main K8s Components
        • 2. K8s Architecture
        • 3. Minikube & Kubectl
        • 4. YAML Configuration File
        • 5. K8s Namespaces
        • 6. K8s Ingress
        • 7. Helm - Package Manager of K8s
        • 8. K8 Volumes
        • 9. K8 StatefulSet
        • 10. K8 Services
  • Development
    • Blockchain
      • FreeCodeCamp Course
        • 1. Introduction
        • 2. Solidity Basics
        • 3. Storage Factory
        • 4. Fund Me
        • 5. Ethers.js
        • 6. Hardhat
        • 7. Hardhat | Fund Me
        • 8. Contract Lottery | Raffle
        • 9. IPFS
        • 10. ERC20s
        • 11. DeFi & Aave
        • 12. NFTs | Encoding
        • 13. Reentrancy Attack
    • Backend
      • NodeJs
        • Introduction
        • Additional Concepts
        • ExpressJs
    • Database
      • SQL
        • Basics
          • 1. Querying Data
          • 2. Filtering Data
          • 3. Joining Multiple Tables
          • 4. Grouping Data
          • 5. Set Operations
          • 6. Grouping Sets, Cube, and Rollup
          • 7. Subquery
          • 8. Common Table Expressions
          • 9. Modifying Data
          • 10. Transactions
          • 11. Import & Export Data
          • 12. Managing Tables
    • Testing
      • Test Driven Development (TDD)
      • Jest js
      • Cypress js
Powered by GitBook
On this page
  • Hardhat Setup
  • Deploying SimpleStorage (Method 1)
  • Networks in Hardhat
  • Programatic Verification
  • Interacting with Contracts in Hardhat
  • Artifacts Troubleshooting
  • Custom Hardhat Tasks
  • Hardhat Localhost Node
  • Hardhat console
  • Running Tests
  • Hardhat Gas Reporter
  • Solidity Coverage
  • Hardhat Waffle
  1. Development
  2. Blockchain
  3. FreeCodeCamp Course

6. Hardhat

Hardhat Setup

  • Installed as a node package using npm or yarn

  • Accessed via yarn hardhat

  • Contracts compiled via yarn hardhat compile


Deploying SimpleStorage (Method 1)

  • yarn hardhat run scripts/deploy.js

const { ethers } = require("hardhat");

async function main() {
  const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
  console.log("Deploying contract...");

  const simpleStorage = await SimpleStorageFactory.deploy();
  await simpleStorage.deployed();

  console.log(`Deployed contract to: ${simpleStorage.address}`);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.log(error);
    process.exit(1);
  });

Networks in Hardhat

  • Hardhat contains default hardhat network, rpc and wallet by default

  • We can edit hardhat.config.js file to change default settings

  • We can also explicitly select network while running hardhat i.e yarn hardhat run scripts/deploy.js --network goerli

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

const GOERLI_RPC_URL = process.env.GOERLI_RPC_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  defaultNetwork: "hardhat",
  networks: {
    goerli: {
      url: GOERLI_RPC_URL,
      accounts: [PRIVATE_KEY],
      chainId: 5,
    },
  },
  solidity: "0.8.17",
};

Programatic Verification

  • In our code script, we can automatically verify our contract code upon deployment

  • Works on block explorers like etherScan, might not work on other explorers

  • We can use etherScan API or use hardhat plugins hardhat-etherscan

hardhat.config.js

// ...
require("@nomiclabs/hardhat-etherscan");
// ...
module.exports = {
	// ...
	solidity: "0.8.17",
  etherscan: {
    apiKey: ETHERSCAN_API_KEY,
  },
};

deploy.js

// Run package allows us to run any hardhat task in code
// Network package gives us network information
const { ethers, run, network } = require("hardhat");

async function main() {
  // ...
  // Only verify if we are on goerli test network
  /*
    4 == 4 -> true
    4 == "4" -> true
    4 === "4" -> false (no type conversion is done)
  */
  if (network.config.chainId === 5 && process.env.ETHERSCAN_API_KEY) {
    console.log("Waiting for block txes...");
    await simpleStorage.deployTransaction.wait(6);
    await verify(simpleStorage.address, []);
  }
}

async function verify(contractAddress, args) {
  console.log("Verifying contract...");

  try {
    await run("verify:verify", {
      address: contractAddress,
      constructorArguments: args,
    });
  } catch (e) {
    if (e.message.toLowerCase().includes("already verified")) {
      console.log("Already Verified!");
    } else {
      console.log(e);
    }
  }
}

Interacting with Contracts in Hardhat

deploy.js

  const currentValue = await simpleStorage.retrieve();
  console.log(`Current Value is: ${currentValue}`);

  const transactionResponse = await simpleStorage.store(7);
  await transactionResponse.wait(1);
  const updatedValue = await simpleStorage.retrieve();
  console.log(`Updated Value is: ${updatedValue}`);

Artifacts Troubleshooting

  • Delete the cache and artifacts folder if any issue arises (yarn hardhat clean)

  • Hardhat will re compile and generate the artifacts


Custom Hardhat Tasks

  • Can be defined in hardhat.config.js

  • Generally created in tasks folder

  • Can be accessed via yarn hardhat block-number

tasks/block-number.js

const { task } = require("hardhat/config");

task("block-number", "Prints the current block number").setAction(
  // hre is like importing hardhat, gives access to all functionalities
  async (taskArgs, hre) => {
    const blockNumber = await hre.ethers.provider.getBlockNumber();
    console.log(`Current block number: ${blockNumber}`);
  }
);

module.exports = {};

hardhat.config.js

// ...
require("./tasks/block-number");
// ...

Hardhat Localhost Node

  • yarn hardhat node spins up a local blockchain node as ganache, gives us accounts and rpc

  • The rpc url must be added to hardhat config like before in order to use that localnode


Hardhat console

  • let us run interactive commands to interact with blockchain

  • yarn hardhat console --network <network>


Running Tests

  • Hardhat works with mocha framework which is a javascript framework for running tests

  • chai framework is required for assert and expect statements

  • We can run individual tests using grep pattern matching in it description like yarn hardhat test --grep store

  • We can also use it.only keyword which will ignore all other test cases and run only this test case

test/test-deploy.js

const { ethers } = require("hardhat");
const { expect, assert } = require("chai");

describe("SimpleStorage", function () {
  let simpleStorageFactory, simpleStorage;

  beforeEach(async function () {
    simpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
    simpleStorage = await simpleStorageFactory.deploy();
  });

  it("Should start with a favorite number of 0", async function () {
    const currentValue = await simpleStorage.retrieve();
    const expectedValue = "0";

    // expect(currentValue.toString()).to.equal(expectedValue)
    assert.equal(currentValue.toString(), expectedValue);
  });

  it("Should update when we call store", async function () {
    const expectedValue = "7"
    const transactionResponse = await simpleStorage.store(expectedValue)
    await transactionResponse.wait(1)

    const currentValue = await simpleStorage.retrieve()
    assert.equal(currentValue.toString(), expectedValue)
  })
});

Hardhat Gas Reporter

  • Popular hardhat extension to see how much gas our funciton costs

  • Automatically gets attached to our tests

  • Can also specify which tokens to test gas for

hardhat.config.js

require("hardhat-gas-reporter")
// ...
  etherscan: {
    apiKey: ETHERSCAN_API_KEY,
  },
  gasReporter: {
    enabled: true,
    outputFile: "gas-reports.txt",
    noColors: true,
    currency: "USD",
    coinmarketcap: COINMARKETCAP_API_KEY,
    token: "MATIC"
  }

Solidity Coverage

  • A hardhat plugin that checks how many lines of our .sol code is covered in a test

  • Added in hardhat.config.js on the top as require("solidity-coverage")

  • Also generates a folder and file called coverage and coverage.json


Hardhat Waffle

  • Advanced testing framework for solidity by hardhat


Previous5. Ethers.jsNext7. Hardhat | Fund Me

Last updated 1 year ago