先从基础开始,这里是一个适合新手的智能合约模板(合约文件 `LearningPath.sol`):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract LearningPath {
// 状态变量存储在区块链上
string public greeting = "Hello Blockchain!";
// 基础函数示例
function setGreeting(string memory _newGreeting) public {
greeting = _newGreeting;
}
// view函数不消耗gas
function greet() public view returns (string memory) {
return greeting;
}
// 待实现的功能区域
// ...(后续添加更多功能)
}
将使用示例合约、该合约的测试以及用于部署它的Hardhat Ignition模块来探索创建Hardhat项目的基础知识。
先初始化 Hardhat 项目。让我们先完成项目初始化:
# 在项目根目录执行
npx hardhat init
$ npx hardhat init
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
888 888 "88b 888P" d88" 888 888 "88b "88b 888
888 888 .d888888 888 888 888 888 888 .d888888 888
888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.
888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888
👷 Welcome to Hardhat v2.22.19 👷
? What do you want to do? …
❯ Create a JavaScript project
Create a TypeScript project
Create a TypeScript project (with Viem)
Create an empty hardhat.config.js
Quit
初始化过程会提示您选择配置模板,建议选择 JavaScript 或 TypeScript 模板。初始化完成后,目录结构会包含以下关键文件:
contracts/
scripts/
test/
hardhat.config.js
完成初始化后,您原来的合约文件 `LearningPath.sol` 需要移动到 contracts/ 目录下,
move LearningPath.sol contracts/LearningPath.sol
之后可以执行:
# 编译合约(确保在项目根目录)
npx hardhat compile
# 启动本地节点(单独开新的终端窗口)
npx hardhat node
需要特别注意:
1. 所有合约文件应存放在 contracts/ 目录
2. 确保执行命令时在包含 hardhat.config.js 的目录
3. 如果使用 Windows 系统,路径分隔符建议统一使用正斜杠 /
验证是否初始化成功:
# 执行后会显示可用的Hardhat命令
npx hardhat
功能详解(结合法律科技场景)
1. contracts/
- 存放所有.sol智能合约文件
- 典型应用:电子合同存证、数字身份验证、仲裁条款自动化执行
- 示例:可创建 LegalDocument.sol 实现合同哈希值上链存证
2.scripts/
- 部署脚本示例(以LearningPath合约为例):
async function main() {
const Contract = await ethers.getContractFactory("LearningPath");
const contract = await Contract.de