cyfuer

Jul 10, 2022

学习笔记:《Full Stack Blockchain Lesson 6:Hardhat Simple Storage

 
 
 

Introduction

notion image

Hardhat Setup

Troubleshooting Hardhat Setup

  • Special Guest Cami Ramos Garzon
    • Two common problems that you might see
    • can’t get back the menu like this after installing hard hat and running the command npx hard hat in your new project folder
      • notion image
        it usually just means that you have a config file somewhere that it shouldn't be, and deleting it will get rid of that error.
        // 1.find the file npx hardhat --verbose // 2.delete the config file // 3.recreate npx harhat
         
    • for getting to npm install
 
 

Hardhat Setup Continued

yarn hardhat
AVAILABLE TASKS:
e.g. yarn hardhat [task] AVAILABLE TASKS: check Check whatever you need clean Clears the cache and deletes all artifacts compile Compiles the entire project, building all artifacts console Opens a hardhat console coverage Generates a code coverage report for tests flatten Flattens and prints contracts and their dependencies gas-reporter:merge help Prints this message node Starts a JSON-RPC server on top of Hardhat Network run Runs a user-defined script after compiling the project test Runs mocha tests typechain Generate Typechain typings for compiled contracts verify Verifies contract on Etherscan

Deploying SimpleStorage from Hardhat

notion image
 
rename Lock.sol to SimpleStorage.sol, and update the code.
notion image
 
fix solidity version error,go to hardhat.config.js and change the version of solidity.
notion image
 
compile product.
yarn hardhat compile
 
add prettier and solidity prettier plugins. add file named “.prettierrc”, and add file named “.prettierignore” which tells prettier not to format some files.
yarn add --dev prettier prettier-pulgin-solidity
notion image
notion image
 
 
edit deploy.js.
notion image
// imports const { ethers } = require("hardhat") // async main async function main() { const SimpleStorageFactory = await ethers.getContractFactory( "SimpleStorage" ) console.log("Deploying contract...") const simpleStorage = await SimpleStorageFactory.deploy() await simpleStorage.deployed() // what's the private key? // what's the rpc url? console.log(`Deployed contract to:${simpleStorage.address}`) } // main main().then(() => process.exit(0)).catch((error) => { console.error(error); process.exit(1); })
 

Networks in Hardhat

  • Hardhat configuration
    • hardhat have defaultNetwork.
      notion image
       
      add network sections that we want in hardhat.config.js.
      1. add modules dotenv
        1. yarn add --dev dotenv
      1. create file named “.env” and edit it.
        1. notion image
      1. edit hardhat.config.js.
        1. notion image
      1. deploy contract with rinkeby.
        1. // compile by rinkeby yarn hardhat run scripts/deploy.js --network rinkeby // compile by default yarn hardhat run scripts/deploy.js // or yarn hardhat run scripts/deploy.js --network hardhat
 
 

Programmatic Verification

 
 
 
  • Verify
    • notion image
Install hardhat-etherscan to make verification process much much easier.
npm install --savedev @nomiclabs/hardhat-etherscan
And add the following statement to hardhat.config.js file.
require("@nomiclabs/hardhat-etherscan");
 
Add following Etherscan config to hardhat.config.js file.
module.exports = { networks: { mainnet: { ... } }, etherscan: { // Your API key for Etherscan // Obtain one at https://etherscan.io/ appKey: "YOUR ETHERSCAN_ API KEY" } };
 
Get api key for Etherscan.
notion image
Add api key in .env.
notion image
And add the following statement to hardhat.config.js file.
notion image
 
We‘ll get a new verify task.
notion image
programing verification.
notion image
notion image
 

Interacting with Contracts in Hardhat

 

Artifacts Troubleshooting

Custom Hardhat Tasks

  • Custom block-number task
    • Create tasks folder, and create block-number.js file.
      notion image
      const { task } = require("hardhat/config") task("block-number", "prints the current block number").setAction( // async(taskArgs, hre) => { const blockNumber = await hre.ethers.provider.getBlockNumber() console.log(`Current block number:${blockNumber}`) } )
       
      Import block-number.js to hardhat.config.js .
      require("./tasks/block-number")
       
      excute command yarn hardhat , you will see the log following image.
      notion image
       
      Now you can use the task named block-number .
      yarn hardhat block-number
 
 

Hardhat Localhost Node

 

Default Hardhat Network

every time we work with the harthat network, or every time we run a script, the hardhat network id deleted
 

hardhat node

Execute following command to create new local host, but it isn’t on the default hardhat network.
# create new network everytime yarn hardhat node
notion image
 
 

Custom local host

notion image
 

The Hardhat Console

Hardhat Tests

  • Basic test
    • Create test folder and test-deploy.js file.
      notion image
Edit test-deploy.js file.
const { ethers } = require("hardhat") const { expect, assert } = require("chai") // describe("SimpleStorage", () => {}) describe("SimpleStorage", function () { // let simpleStorageFactory // let simpleStorage 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" // assert // expect assert.equal(currentValue.toString(), expectedValue) // expect(currentValue.toString()).to.equal(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) }) // Extra - this is not in the video it("Should work correctly with the people struct and array", async function () { const expectedPersonName = "Patrick" const expectedFavoriteNumber = "16" const transactionResponse = await simpleStorage.addPerson( expectedPersonName, expectedFavoriteNumber ) await transactionResponse.wait(1) const { favoriteNumber, name } = await simpleStorage.people(0) // We could also do it like this // const person = await simpleStorage.people(0) // const favNumber = person.favoriteNumber // const pName = person.name assert.equal(name, expectedPersonName) assert.equal(favoriteNumber, expectedFavoriteNumber) }) })
Run test.
notion image
notion image
 
  • Test seeing how much gas function cost
    • Install hardhat-gas-reporter , this is an extension that gets attached to all of our tests and automatically gives us an output that looks like this that tells us approximately how much gas each one of our functions cost.
      notion image
      # or yarn add hardhat- gas-reporter -dev npm install hardhat-gas-reporter --save-dev
       
      Add a new section called gas reporter to have it run whenever we run our test in hardhat.config.js .
      require("hardhat-gas-reporter") module.exports = { gasReporter: { enable: true, } }
       
      Run following command, and then it will automatically run this gas reporter.
      yarn hardhat test
      notion image
Add outputFile in hardhat.config.js , Make it to output file. and then in .gitignored add the file.
require("hardhat-gas-reporter") module.exports = { gasReporter: { enable: true, outputFile: "gasreport.txt", noColors: true, // the colors can get messed up basically when we output to a file currency: "USD", // get the cost of each function in usd coinmarketcap: "your coinmarketcap api key", // in order to get currency here token: "MATIC", } }
notion image
notion image
 
  • Test covered
    • Install solidity-coverage, this is also a hardhat plugin that we can use for our code slowly, tests and sees how many lines of our .sol code is covered in a test.
      yarn add --dev solidity-coverage
       
      Import solidity-coverage to hardhat.config.js .
      require("solidity-coverage")
       
      Run following command to see coverage by default.
      yarn hardhat coverage
      notion image

Hardhat Gas Reporter

Solidity Coverage

Hardhat Waffle

Lesson 6 Recap

Typescript Hardhat Simple Storage

yarn add --dev @typechain/ethers-v5 @typechain/hardhat @types/chai

Copyright © 2025 cyfuer

logo