๐ก๏ธ 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! ๐ฐโจ
