Files
nexus/wiki/concepts/Checks-Effects-Interactions.md
2026-04-21 00:02:55 +08:00

42 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Checks-Effects-Interactions"
type: concept
tags: [smart-contract, pattern, security]
sources: [blockchain-security-auditor]
last_updated: 2026-04-20
---
## Definition
Checks-Effects-Interactions检查-效果-交互)是一种智能合约安全设计模式,通过在执行外部调用前完成所有状态更新来防止重入攻击。
## Pattern
```solidity
function withdraw() external nonReentrant {
// 1. CHECKS: 验证条件
uint256 amount = balances[msg.sender];
require(amount > 0, "No balance");
// 2. EFFECTS: 更新状态
balances[msg.sender] = 0;
// 3. INTERACTIONS: 执行外部调用
(bool success,) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
```
## Why It Works
1. 状态在外部调用前已更新
2. 攻击者重入时检查失败
3. 即使外部调用失败,状态也不会不一致
## Limitations
- 复杂业务逻辑可能无法严格遵循
- 需要配合 ReentrancyGuard 作为额外防护
- 异步操作(如 event emission应在交互后执行
## Connections
- [[Reentrancy]] ← prevents ← [[Checks-Effects-Interactions]]
- [[Smart Contract Pattern]] ← is_type_of ← [[Checks-Effects-Interactions]]