The Ethereum Virtual Machine (EVM) revolutionized decentralized applications by introducing Turing-complete smart contracts. However, the immutable nature of blockchain code means that security vulnerabilities can have catastrophic consequences. Once a contract is deployed, bugs cannot be "hotfixed" in the traditional sense, making rigorous security auditing paramount.

In this article, we'll explore some of the most prominent smart contract vulnerabilities in Solidity, how they work, and how to prevent them.


1. Reentrancy Attacks

The Reentrancy attack is perhaps the most infamous smart contract vulnerability, brought to the spotlight by the 2016 DAO hack which resulted in the loss of millions of dollars.

How it Works A reentrancy attack occurs when a smart contract makes an external call to an untrusted contract. If the untrusted contract contains a malicious fallback function, it can recursively call back into the original contract before the initial execution is complete. This allows the attacker to repeatedly execute a specific function (like withdrawing funds) before the contract's state (like the user's balance) is updated.

Prevention

  • Checks-Effects-Interactions Pattern: Always update the state (e.g., deducting a balance) before making an external call.
  • Reentrancy Guards: Use a mutex lock, such as OpenZeppelin's nonReentrant modifier, to prevent a function from being called repeatedly within the same transaction.

2. Integer Overflow and Underflow

Prior to Solidity version 0.8.0, arithmetic operations did not inherently check for overflows or underflows.

How it Works If an unsigned integer is set to 255 and incremented by 1, it overflows back to 0. Attackers could exploit this to bypass authorization checks or mint infinite tokens if business logic relied on unchecked arithmetic.

Prevention

  • Solidity 0.8.0+: Upgrade your compiler. Modern Solidity versions have built-in overflow and underflow checks that will revert the transaction if an error occurs.
  • SafeMath: If you must use older compiler versions, always use a library like OpenZeppelin's SafeMath.