I just finished writing an analysis about reentrancy — a security issue that many developers still overlook when building smart contracts.



Simply put, reentrancy occurs when a smart contract is called repeatedly before the initial call completes. Imagine this: ContractA is executing a function, it calls ContractB, and ContractB calls back ContractA before ContractA finishes. That’s the vulnerability an attacker can exploit.

A concrete example: EtherStore has 10 Ether, and ContractB has sent 1 Ether into it. When ContractB calls the withdraw function, it checks if the balance is greater than 0, and if so, sends Ether back. But here’s the dangerous part — updating the balance to zero happens after sending the Ether. Therefore, an attacker can create a fallback function that, upon receiving Ether, calls the withdraw function again. This loop continues until all Ether is drained.

I will outline three ways to prevent reentrancy:

First is using the nonReentrant modifier. This method locks the contract while the function is running, preventing re-entry. Simple but effective for a single function.

Second is applying the Checks-Effects-Interactions pattern. Instead of updating the balance after sending Ether, update it beforehand. This way, even if a reentrant call occurs, the balance is already zero, and the check will fail.

Third is creating a separate GlobalReentrancyGuard contract. This approach uses a shared state variable to control reentrancy across multiple contracts simultaneously. Especially useful when your project involves multiple interacting contracts. Instead of checking within each contract, you centralize the control.

Reentrancy issues are not new, but they remain one of the most common vulnerabilities. I see many developers still not applying these measures consistently. If you’re working with Solidity, make sure you understand this problem thoroughly and implement at least one of these three methods in your project. Smart contract security is not optional; it’s mandatory.
View Original
This page may contain third-party content, which is provided for information purposes only (not representations/warranties) and should not be considered as an endorsement of its views by Gate, nor as financial or professional advice. See Disclaimer for details.
  • Reward
  • Comment
  • Repost
  • Share
Comment
Add a comment
Add a comment
No comments
  • Pin