Skip to content

Commit addcaf9

Browse files
committed
Add study notes for 2025-08-16
1 parent f0f0ee9 commit addcaf9

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

snaildarter.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,84 @@ timezone: UTC+8
1515
## Notes
1616

1717
<!-- Content_START -->
18+
# 2025-08-16
19+
20+
### 快速上手:Hardhat 中使用 Viem
21+
22+
1. 快速开始
23+
24+
- 新项目:创建时选“create a TypeScript project (with Viem)”
25+
- 已有项目:安装`@nomicfoundation/hardhat-viem`,添加到配置(与 ethers 兼容)
26+
27+
2. 核心操作(附示例)
28+
29+
- 客户端交互:
30+
31+
1. 新建`scripts/clients.ts`,写入代码(查余额、转账):
32+
33+
```typescript
34+
import { parseEther, formatEther } from 'viem';
35+
import hre from 'hardhat';
36+
37+
async function main() {
38+
const [bobWallet, aliceWallet] = await hre.viem.getWalletClients();
39+
const publicClient = await hre.viem.getPublicClient();
40+
41+
// 查Bob余额
42+
const bobBalance = await publicClient.getBalance({
43+
address: bobWallet.account.address,
44+
});
45+
console.log(`Bob余额:${formatEther(bobBalance)} ETH`);
46+
47+
// Bob转1 ETH给Alice
48+
const hash = await bobWallet.sendTransaction({
49+
to: aliceWallet.account.address,
50+
value: parseEther('1'),
51+
});
52+
await publicClient.waitForTransactionReceipt({ hash });
53+
}
54+
main()
55+
.then(() => process.exit())
56+
.catch(console.error);
57+
```
58+
59+
2. 运行:`npx hardhat run scripts/clients.ts`
60+
61+
- 合约操作:
62+
63+
1. 新建`contracts/MyToken.sol`写合约(示例略,含`increaseSupply`等方法),编译:`npx hardhat compile`
64+
2. 新建`scripts/contracts.ts`部署并调用:
65+
66+
```typescript
67+
import hre from 'hardhat';
68+
69+
async function main() {
70+
// 部署合约(初始供应量100万)
71+
const myToken = await hre.viem.deployContract('MyToken', [
72+
1_000_000n,
73+
]);
74+
console.log('初始供应量:', await myToken.read.getCurrentSupply());
75+
76+
// 增加供应量50万
77+
const hash = await myToken.write.increaseSupply([500_000n]);
78+
await hre.viem.getPublicClient().waitForTransactionReceipt({ hash });
79+
console.log('新供应量:', await myToken.read.getCurrentSupply());
80+
}
81+
main()
82+
.then(() => process.exit())
83+
.catch(console.error);
84+
```
85+
86+
3. 运行:`npx hardhat run scripts/contracts.ts`
87+
88+
- 测试:
89+
1. 新建`test/my-token.ts`写用例(验证供应量增减、无效操作回滚),示例略
90+
2. 运行:`npx hardhat test`
91+
92+
3. 版本管理
93+
- 稳定优先:固定`viem``hardhat-viem`版本(去`package.json``^`
94+
- 功能优先:不固定版本,接受偶尔类型错误
95+
1896
# 2025-08-15
1997

2098
### 命令行短命令

0 commit comments

Comments
 (0)