수정자와 검사-효과-상호 작용 패턴
함수 수정자로 사전 조건을 깔끔하게 강제하고 검사-효과-상호 작용 패턴을 적용해 더 안전한 컨트랙트를 작성합니다.
수정자와 검사-효과-상호 작용 패턴은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Are Modifiers?
A modifier is reusable code that runs before (or around) a function body. It is ideal for enforcing preconditions like access control without repeating the same checks everywhere.
Declaring a Modifier
The special _; placeholder marks where the function body executes. Code before it runs first; code after runs when the function returns.
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}Applying a Modifier
Attach a modifier to a function declaration. The check runs automatically on every call, keeping the function body focused on logic.
function withdraw() public onlyOwner {
payable(owner).transfer(address(this).balance);
}Modifiers with Parameters
Modifiers can take arguments, making them flexible for validating dynamic conditions such as minimum values.
modifier costs(uint price) {
require(msg.value >= price, "Not enough");
_;
}Stacking Multiple Modifiers
You can apply several modifiers to one function; they run left to right. Keep them small and single-purpose so combinations stay predictable.
function buy() public payable onlyWhenOpen costs(1 ether) {
// ...
}The Reentrancy Danger
When a contract calls out to an external address, that address can call back into your contract before the first call finishes. This reentrancy can drain funds if state is updated too late.
Checks-Effects-Interactions
The checks-effects-interactions pattern orders your function in three phases: validate inputs (checks), update state (effects), then call external contracts (interactions). External calls come last.
A Vulnerable Withdraw
This sends ETH before zeroing the balance, leaving a reentrancy window.
// VULNERABLE
function withdraw() public {
uint amt = balances[msg.sender];
payable(msg.sender).call{value: amt}("");
balances[msg.sender] = 0; // too late!
}The Safe Version
Update state before the external call so a reentrant call sees a zero balance.
// SAFE
function withdraw() public {
uint amt = balances[msg.sender];
balances[msg.sender] = 0; // effects first
payable(msg.sender).call{value: amt}(""); // interaction last
}Reentrancy Guards
For extra safety, add a reentrancy guard modifier that sets a lock flag during execution, rejecting nested calls. Libraries like OpenZeppelin provide nonReentrant.
Combining the Patterns
Use modifiers for the checks phase (access and validation), structure the body as effects-then-interactions, and add a guard on functions that move value. Together they form a strong defensive baseline.
Quick Check
Check your knowledge of safe contract patterns.
Recap
You learned defensive Solidity patterns:
- Modifiers centralize preconditions like access control
- They can take parameters and be stacked
- Checks-effects-interactions orders functions to prevent reentrancy
- Add a reentrancy guard on value-moving functions
These patterns are foundational to writing secure contracts.
자주 묻는 질문
“수정자와 검사-효과-상호 작용 패턴” 강의는 무료인가요?
네 — “수정자와 검사-효과-상호 작용 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“수정자와 검사-효과-상호 작용 패턴”에서 뭘 배우나요?
함수 수정자로 사전 조건을 깔끔하게 강제하고 검사-효과-상호 작용 패턴을 적용해 더 안전한 컨트랙트를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“수정자와 검사-효과-상호 작용 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 상속과 인터페이스
- 라이브러리와 추상 계약
- Revert/Require를 활용한 오류 처리
- 수정자와 검사-효과-상호 작용 패턴