charlieviettq/awesome-agent-skill / .claude/skills/algo-blockchain-smart-contract
"algo-blockchain-smart-contract"
Verified"Design and implement smart contracts as self-executing programmatic agreements on blockchain. Use this skill when the user needs to build automated on-chain logic, evaluate smart contract security, or design tokenized business rules — even if they say 'smart contract development', 'automated agreement', or 'on-chain logic'.".
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 4.7 KB |
| examples/sample_scenario.md | markdown | 5.7 KB |
| references/gas-optimization.md | markdown | 11.3 KB |
| references/vulnerability-patterns.md | markdown | 17.0 KB |
references/vulnerability-patterns.md
View on GitHub# Vulnerability Patterns
## The Core Mental Model: Attacker Controls Execution Context
Every vulnerability falls into one of three root causes:
1. **State manipulation** — attacker changes contract state before expected reads/writes
2. **Trust violations** — contract trusts an address or value it shouldn't
3. **Resource exhaustion** — attacker makes a function unusable or prohibitively expensive
---
## V-1: Reentrancy
**Severity: Critical** — caused the DAO hack ($60M, 2016)
### How It Works
A malicious contract's fallback function calls back into the victim before state is updated.
```
Attacker calls withdraw()
→ victim sends ETH via call{value: amt}("")
→ attacker's receive() fires
→ attacker calls withdraw() AGAIN
→ balance still shows old value (state not updated yet)
→ ETH sent again
→ repeat until drained
```
### Vulnerable Code
```solidity
// VULNERABLE: state update happens AFTER external call
mapping(address => uint256) public balances;
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount, "Insufficient balance");
// External call BEFORE state update — reentrancy window here
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
balances[msg.sender] -= amount; // Too late: attacker re-entered above
}
```
### Fixed Code (Checks-Effects-Interactions)
```solidity
// SAFE: state update happens BEFORE external call
function withdraw(uint256 amount) external nonReentrant {
require(balances[msg.sender] >= amount, "Insufficient balance");
// EFFECT: update state first
balances[msg.sender] -= amount;
// INTERACTION: external call last
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
```
### ReentrancyGuard Pattern
```solidity
// OpenZeppelin's implementation — use this rather than rolling your own
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status = _NOT_ENTERED;
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
```
### Cross-Function Reentrancy (Less Obvious)
Even with CEI, reentrancy across multiple functions is possible:
```solidity
// VULNERABLE: two functions share state; attacker re-enters transfer() from withdraw()
function withdraw() external {
uint256 amount = balances[msg.sender];
(bool success, ) = msg.sender.call{value: amount}(""); // attacker re-enters transfer()
balances[msg.sender] = 0; // never reached
}
function transfer(address to, uint256 amount) external {
require(balances[msg.sender] >= amount);
balances[to] += amount;
balances[msg.sender] -= amount;
}
```
**Fix**: Use `nonReentrant` on all mutually-trusting functions, or use the mutex consistently.
### Detection Checklist
| Check | Red Flag |
|-------|----------|
| External calls before state updates | `call()` / `transfer()` appears before storage writes |
| Fallback/receive can call back | Malicious contract's `receive()` could loop |
| Missing ReentrancyGuard | No mutex on ETH-sending functions |
| Read-only reentrancy | View functions return stale state during re-entry (affects other protocols) |
---
## V-2: Integer Overflow / Underflow
**Severity: High** — mitigated by Solidity 0.8+, still critical in older contracts and assembly
### Solidity Version Decision Table
| Version | Overflow Behavior | Fix Required |
|---------|------------------|--------------|
| < 0.8.0 | Wraps silently | Use SafeMath library |
| ≥ 0.8.0 | Reverts automatically | Safe by default |
| Any version, `unchecked {}` block | Wraps silently | Manual bounds check |
| Inline assembly (`assembly {}`) | Wraps silently | Manual bounds check always |
### Classic Underflow (Pre-0.8)
```solidity
// VULNERABLE: uint256 underflow wraps to max value
function burn(uint256 amount) external {
balances[msg.sender] -= amount; // if amount > balance: wraps to 2^256 - (amount - balance)
totalSupply -= amount;
}
```
### Dangerous Use of `unchecked` (Post-0.8)
```solidity
// WRONG: using unchecked for gas savings without verifying safety
function decrementCounter(uint256 by) external {
unchecked {
counter -= by; // developer intended "never underflows" but didn't prove it
}
}
// RIGHT: prove safety before using unchecked
function decrementCounter(uint256 by) external {
require(counter >= by, "Underflow");
unchecked {
counter -= by; // safe: require() above guarantees no underflow
}
}
```
### Multiplication Overflow Pattern
```solidity
// Both values look safe individually, but product overflows
uint256 price = 1e18; // 10^18
uint256 quantity = 1e20; // 10^20
uint256 total = price * quantity; // 10^38 > 2^256 (~1.15 × 10^77) — actually fits here
// but e.g. price=2^128, quantity=2^128 → overflow
```
**Rule**: Any multiplication of two `uint256` values where either could exceed `2^128` requires overflow checking.
---
## V-3: Access Control Failures
**Severity: Critical** — Parity multisig freeze ($150M, 2017) was an access control bug
### Missing `onlyOwner`
```solidity
// VULNERABLE: anyone can call this
function setOwner(address newOwner) external {
owner = newOwner;
}
// SAFE
function setOwner(address newOwner) external onlyOwner {
owner = newOwner;
}
```
### `tx.origin` vs `msg.sender`
```solidity
// VULNERABLE: tx.origin is the original EOA, not the immediate caller
// A malicious contract can trick the user into calling it, then call this function
modifier onlyOwner() {
require(tx.origin == owner, "Not owner"); // Wrong
_;
}
// SAFE: always use msg.sender for authentication
modifier onlyOwner() {
require(msg.sender == owner, "Not owner"); // Correct
_;
}
```
**`tx.origin` use is only appropriate for**: detecting if the caller is an EOA (not a contract), and even then it's a weak check.
### Uninitialized Storage Proxy Bug (Parity Pattern)
```solidity
// Library contract with no initialization guard
contract WalletLibrary {
address public owner;
// VULNERABLE: initWallet has no "already initialized" check
function initWallet(address _owner) public {
owner = _owner; // Attacker calls this on the library directly to seize ownership
}
function kill() public onlyOwner {
selfdestruct(payable(owner)); // Attacker then kills the library, freezing all proxies
}
}
```
**Fix**: Always check initialization state and use constructor-based initialization when possible.
### Role-Based Access Control Decision Framework
```
Q: Is this function called by one specific address?
→ Use: address owner + onlyOwner modifier
Q: Is this function called by one of several trusted addresses?
→ Use: mapping(address => bool) hasRole + OpenZeppelin AccessControl
Q: Does this require M-of-N signers to act?
→ Use: Gnosis Safe multisig or Timelock + Guardian pattern
Q: Should there be a delay before sensitive operations take effect?
→ Use: Timelock (e.g. 48-hour delay for contract upgrades)
```
---
## V-4: Front-Running (MEV)
**Severity: Medium-High** — affects DEXes, NFT mints, auctions
### How Front-Running Works
```
1. User submits tx: buy token at price P, gas = G
2. Miner/searcher sees mempool, inserts own tx: buy at price P, gas = G+1
3. Miner's tx executes first, raises price
4. User's tx executes at worse price (or reverts if slippage limit hit)
```
### Sandwich Attack (Specific to AMMs)
```
Attacker buy → User's swap (price shifts adversely) → Attacker sell
Net: Attacker extracts value equal to ~user's slippage tolerance
```
### Commit-Reveal Pattern (Mitigation)
Used for: auctions, random number generation, blind voting.
```solidity
// Phase 1: Commit (hide the value)
mapping(address => bytes32) public commitments;
function commit(bytes32 hash) external {
commitments[msg.sender] = hash;
// hash = keccak256(abi.encodePacked(bidAmount, secret))
// Attacker sees hash but cannot determine bidAmount
}
// Phase 2: Reveal (after commit period closes)
function reveal(uint256 bidAmount, bytes32 secret) external {
require(
commitments[msg.sender] == keccak256(abi.encodePacked(bidAmount, secret)),
"Hash mismatch"
);
// Process bidAmount now that commit period is over
}
```
### Slippage Protection for AMM Interactions
```solidity
// Always enforce minimum output
function swap(uint256 amountIn, uint256 minAmountOut) external {
uint256 amountOut = _calculateOutput(amountIn);
require(amountOut >= minAmountOut, "Slippage exceeded");
_executeSwap(amountIn, amountOut);
}
// minAmountOut is set by the user off-chain based on acceptable slippage (e.g. 0.5%)
```
### Situations Where Front-Running Is Unavoidable
- Any operation that changes price/state based on pending order (AMMs, lending liquidations)
- Solutions: batch auctions (Gnosis Protocol), private mempools (Flashbots Protect), commit-reveal
---
## V-5: Oracle Manipulation
**Severity: Critical** — Mango Markets exploit ($117M, 2022) used oracle manipulation
### The Attack Pattern
1. Attacker takes large position in a thinly-traded asset
2. Attacker pumps spot price on a low-liquidity DEX
3. Lending protocol reads that DEX as its oracle → inflated collateral value
4. Attacker borrows against inflated collateral → drains protocol
### Spot Price Oracle (Dangerous)
```solidity
// VULNERABLE: single-block spot price is easily manipulated
function getPrice(address token) external view returns (uint256) {
(uint256 reserve0, uint256 reserve1,) = uniswapPair.getReserves();
return reserve1 * 1e18 / reserve0; // Snapshot price — manipulable in same tx
}
```
### TWAP Oracle (Safer)
```solidity
// SAFER: Uniswap V3 TWAP over 30-minute window
function getTWAP(address pool, uint32 secondsAgo) external view returns (uint256) {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
int24 arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));
return TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
// Manipulation cost: must sustain price deviation for full TWAP window
}
```
### Chainlink Integration Requirements
```solidity
// Minimum safe Chainlink consumption pattern
function getChainlinkPrice(address feedAddress) internal view returns (uint256) {
AggregatorV3Interface feed = AggregatorV3Interface(feedAddress);
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = feed.latestRoundData();
// REQUIRED checks — all four must pass:
require(answer > 0, "Negative price"); // Sanity
require(updatedAt > 0, "Round not complete"); // Stale round
require(block.timestamp - updatedAt <= 3600, "Price stale"); // Heartbeat check
require(answeredInRound >= roundId, "Stale answer"); // Round completeness
return uint256(answer);
}
```
### Oracle Risk Matrix
| Oracle Type | Manipulation Cost | Staleness Risk | Recommended For |
|-------------|------------------|----------------|-----------------|
| Single-block DEX spot | Very low (flash loan) | Low | Never use for value decisions |
| TWAP (30 min) | Medium | Medium | Low-value operations |
| TWAP (24 hr) | High | High | Medium-value |
| Chainlink with checks | Very high (requires majority of node operators) | Low | Production DeFi |
| Chainlink + TWAP sanity | Highest | Low | High-value lending/derivatives |
---
## V-6: Delegatecall and Proxy Vulnerabilities
**Severity: Critical** — storage collision destroys proxy contracts
### How `delegatecall` Works
```
Normal call: msg.sender → ContractA.foo() → reads ContractA's storage
Delegatecall: msg.sender → Proxy.delegatecall(Logic.foo()) → reads PROXY's storage
using Logic's slot layout
```
The logic contract's code runs but in the proxy's storage context. Slot layout must match.
### Storage Collision
```solidity
// Proxy storage:
contract Proxy {
address public implementation; // slot 0
address public admin; // slot 1
}
// Logic contract:
contract LogicV1 {
address public owner; // slot 0 — COLLIDES with Proxy.implementation
uint256 public totalSupply; // slot 1 — COLLIDES with Proxy.admin
}
// Writing to owner in logic actually overwrites implementation in proxy
```
### EIP-1967 Standard Slots (Fix)
```solidity
// Use pseudo-random slots far from slot 0 to avoid collisions
bytes32 private constant IMPLEMENTATION_SLOT =
bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1);
// = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
bytes32 private constant ADMIN_SLOT =
bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1);
```
### Uninitialized Implementation Contract
```solidity
// VULNERABLE: if implementation contract is deployed without initialization,
// anyone can call initialize() on the implementation directly
contract TokenLogic {
address public owner;
bool private initialized;
// Missing: check that this hasn't been called before
function initialize(address _owner) external {
owner = _owner;
}
}
// SAFE: use initializer modifier (OpenZeppelin Initializable)
function initialize(address _owner) external initializer {
owner = _owner;
}
```
---
## V-7: Denial of Service
**Severity: High** — can permanently lock funds
### Push Payment DoS
```solidity
// VULNERABLE: if any recipient reverts, ALL payments fail
function distributeRewards(address[] memory recipients, uint256[] memory amounts) external {
for (uint256 i = 0; i < recipients.length; i++) {
payable(recipients[i]).transfer(amounts[i]); // One revert = all fail
}
}
```
**Attacker tactic**: Deploy a contract with a `receive()` that always reverts, add it to `recipients`. Entire distribution is permanently stuck.
### Pull Payment Pattern (Fix)
```solidity
// SAFE: each user withdraws their own funds; failures are isolated
mapping(address => uint256) public pendingWithdrawals;
function distributeRewards(address[] memory recipients, uint256[] memory amounts) external {
for (uint256 i = 0; i < recipients.length; i++) {
pendingWithdrawals[recipients[i]] += amounts[i]; // Never fails
}
}
function withdrawReward() external {
uint256 amount = pendingWithdrawals[msg.sender];
require(amount > 0, "Nothing to withdraw");
pendingWithdrawals[msg.sender] = 0; // CEI: effect before interaction
payable(msg.sender).transfer(amount);
}
```
### Unbounded Loop DoS
```solidity
// VULNERABLE: attacker can grow array until gas cost exceeds block limit
address[] public allUsers;
function processAll() external {
for (uint256 i = 0; i < allUsers.length; i++) { // Can become uncallable
_processUser(allUsers[i]);
}
}
```
**Fix**: Use pagination (`startIndex`, `count` parameters), or off-chain enumeration with on-chain single-item processing.
---
## Vulnerability Quick-Reference
| Vulnerability | Root Cause | Primary Fix | Detection Signal |
|---------------|-----------|-------------|-----------------|
| Reentrancy | External call before state update | CEI pattern + ReentrancyGuard | `call()` before storage write |
| Integer overflow | Arithmetic wrap-around | Solidity ≥0.8.0; audit `unchecked` | `unchecked {}` or assembly math |
| Access control | Missing or wrong auth check | `msg.sender` checks, AccessControl | Missing modifier on sensitive fn |
| Front-running | Mempool visibility | Commit-reveal, slippage limits | Price-sensitive one-step ops |
| Oracle manipulation | Trusting manipulable price | TWAP + Chainlink with staleness checks | Single-block spot price reads |
| Proxy storage collision | Misaligned slot layout | EIP-1967 slots, OpenZeppelin Proxy | Proxy and logic share slot 0 |
| Push payment DoS | External call in loop | Pull payment pattern | `transfer()` inside loops |
---
## Audit Tool Integration
Run these before any mainnet deployment:
```bash
# Slither: static analysis (catches ~80% of V-1 through V-5 above)
pip install slither-analyzer
slither . --print human-summary
# Mythril: symbolic execution (deeper but slower)
pip install mythril
myth analyze contracts/MyContract.sol --solc-version 0.8.20
# Echidna: property-based fuzzing (catches logic bugs not caught by static analysis)
# Requires a separate properties contract defining invariants
echidna-test . --contract MyContractProperties --config echidna.yaml
```
**Automated tools do not replace manual review.** Slither will not catch complex oracle manipulation or economic attacks. Use automated tools to eliminate obvious issues, then apply the patterns in this document to review logic manually.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |