---
name: solidity-security
description: Master smart contract security best practices to prevent common vulnerabilities and implement secure Solidity patterns. Use when writing smart contracts, auditing existing contracts, or implementing security measures for blockchain applications.
enabled: false
source: github:JuanJoseGonGi/skills
imported-from: github:JuanJoseGonGi/skills
---

# Solidity Security

Master smart contract security best practices, vulnerability prevention, and secure Solidity development patterns.

## When to Use This Skill

- Writing secure smart contracts
- Auditing existing contracts for vulnerabilities
- Implementing secure DeFi protocols
- Preventing reentrancy, overflow, and access control issues
- Optimizing gas usage while maintaining security
- Preparing contracts for professional audits
- Understanding common attack vectors

## Critical Vulnerabilities

> Full vulnerable/secure code examples: **references/vulnerability-patterns.md**

### 1. Reentrancy

Attacker calls back into contract before state is updated. External call before state change lets attacker re-enter and drain funds.

**Fix:** Checks-Effects-Interactions pattern (update state before external calls) or OpenZeppelin `ReentrancyGuard` with `nonReentrant` modifier.

### 2. Integer Overflow/Underflow

Arithmetic wraps around in Solidity < 0.8.0 (e.g., `uint256(0) - 1` = `MAX_UINT`).

**Fix:** Use Solidity >= 0.8.0 (built-in checks) or `SafeMath` for older versions.

### 3. Access Control

Critical functions callable by anyone when missing `onlyOwner` / role checks.

**Fix:** OpenZeppelin `Ownable` or `AccessControl`. Apply modifiers to all sensitive functions.

### 4. Front-Running

Attackers observe mempool and submit transactions ahead of victims (sandwich attacks on DEXes).

**Fix:** Commit-reveal schemes, slippage limits, or private transaction pools (Flashbots).

## Security Best Practices

> Full code examples: **references/secure-patterns.md**

### Checks-Effects-Interactions (CEI)

1. **CHECKS** — validate all conditions with `require`
2. **EFFECTS** — update contract state
3. **INTERACTIONS** — external calls last

### Pull Over Push

Let users withdraw funds rather than pushing payments. Prevents single-failure blocking entire batches.

### Input Validation

Always validate: non-zero address, non-zero amount, sender has sufficient balance, recipient is not the contract itself.

### Emergency Stop (Circuit Breaker)

Use OpenZeppelin `Pausable` to add `whenNotPaused` modifier to critical functions with owner-controlled `_pause()` / `_unpause()`.

## Gas Optimization

> Full code examples: **references/gas-optimization.md**

| Technique | Why |
|-----------|-----|
| Use `uint256` over smaller types | EVM operates on 256-bit words; smaller types cost extra conversion gas |
| Pack storage variables | Group smaller types to fill 32-byte slots (e.g., `uint128 + uint64 + uint64`) |
| Use `calldata` over `memory` | Avoids copying for read-only external function args |
| Events over storage | Cheaper when on-chain reads aren't needed |
| Cache storage reads | `uint256 bal = balances[msg.sender]` — read once, use many |
| Short-circuit `require` | Put cheapest checks first |

## Security Checklist

Before deployment or audit, verify:

- [ ] Reentrancy protection (ReentrancyGuard or CEI pattern)
- [ ] Integer overflow/underflow (Solidity 0.8+ or SafeMath)
- [ ] Access control on all sensitive functions
- [ ] Input validation (require statements)
- [ ] Front-running mitigation (commit-reveal if applicable)
- [ ] Gas optimization (packed storage, calldata)
- [ ] Emergency stop mechanism (Pausable)
- [ ] Pull over push pattern for payments
- [ ] No `delegatecall` to untrusted contracts
- [ ] No `tx.origin` for authentication (use `msg.sender`)
- [ ] Proper event emission for all state changes
- [ ] External calls at end of function
- [ ] Check return values of all external calls
- [ ] No hardcoded addresses
- [ ] Upgrade mechanism tested (if proxy pattern)
- [ ] Pinned pragma version (no floating `^`)

## Common Pitfalls

1. **`tx.origin` for auth** — spoofable via intermediate contracts; use `msg.sender`
2. **Unchecked external calls** — always check `bool success` return
3. **`delegatecall` to untrusted contracts** — can hijack storage/control flow
4. **Floating pragma** — pin to specific Solidity version (e.g., `pragma solidity 0.8.20;`)
5. **Missing events** — emit events for every state change for off-chain tracking
6. **Unbounded loops** — can hit block gas limit; use pagination or limits
7. **No upgrade path** — consider transparent/UUPS proxy if upgrades needed

## Tools for Security Analysis

| Tool | Type | Use |
|------|------|-----|
| **Slither** | Static analysis | Fast detection of common patterns |
| **Mythril** | Symbolic execution | Deep vulnerability discovery |
| **Echidna** | Fuzzing | Property-based testing |
| **Manticore** | Symbolic execution | Complex path exploration |
| **Securify** | Automated scanner | Quick compliance checks |

## References

- **references/vulnerability-patterns.md** — Full vulnerable/secure code for reentrancy, overflow, access control, front-running
- **references/secure-patterns.md** — CEI, pull-over-push, input validation, emergency stop, testing examples, audit preparation
- **references/gas-optimization.md** — Detailed gas optimization code patterns
