RareSkills Solidity Interview Question #17 Answered: What is the check-effects pattern?
This series will provide answers to the list of Solidity interview questions that were published by RareSkills..
Question #17 (Easy): What is the check-effects pattern?
Answer: The check-effects pattern (also known as check-effects-interactions) is a Solidity smart contract design framework that defines the order of operations within a function. The check is the first operation, where the method validates the parameters and/or state to ensure that the passed in data is acceptable and the contract is in the correct state to execute the function. Then, the effects operation, where the core functionality of the method follows and the contract state can be updated.
Demonstration:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
contract ChecksEffectsInteractions {
mapping(address => uint) balances;
function deposit() public payable {
balances[msg.sender] = msg.value;
}
function withdraw(uint amount) public {
// Check
require(balances[msg.sender] >= amount);
// Effects
balances[msg.sender] -= amount;
// Interactions
(bool sent, bytes memory data) = msg.sender.call{value: amount}("");
}
}
The interactions operation, following effects, in the check-effects-interactions pattern is an important security measure for defending against certain types of attacks, especially reentrancy. In this phase, the contract interacts with external contracts or addresses, such as transferring Ether or calling external functions.
The purpose of the pattern is to prevent external contracts from taking control of the execution flow before the original contract’s state is fully updated.
Connect with me:
- Github: https://github.com/FaybianB
- LinkedIn: https://www.linkedin.com/in/faybianbyrd/
Previous articles:
- Question #7 (Easy): What are the challenges of creating a random number on the blockchain?
- Question #8 (Easy): What is the difference between a Dutch Auction and an English Auction?
- Question #9 (Easy): What is the difference between transfer and transferFrom in ERC20?
- Question #10 (Easy): Which is better to use for an address allowlist: a mapping or an array? Why?
- Question 11 (Easy): Why shouldn’t tx.origin be used for authentication?
- Question #12 (Easy): What hash function does Ethereum primarily use?
- Question #13 (Easy): How much is 1 gwei of Ether?
- Question #14 (Easy): How much is 1 wei of Ether?
- Question #15 (Easy): What is the difference between assert and require?
- Question #16 (Easy): What is a flash loan?
Disclosure: Some content may have been generated with the help of artificial intelligence.