Update nexus wiki content

This commit is contained in:
2026-05-03 05:42:06 +08:00
parent 90f3811b83
commit 111bc65b7b
707 changed files with 32306 additions and 7289 deletions

View File

@@ -0,0 +1,39 @@
---
title: "ReentrancyGuard"
type: concept
tags: []
last_updated: 2026-05-01
---
## Definition
ReentrancyGuard 是 OpenZeppelin 提供的修饰器modifier通过在函数入口设置 mutex 锁防止合约函数在执行过程中被递归调用re-entrancy从而避免重入攻击。
## Implementation
```solidity
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract Vault is ReentrancyGuard {
function withdraw() external nonReentrant {
// ...
msg.sender.call{value: amount}("");
// 递归调用此函数会被 revert
}
}
```
## Limitations
- **不是万能药**ReentrancyGuard 防止同一合约被递归调用,但不防止**跨合约**重入(跨合约重入需配合 ChecksEffectsInteractions 原则)
- **Gas 成本**:每次 nonReentrant 检查约消耗 200 gas
- **OpenZeppelin v5 改进**v5 版本优化了检查逻辑,降低了 gas 成本
## 与 ChecksEffectsInteractions 的关系
两者互补:
- ChecksEffectsInteractions 是**设计原则**——正确顺序的结构化思维
- ReentrancyGuard 是**工程手段**——即使违反 CEI 也能防止单合约重入
最佳实践:**同时使用两者**Guard 作为最后防线CEI 作为代码结构规范。
## Sources
- [[engineering-solidity-smart-contract-engineer]]
- [[The-DAO]]
- [[OpenZeppelin]]