In traditional web development, a bug in your code means deploying a quick patch. In Web3, a single oversight can permanently drain your protocol’s treasury. Here are the five most common traps beginners fall into—and the industry-standard patterns to prevent them.
1. Using transfer() or send() for Ether Transfers
Many introductory tutorials written before 2019 still teach developers to forward native Ether using address.transfer() or address.send(). Beginners naturally adopt these because they seem safe and simple.
The Problem
Both transfer() and send() forward a hardcoded stipend of 2,300 gas. While this was originally intended to prevent reentrancy attacks, the Istanbul hard fork (EIP-1884) changed the gas costs of several opcodes. If the receiving contract does any non-trivial computation in its receive() or fallback() function, or if it is a smart contract wallet (like Gnosis Safe or Argent), the transfer will run out of gas and revert.
How to Avoid It
Use the low-level .call() method with a value payload, paired with a reentrancy guard or strict state updates before the call.
❌ Bad Practice
// Risky: Hardcoded 2300 gas limit will break for smart contract wallets
payable(recipient).transfer(amount);
✅ Recommended Practice
// Correct: Forwards all available gas (or a custom amount) and checks return status
(bool success, ) = payable(recipient).call{value: amount}("");
require(success, "Transfer failed");
2. Violating the Checks-Effects-Interactions (CEI) Pattern
Reentrancy remains the most infamous attack vector in smart contract history (responsible for the 2016 DAO hack). New developers often grasp the concept theoretically, but still make subtle ordering errors in practice.
The Problem
When your contract interacts with an external address (such as sending Ether or calling an external token contract), control is temporarily handed over to that external address. If you update the user’s balance after making the external transfer, the recipient can recursively invoke your withdrawal function before their balance is set to zero.
How to Avoid It
Always structure your functions strictly following the Checks-Effects-Interactions order:
- Checks: Validate conditions (e.g.,
require(balance >= amount)). - Effects: Update your internal state variables (e.g., deduct the user’s balance).
- Interactions: Call other contracts or send native tokens.
Additionally, incorporate OpenZeppelin’s battle-tested ReentrancyGuard on functions that transfer assets.
// Follow Checks-Effects-Interactions:
function withdraw(uint256 amount) external nonReentrant {
// 1. CHECKS
require(balances[msg.sender] >= amount, "Insufficient balance");
// 2. EFFECTS (Update state before external call)
balances[msg.sender] -= amount;
// 3. INTERACTIONS
(bool success, ) = payable(msg.sender).call{value: amount}("");
require(success, "Transfer failed");
}
3. Authenticating with tx.origin Instead of msg.sender
Coming from Web2, developers often equate tx.origin to an “authenticated user session ID” and msg.sender to a “local caller.” This fundamental misunderstanding creates a glaring phishing vulnerability.
The Problem
tx.origin refers to the original Externally Owned Account (EOA) that initiated the transaction chain, whereas msg.sender represents the immediate caller of the current contract. If you use tx.origin for access control, an attacker can trick an authorized user into calling a malicious contract, which in turn calls your contract—bypassing your security check completely.
How to Avoid It
Never use tx.origin for authorization. Always use msg.sender.
❌ Vulnerable to Phishing
function transferOwnership(address newOwner) external {
// Dangerous: If the owner interacts with an attacker's contract,
// tx.origin will still equal owner!
require(tx.origin == owner, "Not owner");
owner = newOwner;
}
✅ Secure Access Control
function transferOwnership(address newOwner) external {
// Safe: Verifies that the immediate caller is the owner
require(msg.sender == owner, "Not owner");
owner = newOwner;
}
4. Writing Unbounded Loops Over Dynamic Storage Arrays
In languages like JavaScript or Python, iterating over a list of items is standard procedure. In Solidity, writing a loop over a dynamic array stored on-chain is a silent time bomb.
The Problem
Ethereum blocks have a strict Gas Limit (currently 30 million gas). Every read and write operation inside a loop consumes gas. If your contract iterates over an array that grows with every new user (e.g., distributing dividends or refunding deposits), the array will eventually grow so large that the gas required to complete the loop exceeds the block gas limit. The transaction will permanently revert, resulting in a Denial of Service (DoS) lockup.
How to Avoid It
- Favor “Pull” over “Push”: Instead of pushing rewards to 10,000 addresses in a single loop, let individual users “pull” (claim) their rewards in separate transactions.
- Use Off-Chain Indexing: Use subgraphs (The Graph) or off-chain indexers to aggregate data, and verify proof on-chain (e.g., using Merkle Trees).
- Implement Pagination: If on-chain iteration is unavoidable, process items in bounded batches using cursor pagination.
5. Mismanaging storage vs. memory and calldata
Solidity provides fine-grained control over where data lives: storage, memory, or calldata. Beginners often default to memory everywhere without realizing the cost implications, or unintentionally write variables to expensive contract storage.
The Problem
storage operations (specifically SSTORE and SLOAD) are the most expensive opcodes in the EVM. If you repeatedly read or write to a storage variable inside a loop instead of caching it, your users will pay exorbitant gas fees. Similarly, using memory for external function arguments forces Solidity to allocate and copy data from the transaction payload into memory, burning unnecessary gas.
How to Avoid It
- Use
calldatafor read-only external inputs: For arrays, strings, and structs passed intoexternalfunctions, declare them ascalldatainstead ofmemory. This avoids memory allocation and references the raw input directly. - Cache storage variables in local memory: Read a state variable once into a local stack variable before performing repetitive loops or operations.
❌ Wasteful Gas Usage
uint256 public totalScore;
// Copying string/array to memory burns gas; reading totalScore repeatedly burns gas
function updateScores(uint256[] memory scores) external {
for (uint256 i = 0; i < scores.length; i++) {
totalScore += scores[i]; // Repeated SSTORE & SLOAD
}
}
✅ Optimized Gas Usage
uint256 public totalScore;
// calldata avoids copying; local variable saves on SSTORE
function updateScores(uint256[] calldata scores) external {
uint256 tempTotal = totalScore; // Single SLOAD
uint256 len = scores.length; // Cached length
for (uint256 i = 0; i < len; i++) {
tempTotal += scores[i];
}
totalScore = tempTotal; // Single SSTORE
}