前提:安装node 版本>12,npm, git等
1.创建文件夹,创建之后用自己熟悉的工具打开,例如:webstorm
2.打开之后运行“npm init -y” ,会在控制台打印:
{
“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.运行npm install --save-dev hardhat,成功之后如下:
注意:报错解决办法:npm install --save-dev “@nomiclabs/hardhat-ethers@^2.0.0” “ethereum-waffle@^3.2.0” “ethers@^5.0.0”
4.这样就成功创建了hardhat项目,接下来我们可以用npx(npm子命令)运行测试 npx hardhat,d出下图证明成功
5.期间提示你安装一些插件,进行安装
6.可用命令npx hardhat --help7.编译合约用npx hardhat compile
8.接下来进行重新编写个小的代币合约
//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.编译后进行编写测试脚本:
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.运行命令进行测试:npx hardhat test
注意:第一次运行可能报以下错误:Error: Cannot find module ‘chai’ 解决办法:npm install
–save-dev chai
运行测试成功如下图:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)