🛡️ Contract Security: Attacks and Auditing
The Castle and the Thieves
Imagine you built an amazing castle (your smart contract) where people store their gold (cryptocurrency). But thieves are always watching, looking for weak spots. Today, we’ll learn how to protect your castle from the sneakiest thieves in Web3!
🔐 Checks-Effects-Interactions (The Safe Order Rule)
What Is It?
Think of a vending machine. When you buy a snack:
- CHECK - Machine checks if you put in enough money
- EFFECT - Machine marks the snack as “sold” internally
- INTERACTION - Machine drops the snack to you
If the machine gave you the snack FIRST, a sneaky person could grab it and run before paying! That’s what happens in smart contracts when we do things in the wrong order.
The Problem: Reentrancy Attack
// ❌ BAD - Wrong order!
function withdraw() {
uint amount = balances[msg.sender];
msg.sender.call{value: amount}("");
balances[msg.sender] = 0;
}
Here, we send money BEFORE setting balance to zero. An attacker can call withdraw again and again before their balance updates!
The Solution
// ✅ GOOD - Right order!
function withdraw() {
uint amount = balances[msg.sender];
balances[msg.sender] = 0; // Effect first!
msg.sender.call{value: amount}(""); // Then interact
}
Simple Rule: Always update your records BEFORE sending money out!
🏃 Front-Running Attacks
What Is It?
Imagine you’re in line at an ice cream shop. You say “I want the last chocolate cone!” But someone behind you has a special power to JUMP ahead in line and grab it first!
In blockchain, transactions wait in a public waiting room (mempool). Attackers can see your transaction and pay more gas to get ahead of you.
Real Example
You: "I'll buy Token X for $100"
↓ (visible in mempool)
Attacker sees this!
↓
Attacker: "I'll buy Token X for $100 first!" (pays more gas)
↓
Price goes up
↓
Your transaction buys at higher price 😢
How To Protect Yourself
- Use commit-reveal schemes - Hide your intention first
- Set slippage limits - “I won’t pay more than $105”
- Use private transactions - Some services hide your transaction
🥪 Sandwich Attacks
What Is It?
Remember front-running? A sandwich attack is even sneakier! The attacker puts TWO transactions around yours - like bread around your filling!
How It Works
🍞 Attacker buys BEFORE you (price goes up)
🥓 YOUR transaction (you buy at higher price)
🍞 Attacker sells AFTER you (they profit!)
It’s like someone buying all the cookies before you, then selling them to you at a higher price, then selling the rest after!
Real Example
Step 1: You want to swap 10 ETH → Tokens
Step 2: Attacker sees this in mempool
Step 3: Attacker buys tokens (price ↑)
Step 4: Your swap happens (bad price)
Step 5: Attacker sells tokens (profit!)
Protection Tips
- Use DEXs with MEV protection
- Set tight slippage (like 0.5%)
- Use private transaction services
⚡ Flash Loan Attacks
What Is It?
Imagine you could borrow a BILLION dollars, but you MUST return it in the same second. Sounds impossible? In blockchain, it’s real!
Flash loans let you borrow huge amounts with zero collateral - but you must repay in the same transaction.
How Attackers Use This
graph TD A["Borrow $10 Million"] --> B["Manipulate a market"] B --> C["Exploit vulnerable contract"] C --> D["Make profit"] D --> E["Repay $10 Million"] E --> F["Keep the profit! 💰"]
Famous Example
1. Borrow 10,000 ETH (flash loan)
2. Dump ETH on Exchange A (price drops)
3. Use low price to exploit Contract X
4. Profit from price difference
5. Repay 10,000 ETH
6. Attacker keeps millions in profit!
Why It’s Dangerous
- Attackers need ZERO money to start
- All happens in ONE transaction
- Can manipulate prices temporarily
🔮 Oracle Manipulation
What Is It?
Oracles are like messengers that tell your smart contract about the outside world. “Hey, 1 ETH = $2000 right now!”
But what if someone tricks the messenger?
The Problem
Normal: Oracle says 1 ETH = $2000
Attack: Manipulated to say 1 ETH = $200
If your contract trusts this bad price...
Attacker borrows way more than they should!
Real Example
// ❌ Dangerous - Single price source
function getPrice() {
return exchange.getSpotPrice();
}
// ✅ Safer - Multiple sources + TWAP
function getPrice() {
return oracle.getTWAP(1 hour);
}
TWAP = Time-Weighted Average Price. It averages prices over time, making manipulation much harder!
Protection Methods
| Method | How It Helps |
|---|---|
| Multiple oracles | Hard to fool them all |
| TWAP | Average over time |
| Chainlink | Decentralized price feeds |
| Circuit breakers | Stop if price seems crazy |
🔍 Smart Contract Auditing
What Is It?
Before you drive a car, mechanics check if it’s safe. Before launching a smart contract, auditors check if it’s secure!
The Audit Process
graph TD A["Submit Code"] --> B["Manual Review"] B --> C["Automated Scanning"] C --> D["Write Report"] D --> E["Fix Issues"] E --> F["Final Check"] F --> G["Ready to Launch! 🚀"]
What Auditors Look For
- Logic bugs - Does 2+2 really equal 4?
- Access control - Who can do what?
- Reentrancy - Can attackers call back?
- Integer overflow - Do numbers break?
- Gas issues - Will it cost too much?
Top Audit Firms
- OpenZeppelin
- Trail of Bits
- Consensys Diligence
- Certik
Remember
An audit is NOT a guarantee! It’s like a health checkup - helpful but not perfect.
🔧 Static Analysis Tools
What Is It?
Static analysis tools are like spell-checkers for code. They automatically scan for common mistakes without running the code.
Popular Tools
| Tool | What It Does |
|---|---|
| Slither | Finds vulnerabilities fast |
| Mythril | Deep security analysis |
| Securify | Pattern-based detection |
| Echidna | Fuzzing (random testing) |
Slither Example
# Running Slither
slither ./MyContract.sol
# Output:
# ⚠️ Reentrancy vulnerability in withdraw()
# ⚠️ Unused variable: oldBalance
# ✅ No integer overflow detected
What They Catch
- ✅ Reentrancy patterns
- ✅ Unchecked returns
- ✅ Dangerous functions
- ✅ Gas optimization issues
- ✅ Style violations
Limitations
- ❌ Can’t find all bugs (false negatives)
- ❌ Sometimes wrong (false positives)
- ❌ Can’t understand business logic
Best Practice: Use BOTH automated tools AND human auditors!
🎯 Quick Summary
| Attack | What Happens | Protection |
|---|---|---|
| Reentrancy | Attacker calls back repeatedly | Checks-Effects-Interactions |
| Front-running | Attacker jumps ahead | Commit-reveal, private tx |
| Sandwich | Two txs around yours | Slippage limits |
| Flash Loan | Borrow millions instantly | Use TWAP, multiple oracles |
| Oracle Manipulation | Fake price data | Decentralized oracles |
💪 You’ve Got This!
Security isn’t scary - it’s just careful thinking! Remember:
- Check everything before acting
- Update your records before sending money
- Use multiple price sources
- Audit your code before launching
- Scan with automated tools
Your castle can be impenetrable. Now go build it right! 🏰✨
