Prerequisite: Install node version >12, npm, git, etc.
1. Create a folder and open it with a tool you are familiar with, such as webstorm
2. After opening, run "npm init -y" and it will print on the console:
{
“name”: “76-learn-hardhat”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo “Error: no test specified” && exit 1”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”
}
3. Run npm install --save-dev hardhat. After success, the following is as follows:
Note: Solution to the error: npm install --save-dev “@nomiclabs/hardhat-ethers@^2.0.0” “ethereum-waffle@^3.2.0” “ethers@^5.0.0”
4. This will create it successfully After installing the hardhat project, we can then use npx (npm subcommand) to run and test npx hardhat . The following picture will pop up to prove success.
5. During the period, you will be prompted to install some plug-ins and install them.
6. The available command npx hardhat --help 7. Compile the contract npx hardhat compile
8. Next, rewrite a small token contract
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract Token {
string public name='my token';
string public symbol = 'Mtn';
uint256 public total = 100000;
address public owner;
mapping(address =>uint) balances;
constructor() {
owner = msg.sender;
balances[msg.sender] =total;
}
function tranfer(address to,uint amount) external{
balances[msg.sender] -=amount;
balances[to] +=amount;
}
function getamount(address account) view external returns(uint a){
a = balances[account];
}
}
9. After compilation, write the test script:
const {
expect } = require("chai");
const {
ethers } = require("hardhat");
describe("Token", function () {
let Token, token, owner,address
beforeEach(async ()=>{
Token = await ethers.getContractFactory('Token');
token = await Token.deploy();//部署
[owner,address,] = await ethers.getSigners();
})
describe('test',()=>{
it('所有者', async ()=> {
expect(await token.owner()).to.equal(owner.address);
})
})
});
10. Run the command to test: npx hardhat test
Note: The following error may be reported when running for the first time: Error: Cannot find module 'chai' Solution: npm install
–save-dev chai
The test runs successfully as shown below: