开发工具链
Hardhat、Foundry、OpenZeppelin、Slither。
35 分钟
开发工具链
链上开发除了 Remix,还需要本地编译、测试、部署脚本与静态分析。Hardhat 与 Foundry 是两套主流方案;OpenZeppelin 提供安全合约库,Slither 帮助发现常见漏洞。见 /roadmaps/blockchain。
学习目标
- 用 Hardhat 或 Foundry 初始化项目并运行测试
- 通过 OpenZeppelin 复用经过审计的合约模块
- 了解 Slither 在 CI 中的基本用法
Hardhat 快速开始
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npx hardhat init
// test/Counter.test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Counter", function () {
it("increments", async function () {
const Counter = await ethers.getContractFactory("Counter");
const counter = await Counter.deploy();
await counter.increment();
expect(await counter.count()).to.equal(1n);
});
});
npx hardhat test
npx hardhat node # 本地链
npx hardhat run scripts/deploy.js --network localhost
Foundry 对比
| Hardhat | Foundry | |
|---|---|---|
| 语言 | JavaScript / TypeScript | Solidity 测试 + Rust 工具 |
| 测试速度 | 较快 | 通常更快 |
| 生态插件 | 丰富 | 成长中 |
forge init my-project
forge test
forge script script/Deploy.s.sol --rpc-url $RPC --broadcast
OpenZeppelin
优先 import 官方实现,而非手写 transfer 逻辑:
ERC20、ERC721、Ownable、PausableReentrancyGuard防重入
Slither 静态分析
pip install slither-analyzer
slither .
关注:reentrancy-eth、unchecked-transfer、suicidal 等高危检测项。可接入 GitHub Actions,合并前自动扫描。
练习
- 用 Hardhat 或 Foundry 为 Counter 写至少 2 个测试用例
- 配置
.env存放 RPC URL 与私钥,并加入