本文主要是介绍hardhat学习笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
hardhat学习笔记会不定时填充内容。
初始化项目
yarn init
安装hardhat依赖
yarn add --dev hardhat
初始化 Hardhat
yarn hardhat
代码格式化
yarn add --dev prettier prettier-plugin-solidity
项目中增加.prettierrc
与 .prettierignore
配置文件统一格式(根据项目自行配制即可)
//.prettierrc
{"$schema": "https://json.schemastore.org/prettierrc","semi": false,"tabWidth": 2,"singleQuote": true,"printWidth": 100,"trailingComma": "none"
}
//.prettierrc
node_modules
package.json
img
artifacts
cache
coverage
.env
.*
README.md
coverage.json
编译合约
yarn hardhat compile
设置环境按量
安装依赖
yarn add --dev dotenv
在 .env
文件中,我们可以设置环境变量
RINKEBY_RPC_URL=https://rinkeby.infura.io/v3/key
RINKEBY_PRIVATE_KEY=0xkey
ETHERSCAN_API_KEY=key
COINMARKETCAP_API_KEY=key
hardhat.config.js
读取环境变量
const INFURA_API_KEY = process.env.INFURA_API_KEY || "";
const RINKEBY_PRIVATE_KEY = process.env.RINKEBY_PRIVATE_KEY || "";
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY || "key";
const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY || "key";
配置网络环境
现配置本地网络环境,测试账号还没申请下来
运行 yarn hardhat node
命令,启动一个本地可持续的网络
yarn hardhat node
配置 hardhat.config.js
const config: HardhatUserConfig = {solidity: '0.8.24',defaultNetwork: 'hardhat',networks: {localhost: {url: 'http://localhost:8545'}// rinkeby: {// url: `https://rinkeby.infura.io/v3/${INFURA_API_KEY}`,// accounts: [`0x${RINKEBY_PRIVATE_KEY}`],// },}
}
部署脚本及关联合约
两个例子,一个hardhat自带的,一个网上找的,分别记录下。
deploy.ts
import { ethers } from 'hardhat'async function main() {const currentTimestampInSeconds = Math.round(Date.now() / 1000)const unlockTime = currentTimestampInSeconds + 60const lockedAmount = ethers.parseEther('0.001')const lock = await ethers.deployContract('Lock', [unlockTime], {value: lockedAmount})await lock.waitForDeployment()console.log(`Lock with ${ethers.formatEther(lockedAmount)}ETH and unlock timestamp ${unlockTime} deployed to ${lock.target}`)//简单合约 --------------------------------//获取合约工厂const simpleStorageFactory = await ethers.getContractFactory('SimpleStorage')//部署const simpleContract = await simpleStorageFactory.deploy()//等待部署完成await simpleContract.waitForDeployment()//输出合约地址simpleContract.getAddress().then((address) => console.log('SimpleStorage deployed to:address:', address))//获取当前值const value = await simpleContract.retrieve()console.log('SimpleStorage value:', value.toString())//设置值await simpleContract.store(13)//获取当前值const newValue = await simpleContract.retrieve()console.log('SimpleStorage new value:', newValue.toString())
}// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().then(() => process.exit(0)).catch((error) => {console.error(error)process.exitCode = 1})
Lock合约(Lock.sol)
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;// 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);}
}
SimpleStorage合约(SimpleStorage.sol)
// SPDX-License-Identifier: UNKNOWN (this is a comment)pragma solidity ^0.8.24;contract SimpleStorage {uint256 favoriteNumber;bool favoriteBool;struct People {uint256 favoriteNumber;string name;}People public person = People({favoriteNumber: 2, name: 'Patrick'});People[] public people;mapping(string => uint256) public nameToFavoriteNumber;///存储值,是一个非view函数,会改变合约的状态function store(uint256 _favoriteNumber) public {favoriteNumber = _favoriteNumber;}///返回值,是一个view函数,不会改变合约的状态function retrieve() public view returns (uint256) {return favoriteNumber;}///增加人员function addPerson(string memory _name, uint256 _favoriteNumber) public {people.push(People(_favoriteNumber, _name));nameToFavoriteNumber[_name] = _favoriteNumber;}///返回人员function getPerson() public view returns (People[] memory) {return people;}
}
运行脚本
yarn hardhat run scripts/deploy.ts
这篇关于hardhat学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!