In Web2 development, a bug usually means a broken layout or a transient 500 error solved by a rapid hotfix. In Web3, a single line of vulnerable code can irreversibly drain a $10M liquidity pool within seconds.
The core promise of Ethereum—immutability—is also its sharpest double-edged sword. Once your smart contract is deployed to the mainnet, your mistakes are permanent unless you have built-in upgradeability, and even then, exploiters race against you to drain funds.
If you are a junior Solidity developer transitioning into the smart contract security mindset, you must shift from asking “Does this feature work?” to asking “How can an adversary break this?”
Here are five of the most common and costly mistakes junior Solidity developers make, along with the precise patterns to mistake-proof your code.
1. Falling into the Reentrancy Trap (Ignoring the CEI Pattern)
Reentrancy remains the most infamous attack vector in smart contract history (the 2016 DAO hack being the most prominent example). It occurs when an external contract call hands execution control over to an untrusted external recipient before the calling contract updates its internal state.
The Vulnerable Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract VulnerableVault {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external {
uint256 amount = balances[msg.sender];
require(amount > 0, "No balance");
// FLAW: Sending ETH before zeroing the balance
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
// State update happens too late!
balances[msg.sender] = 0;
}
}
An attacker can invoke withdraw() from a malicious contract whose fallback() or receive() function calls withdraw() again recursively, draining the contract until gas runs out or the contract is empty.
The Fix: Checks-Effects-Interactions (CEI) & Mutex Guards
Always update your state variables before interacting with external contracts or sending ETH. Additionally, use OpenZeppelin’s battle-tested ReentrancyGuard.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract SecureVault is ReentrancyGuard {
mapping(address => uint256) public balances;
function withdraw() external nonReentrant {
// 1. CHECKS
uint256 amount = balances[msg.sender];
require(amount > 0, "No balance");
// 2. EFFECTS (Update internal state first)
balances[msg.sender] = 0;
// 3. INTERACTIONS (External calls last)
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
}
2. Using tx.origin Instead of msg.sender for Authorization
Junior developers often confuse msg.sender (the immediate caller of the function) with tx.origin (the original Externally Owned Account [EOA] that initiated the entire transaction chain). Using tx.origin for authentication makes your contract vulnerable to phishing attacks.
The Vulnerable Code
contract VulnerableWallet {
address public owner;
constructor() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) external {
// FLAW: tx.origin can be spoofed via an intermediate contract
require(tx.origin == owner, "Not owner");
owner = _newOwner;
}
}
If the owner is tricked into executing a malicious transaction on a third-party website, that third-party contract can call VulnerableWallet.transferOwnership(). Because tx.origin is still the owner, the transaction succeeds.
The Fix: Use msg.sender
function transferOwnership(address _newOwner) external {
// SECURE: Ensures the immediate caller is the owner
require(msg.sender == owner, "Not owner");
require(_newOwner != address(0), "Invalid address");
owner = _newOwner;
}
Rule of Thumb: Almost never use tx.origin for authorization. The only valid use-case for tx.origin is typically to prevent other smart contracts from interacting with your function (e.g., require(msg.sender == tx.origin)), though this breaks account abstraction compatibility (ERC-4337).
3. Assuming “Private” Variables Keep Secrets Hidden
A massive conceptual hurdle for Web2 developers entering Web3 is the definition of the private visibility keyword. In Solidity, private only prevents other smart contracts from reading or modifying the variable directly.
Everything on a public blockchain is completely public.
The Vulnerable Code
contract OnChainRaffle {
// FLAW: The seed is completely visible to anyone reading storage slot 0
uint256 private secretSeed;
constructor(uint256 _seed) {
secretSeed = _seed;
}
function guessSecret(uint256 _guess) external view returns (bool) {
return _guess == secretSeed;
}
}
Anyone running an archive node or using standard RPC commands like eth_getStorageAt(contractAddress, 0) can read the exact value stored in that slot, making the “secret” entirely worthless.
The Fix: Commit-Reveal Schemes or Off-Chain Oracles
- Commit-Reveal Schemes: Users submit a cryptographic hash of their choice along with a secret salt (
keccak256(choice + salt)). Once all entries close, participants reveal their data to verify honesty. - Chainlink VRF (Verifiable Random Function): If you need un-biasable randomness, do not generate it on-chain via block variables; use a cryptographic randomness oracle.
- Zero-Knowledge Proofs (ZKPs): If true hidden data is required, compute proofs off-chain and verify the proof on-chain without revealing the inputs.
4. Ignoring Low-Level Call Return Values
Solidity offers several ways to transfer Ether and invoke external contract methods. Junior developers frequently use low-level calls like .call() or .delegatecall() without properly checking their return values, assuming execution reverts if the sub-call fails.
The Vulnerable Code
function payBonus(address payable recipient, uint256 amount) external {
// FLAW: The return value is discarded!
recipient.call{value: amount}("");
// Contract assumes payment succeeded even if it failed
hasReceivedBonus[recipient] = true;
}
If the recipient is a contract that runs out of gas, reverts in its fallback function, or lacks a payable fallback, .call will return false instead of reverting the transaction. Your contract will proceed as if the transfer occurred.
The Fix: Always Validate the Return Value
function payBonus(address payable recipient, uint256 amount) external {
require(!hasReceivedBonus[recipient], "Already received");
hasReceivedBonus[recipient] = true;
// Check the boolean return value
(bool success, ) = recipient.call{value: amount}("");
require(success, "ETH transfer failed");
}
Note: For ERC-20 token transfers, many tokens (like USDT) do not revert on failure and do not conform strictly to the ERC-20 standard interface (returning non-standard booleans). Always use OpenZeppelin’s SafeERC20 library (e.g., safeTransfer and safeTransferFrom) to handle these edge cases gracefully.
5. Gas Guzzling: Reading and Writing Storage Inside Loops
In traditional systems, reading an array variable in a loop takes nanoseconds. In Ethereum’s EVM, reading from and writing to contract storage (SLOAD and SSTORE) are among the most expensive operations.
Repeatedly accessing storage in a loop results in astronomical gas fees for your users and can lead to a Denial of Service (DoS) via Block Gas Limit, permanently breaking your function if the loop grows too large.
The Vulnerable Code
contract GasHeavy {
uint256[] public values;
uint256 public total;
// Inefficient: Repeatedly reading and writing storage
function calculateTotal() external {
total = 0;
// values.length is an SLOAD every single iteration!
for (uint256 i = 0; i < values.length; i++) {
// total is read (SLOAD) and modified (SSTORE) every iteration!
total += values[i];
}
}
}
The Fix: Cache Storage in Memory / Local Variables
Memory reads (MLOAD) and stack operations cost fractional amounts of gas compared to storage operations. Cache array lengths and intermediate calculations in local variables.
contract GasOptimized {
uint256[] public values;
uint256 public total;
function calculateTotal() external {
// Cache storage values in memory/stack
uint256[] memory cachedValues = values;
uint256 len = cachedValues.length;
uint256 localTotal = 0;
for (uint256 i = 0; i < len;) {
localTotal += cachedValues[i];
// Unchecked increment is safe here because i < len ensures no overflow
unchecked { ++i; }
}
// Only ONE SSTORE write at the very end
total = localTotal;
}
}
The Junior Dev Mistake-Proofing Checklist
Writing defensive smart contracts requires tooling and systematic habits, not just careful eyes. Integrate these into your daily workflow:
- Switch to Modern Tooling: Use Foundry over legacy frameworks. Foundry allows you to write tests in native Solidity, perform fuzz testing, and write invariant tests that uncover edge cases humans miss.
- Static Analysis (Linting on Steroids): Always run Slither and Aderyn in your CI/CD pipeline. They immediately flag reentrancy, uninitialized state, and unused variables before you ever hit a testnet.
- Follow the CEI Pattern Religiously: Checks, Effects, Interactions. It costs nothing to rearrange your lines of code, but it saves millions.
- Don’t Reinvent the Wheel: Never write your own custom access control, ERC-20 logic, or cryptographic verification unless strictly necessary. Rely on audited libraries like OpenZeppelin and Solady.