# vulnerability-patterns
Catalog of known smart contract vulnerability patterns, their mechanics, the EVM or Solidity behaviors that enable them, and conditions required for exploitation.
## Reentrancy
### Core Mechanism
- [[reentrancy is possible whenever external calls precede state updates]]: four distinct types, all share the same root cause
- [[checks-effects-interactions pattern prevents reentrancy by updating state before external calls]]: the canonical defense pattern
### Variants
- [[read-only reentrancy exploits view functions to cause other protocols to read inconsistent state]]: indirect attack via stale view function data during mid-execution callbacks
- [[ERC-721 safeTransferFrom and ERC-777 tokensReceived callbacks create reentrancy entry points in any protocol handling these token standards]]: token standard callbacks as systematically underestimated reentrancy vectors (Omni, HypeBears, Lendf.Me)
- [[ERC-1155 mintBatch callback creates reentrancy before valueLeft storage write enabling unlimited token fraction splitting]]: ERC-1155 as the third hidden-callback standard; Hypercerts audit finding with unlimited token fraction splitting as the impact
- [[hidden ERC standard callbacks create reentrancy surface developers do not recognize as hookable]]: generalizes the token callback variant across all three ERC standards; the shared cognitive failure is the developer's implicit model of standard library calls as pure state writes
### Compiler-Level Reentrancy Failures
- [[vyper compiler reentrancy lock storage slot bug broke cross-function reentrancy protection in versions 0.2.15 through 0.3.0]]: CVE-2023-46247, the compiler bug behind the $52M Curve exploit
- [[vyper empty string nonreentrant key silently produces no reentrancy checks at runtime]]: CVE-2023-42441, empty lock key silently skips all protection
- [[vyper default function did not respect nonreentrancy decorator prior to v0.3.0 allowing reentrancy through the fallback path]]: fallback function never emitted lock code despite decorator
### Reentrancy Impact & Evolution
- [[reentrancy attacks have caused over 500 million dollars in cumulative losses across 70 plus incidents from 2016 through 2025 despite being the most well-known smart contract vulnerability]]: quantitative evidence of persistence across 7 variant types and every major chain
- [[reentrancy variant evolution outpaces defense adoption because each variant exploits a different assumption about where external calls occur]]: why reentrancy persists: 7 variants, each defeating the defense designed for the previous one
- [[vyper nonreentrant decorator uses a single global storage lock eliminating cross-function reentrancy by design in versions 0.4.0 and later]]: post-exploit redesign of Vyper's reentrancy model
### Account Abstraction Reentrancy
- [[ERC-4337 multi-UserOperation bundles require manual transient storage cleanup because transient values from one sender persist into subsequent sender validation]]: EIP-1153 transient storage leaks across bundle sender boundaries
## Compiler Vulnerabilities
### Solidity Compiler Bugs
- [[solidity via-IR transient storage clearing helper collision emits wrong opcode when clearing both persistent and transient variables of the same type]]: SOL-2026-1, Yul helper naming collision in via-ir pipeline (0.8.28-0.8.33)
- [[majority of solidity 0.8.x compiler bugs manifest only under specific pipeline configurations creating hidden behavioral divergence from identical source code]]: same source code, different bytecode semantics depending on compiler flags
### Vyper Compiler Bugs
- [[vyper double evaluation bugs form the largest cluster of compiler CVEs causing side effects to execute multiple times or in wrong order]]: five CVEs from 2024-2025, all from failure to cache intermediate values to stack
- [[vyper augmented assignment evaluation order enables out-of-bounds writes when right-hand side modifies the target array]]: CVE-2025-27105, critical OOB write via cached DynArray target
- [[vyper compiler side effect elision skips state-changing expressions when slice or concat receives zero-length arguments]]: CVE-2025-47774 and CVE-2025-47285, compiler optimizations silently drop state changes
- [[vyper builtin function argument evaluation order is undefined causing unpredictable results with side-effecting expressions]]: undefined evaluation order is the root cause of multiple compiler CVE clusters
### Cross-Compiler Patterns
- [[transient storage violates composability assumptions in multi-contract interactions because values persist across external calls within a transaction]]: new storage domain creating novel compiler-level complexity in both languages
- [[compiler bugs represent a distinct threat category where source-level security analysis is structurally insufficient]]: bytecode verification must become standard audit practice
- [[silent semantic mismatch is a cross-language vulnerability class where code appears to enforce constraints but silently fails]]: correct bytecode from misleading source, distinct from wrong bytecode from correct source
- [[compiler bug patches without coordinated disclosure to deployed protocols create vulnerability windows measured in months to years]]: the ecosystem responsibility gap: fixing a bug in the compiler leaves deployed contracts exposed until protocols are notified; Vyper nonreentrant fix existed 20 months before Curve exploit
## Input Validation
- [[non-existent ID manipulation returns default values enabling silent state corruption]]: functions accepting IDs without existence checks return Solidity defaults, enabling counter decrements and state transitions on phantom records
- [[inconsistent array length between correlated input arrays causes out-of-bounds errors and silent state corruption]]: mismatched lengths between correlated arrays cause OOB panics or wrong data pairings
- [[interface type signature mismatches produce different function selectors causing calls to invoke the fallback function instead of the intended implementation]]: differing parameter types in interface vs implementation dispatch to fallback silently
- [[Solidity allows casting any address to any contract interface type enabling contracts to initialize external dependencies to malicious addresses that pass type checks while executing attacker code]]: type system provides zero bytecode verification on interface casts
## Solidity Language Footguns
- [[incorrect inheritance ordering in Solidity multiple inheritance causes unintended function dispatch because the C3 linearization algorithm resolves ambiguity via reverse order of base class declaration]]: rightmost base has highest priority in C3 MRO; C is A, B means B wins
- [[the Unicode RTL override character U+202E embedded in Solidity source code visually reorders identifiers hiding malicious code from auditors reading the file]]: U+202E reverses display order; compiler reads bytes, not rendered glyphs; invisible in code review
## Access Control
- [[access control vulnerabilities are the leading cause of smart contract financial losses]]: $953.2M in 2024 losses, #1 on OWASP 2025
- [[tx.origin authentication is vulnerable to phishing because any contract in the call chain can read it]]: specific failure mode using tx.origin instead of msg.sender
- [[EXTCODESIZE returns zero during constructor execution allowing contracts to bypass code-size-based EOA checks]]: constructor-phase bypass of isContract-style guards; allows whitelist evasion, bot-prevention bypass, and pre-sale draining with permanent effect
- [[insufficient access control on sensitive functions allows any caller to execute privileged operations]]: missing modifiers, misspelled modifier names, and overpowered role design all produce the same outcome
- [[two-step ownership transfer is exploitable when step two does not verify step one was initiated]]: state-based precondition failure: acceptOwnership() missing a check that pendingOwner was set, allowing direct call to brick or hijack contract ownership; canonical fix is OpenZeppelin Ownable2Step
- [[single-step ownership transfer without confirmation from the new owner risks permanent loss of contract admin control if the target address is wrong or cannot accept ownership]]: architectural risk that motivates two-step adoption; a typoed address or non-accepting contract permanently bricks admin control
- [[Solidity functions without an explicit visibility modifier defaulted to public before version 0.5.0 allowing anyone to call intended-internal functions]]: pre-0.5 default public visibility made initialization functions and internal helpers universally callable
- [[state variables without an explicit visibility modifier default to internal in Solidity making incorrect visibility assumptions invisible during code review]]: the complementary visibility default for state variables; internal by default, no auto-generated getter, creating audit blind spots
- [[unvalidated user-supplied calldata passed to low-level calls in router contracts enables arbitrary transferFrom execution against tokens users have approved to the router]]: Seneca ($6.4M) and Socket ($3.4M) 2024; router holds approvals + unvalidated calldata = attacker drains all approved tokens
- [[stale token approvals persisting after router or spender contract updates create unauthorized spending vectors]]: old approvals persist after contract migration, giving deprecated contracts continued spending authority
- [[incomplete cancellation cleanup that revokes claim access but preserves token allowances creates a dangling approval attackers can exploit after fund withdrawal]]: Hedgey $44.7M; cancelCampaign() withdrew funds and deleted campaign record but omitted safeDecreaseAllowance(), leaving the ERC-20 allowance intact on the token contract for post-cancellation drain
- [[user-granted unlimited token approvals extend a protocol key compromise beyond protocol TVL to all user wallets that previously approved the compromised address]]: bZx November 2021; compromised deployment key drained user wallets via outstanding unlimited approvals; blast radius exceeds protocol TVL
## Signature & Cryptographic
- [[signature malleability allows replay by computing complementary ECDSA signatures without the private key]]: secp256k1 symmetry enables alternative valid signatures; EIP-2098 compact signatures add a second bypass vector
- [[signature replay attacks succeed when contracts verify signatures without tracking processed message hashes]]: same signed message submitted repeatedly; taxonomy of five sub-patterns (cross-chain, missing parameter binding, no expiry, malleability, no nonce)
- [[signature expiration deadlines are necessary because signatures without timestamps function as irrevocable lifetime licenses]]: sub-pattern 3 of replay taxonomy: no expiry converts a signed capability into a permanent grant; nonce prevents re-execution but not delayed first execution; EIP-2612 deadline field is the canonical fix; connects to the same "no expiry = lifetime grant" pattern in [[EIP-7702 authorization tuples encode no execution scope, expiry, or call restrictions making them semantically equivalent to unconditional persistent capability grants]]
- [[ecrecover returns address zero on invalid signatures which matches uninitialized address variables creating false authorization]]: address(0) comparison bypass
- [[EIP-712 domain separator computed at deployment becomes stale after chain forks enabling cross-chain replay]]: cached chainId in domain separator enables fork replay; now enriched with ERC-4337 VerifyingPaymaster chain ID omission angle
- [[cross-chain signature replay succeeds when UserOperations omit chain_id from the signed message]]: ERC-4337 UserOperation chain-binding failure: no fork needed, missing chain_id in payload enables replay wherever same address is deployed; complements the domain separator staleness case in the note above
- [[cross-chain replay of signatures without chain_id binding impacts any signature scheme used across multi-chain deployments]]: generalizes cross-chain replay beyond ERC-4337 to any multi-chain signature scheme
- [[EIP-1271 contracts without isValidSignature implementation return true via fallback causing false signature validation]]: absent EIP-1271 implementation with non-reverting fallback masquerades as valid signer
- [[ERC-2612 permit signatures enable gasless approvals but create phishing vectors where users unknowingly sign malicious allowances]]: $35M stolen in 2024 via off-chain permit phishing bypassing wallet warnings
- [[ERC-4337 signature replay across wallets exploits isValidSignature implementations that authenticate a bytes32 hash without binding the signature to a specific account address]]: cross-wallet replay when domain separator omits account address; requires EIP-712 per-account domain binding
- [[ERC-4337 accounts that revert on signature failure instead of returning SIG_VALIDATION_FAILED break bundler simulation and prevent graceful rejection]]: common ERC-4337 implementation error: must return sentinel not revert on bad signature
### ECDSA Nonce Security
- [[ECDSA nonce reuse directly reveals the private key because two signatures sharing the same r value expose k algebraically]]: identical r values across two signatures expose k and then d via pure algebra in microseconds; Sony PS3 key recovery; Ronin-related EOA drains
- [[biased ECDSA nonces enable lattice-based private key recovery with as few as two or three signatures]]: Hidden Number Problem; BKZ lattice reduction; 2 sigs with 128-bit nonces = 75% recovery; LadderLeak extracts 1-bit bias from cache timing
- [[RFC 6979 deterministic nonce generation eliminates ECDSA private key leakage from randomness failures by deriving nonces from message and private key]]: HMAC-DRBG over (sk, msg_hash) makes both exact reuse and biased nonces computationally impossible
### BLS Multi-Signature Security
- [[BLS signature aggregation enables rogue-key attacks where an attacker forges multi-signatures by registering a cancellation public key]]: PK_rogue = g^beta * PK_honest^(-1) cancels honest key in aggregate; Harmony FBFT consensus; EigenLayer AVS fraud; EIP-2537 Pectra relevance
- [[proof of possession prevents BLS rogue-key attacks only when the PoP hash function is domain-separated from the signature hash function]]: splitting-zero attack exploits shared hash domain between PoP and signing; DST parameter in BLS12-381 hash-to-curve is the implementation requirement
### Merkle Proof Security
- [[Merkle proof second-preimage attacks exploit missing domain separation between leaf and internal node hashes]]: no hash collision required; 64-byte internal node submitted as leaf with shortened proof path; OpenZeppelin issue #3091; FSA framework 2025
- [[commit-reveal schemes without msg.sender binding allow front-runners to copy commitments and claim the reveal reward]]: commitment hash omitting msg.sender is copyable; fix: include msg.sender in hash
### Key Generation & Address Security
- [[publicly disclosed key compromise requires immediate admin privilege revocation across all dependent systems not just fund movement from the compromised address]]: Wintermute opsec failure; moving funds but retaining admin roles left vault authority exercisable by attacker after key recovery; applies to any disclosed key compromise
### Cross-Chain Cryptographic Infrastructure
- [[cross-chain bridge cryptographic failures account for 40 percent of total Web3 hack losses through validator key compromise and signature scheme weaknesses]]: $2.8B+ from Ronin ($625M), Wormhole ($325M), WazirX ($230M), Bybit ($1.5B); cryptographic primitives functioned correctly, key management and signing infrastructure failed
- [[supply chain injection into hardware wallet signing interfaces enables theft without private key extraction by tricking operators into signing fraudulent transactions]]: Bybit $1.5B; JS injection into Safe{Wallet} S3; hardware wallet signs what it receives; supply chain attack on display layer
### EVM Cryptographic Precompiles
- [[EVM precompiles for BN256 elliptic curve operations never revert on invalid input requiring explicit return value checks to detect proof verification failures]]: ecAdd (0x06), ecMul (0x07), ecPairing (0x08) return empty/false on error; unchecked return value means invalid ZK proofs silently pass; EIP-196, 197, 1108
- [[EVM-compatible chain precompile implementations diverge from mainnet specifications creating silent failures for contracts that are safe on Ethereum]]: Moonbeam reverts on under-length input; Aurora v2.7.0 reverts on identity point (0,0); OpDiffer ISSTA 2025: 7.21% of contracts affected
## Low-Level EVM Code
- [[hand-written EVM code shares a specific set of vulnerability classes that are structurally impossible in compiler-generated code]]: synthesis of six compiler-absent safety guarantees: dispatch termination, type masking, extcodesize check, arithmetic safety, access control, and blueprint protection
- [[hand-written EVM function dispatchers that lack a terminal revert allow execution to fall through into unrelated bytecode]]: missing terminal revert in Huff/raw EVM dispatch causes unintended code execution
- [[low-level EVM code must explicitly validate calldata input bit widths because the EVM performs no type-level masking on function parameters]]: dirty calldata upper bits produce different storage slots, permanently locking balances
- [[inline assembly bypasses solidity safety checks including type enforcement and overflow protection]]: assembly bypasses all compiler safety
- [[ERC-5202 blueprint contracts without preamble prefix are callable as runtime code enabling unauthorized constructor execution]]: missing 0xFE71 preamble allows direct CALL execution of stored initcode
## Arithmetic
- [[unchecked arithmetic blocks reintroduce overflow vulnerabilities in post-0.8 solidity]]: unchecked blocks restore pre-0.8 wrapping behavior
- [[integer overflow dropped from second to eighth risk after solidity 0.8 default protections]]: quantifies compiler protection impact; uint underflow wraps to type max enabling token balance inflation in pre-0.8 contracts
- [[assert() misuse for input validation consumes all gas and halts execution instead of gracefully reverting like require()]]: assert() emits INVALID/Panic(0x01) consuming all gas; require() uses REVERT and refunds; misuse makes invalid inputs expensive and failure signal ambiguous
- [[gas optimization via unchecked blocks creates tension with arithmetic safety guarantees]]: structural tension between gas efficiency, safety, and DoS risk
- [[Newton-Raphson iterative solvers in AMM invariant calculations are vulnerable to divergence under extreme input imbalance producing truncated or incorrect state values]]: numerical solver domain violations producing formally valid but economically nonsensical results; yETH $9M
- [[off-by-one errors in loop bounds and comparison operators cause silent boundary failures]]: incorrect loop bounds and comparison operators produce silent boundary misses at medium severity; in reward accumulator contexts the same class produces magnitude explosions (Compound Finance $147M, > vs >=) at critical severity
- [[solidity 0.8 default checked arithmetic converts overflow from a value manipulation vulnerability into a denial-of-service vulnerability]]: the threat model inversion where pre-0.8 value theft became post-0.8 function bricking
- [[division by zero in solidity always reverts even inside unchecked blocks making attacker-controlled denominators a hard DoS vector]]: unconditional div-by-zero check creates a hard DoS vector with no compiler-level opt-out
- [[signed integer division overflow occurs when dividing the minimum value by negative one because the positive result exceeds the type maximum]]: sdiv of int_min by -1 silently wraps in unchecked/Yul/Huff; Solidity 0.8+ checked arithmetic catches it
## Precision & Rounding
- [[multiplication before division is required in Solidity to minimize precision loss because integer division truncates remainders permanently]]: the per-function audit rule: flag any division before multiplication in the same calculation chain; fix is arithmetic reordering to maximize the numerator before dividing
- [[modular protocol architectures hide precision loss by separating calculations across functions contracts and libraries that obscure rounding accumulation]]: the architectural hiding mechanism: individual function boundaries look acceptable; the cumulative path is exploitable; auditor technique is tracing "precision chain seams" end-to-end; USSD audit via Foundry invariant fuzzing
- [[precision loss in DeFi can be weaponized to drain funds rather than merely disadvantaging users]]: the severity escalation framework: controllable inputs + loss accruing to attacker + loop-repeatability = critical fund-draining vulnerability, not a cosmetic inaccuracy
- [[rounding errors become exploitable when amplifiable through repetition or value scale]]: amplification vector taxonomy: repetition, value scale, loop accumulation, and compositional direction mismatch determine whether rounding crosses the exploitability threshold
- [[individually safe rounding directions can produce exploitable composite errors when applied across multiple operations in sequence]]: distinct from single-operation amplification; the error emerges from interaction of independently safe rounding choices across operations (Bunni $8.4M)
- [[Uniswap v3-v4 LiquidityAmounts helper functions round token amounts down while Pool.modifyLiquidity rounds up creating a systematic accounting discrepancy of up to 1 wei per token per position]]: cross-abstraction-layer rounding: helpers and core contract apply opposite rounding to the same calculation; up to 1 wei per token per position
- [[rounding direction inconsistency between parallel computation paths that resolve the same price creates an exploitable state divergence when conditional logic uses one path while state reflects the other]]: the parallel-path variant: two functions computing the same quantity with different rounding directions; decision logic uses one result while state reflects the other; KyberSwap $48.67M as the founding case
## Logic Errors & Business Logic
### Developer Assumption Exploits
- [[developer subconscious assumptions about prior state create systematic input validation gaps auditors must explicitly hunt]]: enumerate implicit preconditions and flag any without explicit enforcement; covers eight subtypes including empty arrays, step ordering, unchecked returns, unexpected matching inputs, assumed uniqueness, mutual exclusivity, boundedness, and sentinel reliability
- [[empty array inputs bypass loop-based verification entirely when callers omit array length validation]]: loop-based checks pass vacuously with zero elements; multi-sig and batch operations are the primary targets; fix is require(length > 0) or require(length >= threshold) before the loop
- [[duplicate entries in user-supplied lists may bypass implicit uniqueness assumptions enabling double-counting]]: address/ID arrays processed without uniqueness enforcement allow double-counting of votes, balances, or reward claims
- [[functions with source and destination parameters may malfunction when the two addresses are equal because cached balances diverge from reality]]: cached balance reads at function entry become stale after the first mutation when src==dst; enables balance inflation
- [[checking default values to detect initialization is unreliable because default values can be legitimate state]]: address(0), zero, and empty containers as sentinel values for "not initialized" fail when those values are legitimate; re-triggers initialization logic
- [[stale cached state after lifecycle transitions enables exploitation when initialization logic conflates fresh deployment with drained state]]: cached storage not reset when protocol returns to zero state through normal operation (full withdrawal, migration); yETH $9M
- [[bootstrap and initialization logic that remains reachable after launch creates a permanent re-initialization attack surface]]: first-operation logic gated by state conditions rather than one-time flags remains callable when conditions recur; yETH $9M
- [[Uniswap v4 modifyLiquidity callerDelta bundles accrued fees with principal causing logic that assumes negative-only deltas to revert or double-count fees]]: three failure patterns from assuming callerDelta contains only principal; V4-specific integration pitfall
- [[non-atomic on-chain initialization creates a universal race condition between structure creation and configuration]]: cross-domain synthesis: AMM pools, proxies, vaults, and bootstrap re-entry all share the same exploitable gap between creation and configuration
### Input Validation
- [[unvalidated user-supplied contract addresses enable arbitrary code execution when protocols call interfaces on attacker-controlled deployments]]: protocols invoking interfaces on user-supplied addresses grant attackers delegated execution context; SushiSwap RouteProcessor2 ($3.3M) canonical case
- [[unvalidated user-supplied spender addresses in token approval flows allow attackers to route ERC-20 allowances to attacker-controlled contracts]]: the approval-specific instantiation: caller-controlled spender address in increaseAllowance call hands ERC-20 spending authority to attacker; Hedgey Finance ($44.7M) canonical case
- [[excessive input validation can lock funds permanently by making withdrawal or critical operations unreachable under valid conditions]]: the inverse problem: over-constraining inputs locks funds when legitimate operations fail overly restrictive preconditions; Akutars ($34M) canonical case
### ERC-20 Implementation Edge Cases
- [[ERC-20 self-transfer with identical sender and recipient duplicates tokens when the implementation subtracts then adds to the same balance without checking sender != recipient]]: bZx iToken ($8.1M, Sep 2020); survived two audits; subtract-then-add without sender != recipient guard; self-transfer edge case not in auditors' specification
### General Logic Errors
- [[logic errors climbed from seventh to third in owasp 2025 ranking indicating a shift toward business logic as primary attack surface]]: $63.8M from application-specific logic flaws; confirmed by 2026 data
- [[business logic vulnerabilities are the highest-frequency attack category yet resist systematic defensive patterns because economically valid code can break under adversarial pressure]]: #2 OWASP 2026 with 58 incidents (47.5% of all 2025 incidents); economically valid code that breaks under adversarial pressure
- [[owasp smart contract top 10 2026 confirms business logic and access control together account for 78 percent of all 2025 incidents]]: 2026 ranking from 122 incidents/$905.4M; business logic #2, access control #1
- [[on-chain rate limiting is undermined by Sybil attacks enabling a single attacker to distribute operations across multiple accounts to evade per-address limits]]: per-address limits structurally bypassable without on-chain identity
- [[Solidity scratch space at memory addresses 0x00-0x3f is overwritten by mapping and array storage slot calculations between assembly blocks]]: scratch space corruption when mapping/array operations occur between assembly blocks
- [[abi.encodePacked concatenates types shorter than 32 bytes without padding creating collision risks]]: hash collision via packed encoding
- [[explicit returns from solidity modifiers do not affect function return values allowing silent control flow bypasses]]: modifier early returns leave return variables at default zero values
## Upgrade & Proxy
- [[unrestricted delegatecall allowing user-specified target addresses enables fund drainage and state manipulation]]: arbitrary code execution in caller's storage
- [[storage layout must remain consistent across proxy implementation versions]]: layout mismatch corrupts state
- [[uninitialized proxy contracts are vulnerable to re-initialization attacks that hijack ownership]]: missing initialization guards; CPIMP is the sophisticated variant that inserts a persistent intermediary rather than claiming ownership
- [[function selector clashes between proxy and implementation can shadow critical admin functions]]: shared namespace collisions
- [[selfdestruct in implementation contracts can permanently brick proxy systems]]: irreversible implementation destruction
- [[contract upgrade procedures create temporary vulnerability windows when initialization must occur after a state change that disables reentrancy protection]]: Optimism: upgrade procedure disabled reentrancy check, enabling double withdrawal during transition window
- [[beacon proxy patterns share upgrade risk across all dependent proxies]]: amplified upgrade risk across system
- [[EIP-1822 UUPS upgrade logic in implementation enables permanent proxy bricking if implementation is destroyed or uninitialized]]: UUPS's upgrade-logic-in-implementation design makes uninitialized or selfdestructed implementations permanently fatal
- [[EIP-2535 Diamond proxy facet storage collisions occur when multiple facets write to non-namespaced storage slots]]: sequential storage layout in facets collides with other facets sharing the same proxy storage
- [[storage gap mismanagement in upgradeable base contracts causes child contract storage collisions]]: __gap arrays in base contracts must be decremented correctly during upgrades; Audius (July 2022) lost funds from gap mismanagement
- [[re-initialization vulnerabilities arise when upgrades inadvertently reset initialization state]]: distinct from uninitialized proxies; upgrade resets the initialized boolean; AllianceBlock (August 2024)
- [[access control failures on UUPS _authorizeUpgrade enable unauthorized proxy upgrades to arbitrary code]]: missing onlyOwner on _authorizeUpgrade allows any address to upgrade; the most common UUPS-specific vulnerability
- [[proxy architecture choice determines the tradeoff between upgrade authority concentration selector routing cost and blast radius scope]]: synthesis comparing transparent, UUPS, beacon, and diamond patterns across five security dimensions
- [[upgrade and deployment procedures constitute a process-layer vulnerability class structurally invisible to code-level security analysis]]: synthesis of deployment-phase, upgrade window, and re-initialization vulnerabilities as a distinct process-layer class
## CPIMP (Cross-Proxy Intermediary Malware Pattern)
- [[CPIMP attacks exploit the gap between proxy deployment and initialization to inject a persistent malicious intermediary that parasitizes the protocol invisibly]]: the core CPIMP mechanism; July 2025 wave affected EtherFi, Pendle, Orderly Network and dozens of others
- [[non-atomic proxy deployment creates a front-running window where any actor can write to the ERC1967 implementation storage slot before the legitimate initialization transaction confirms]]: the root vulnerability enabling CPIMP; separate deployment and initialization transactions create a mempool-visible window
- [[double-delegation chains in CPIMP attacks forward all calls to the legitimate implementation preserving normal protocol functionality while granting hidden attacker control]]: the structural mechanism and per-selector dispatch: proxy → shadow → legitimate implementation makes CPIMP invisible in normal operation
- [[CPIMP self-restoration after every transaction makes standard upgrade procedures ineffective as removal mechanisms]]: three-layer anti-recovery: self-restoration defeats upgrades, immutable backdoor defeats access control changes, outflow caps defeat emergency fund evacuation
- [[CPIMP defeats detection by layering fake ERC1967 Upgraded events with legacy storage slot misdirection so each standard monitoring method sees the legitimate implementation]]: layered detection evasion targeting event readers and legacy-slot readers simultaneously
- [[atomic proxy deployment by passing initialization data to the ERC1967Proxy constructor eliminates the CPIMP front-running window because deployment and initialization occur within a single transaction]]: the primary CPIMP prevention: pass _data to ERC1967Proxy constructor
- [[CREATE2 deterministic deployment enables atomic initialization of circularly dependent proxy contracts by allowing all required addresses to be precomputed before any deployment transaction]]: extends atomic deployment to multi-contract systems with circular address dependencies
- [[post-deployment verification by directly reading ERC1967 implementation storage slots detects proxy hijacking that block explorer displays and emitted events conceal]]: authoritative detection: eth_getStorageAt on EIP-1967 slot cannot be spoofed by CPIMP
- [[deployment-phase vulnerabilities are structurally invisible to standard smart contract audits because auditors examine implementation code correctness not deployment transaction sequences]]: structural audit blindspot; USPD had correct code and two clean audits, yet was exploited at deployment
- [[the USPD exploit demonstrated that publicly disclosed deployment vulnerabilities remain exploitable when teams apply published mitigations to new code without auditing their own deployment procedures]]: USPD ($1M, Dec 2025); exploited 3 months after public CPIMP disclosure; 24-second deployment-to-exploit window
## Denial of Service
- [[DoS via block gas limit permanently bricks functions that iterate over unbounded arrays]]: unbounded loops exceed block gas limit
- [[DoS via unexpected revert exploits fallback functions that intentionally revert to block ETH transfers]]: malicious fallback blocks push payments; pull-payment isolates failures and encodes the design principle that external call failures are expected conditions not exceptions; EIP-7702 extends the attack surface to delegated EOAs
- [[insufficient gas griefing in relayer patterns allows forwarders to starve subcalls while outer transactions succeed]]: meta-transaction gas starvation where forwarder under-supplies gas to subcalls; EIP-150 63/64 rule complicates accounting; defenses split between trust restriction (vetted relayers) and gas verification (enforce adequate forwarding)
- [[unbounded return data from external calls forces quadratic memory cost gas consumption via RETURNDATASIZE]]: malicious callee forces quadratic memory costs via oversized return data
- [[induction variable overflow permanently bricks loop-dependent functions when counter types are too small for the iteration range]]: loop counter overflow (e.g., uint8 past 255) triggers Panic(0x11), distinct from gas limit DoS
- [[attacker-controlled array indices or lengths trigger out-of-bounds panics that permanently block critical contract functions]]: Panic(0x32) via manipulated indices or shrunk arrays in governance, rewards, liquidation
- [[empty array pop triggers Panic(0x31) enabling denial of service when attackers drain arrays before pop-dependent operations]]: drain-then-pop two-phase attack on array-dependent functions
## Data Handling
- [[low-level call and send return false on failure without reverting so unchecked return values cause silent fund loss]]: unchecked .call() and .send() return values
- [[Solidity delete on an array element zeroes the slot without reducing array length leaving a zero-value gap that breaks length-based iteration assumptions]]: delete zeroes but does not compact; length unchanged; use swap-and-pop for true removal
- [[msg.value remains constant throughout a transaction enabling double-spend when referenced inside loops]]: msg.value reuse in loops (Opyn hack)
- [[arbitrary storage writes enable attackers to overwrite critical variables when dynamic array slot calculations are manipulable]]: dynamic array length underflow enables any-slot writes across entire storage address space
- [[dangling storage references from array pop operations allow writes to unintended storage locations]]: .pop() invalidates storage references, writes to wrong slots
- [[memory copies of storage data that are never written back silently lose state updates]]: memory keyword instead of storage means mutations are discarded at function exit; distinct from memory aliasing
- [[swap-and-pop list deletion may invalidate external index references to the moved last element]]: O(1) array deletion moves the last element but external index mappings referencing it become stale
- [[assuming contract balance equals the sum of tracked deposits is unsafe because ETH and tokens can arrive unsolicited]]: ETH via selfdestruct/coinbase/CREATE2 pre-funding and tokens via direct transfer break balance/deposit accounting equivalence
- [[contracts accepting both ETH and WETH must enforce mutual exclusivity or msg.value can be double-counted alongside WETH transfers]]: dual payment path without explicit mutual exclusivity guard enables double-counting
## Slippage & Deadline
- [[slippage protection with zero minTokensOut exposes users to unlimited loss and must always be flagged as critical in audits]]: zero or spot-price-derived minimum provides no sandwich protection
- [[on-chain slippage calculation using Quoter contracts is subject to the same manipulation as the spot price it queries]]: Quoter.quoteExactInput() reads manipulated pool state, making the protection circular
- [[slippage invariant requiring outputAmount >= minOutputAmount must be verified at the final operation step not intermediate steps]]: checking slippage on intermediate outputs allows subsequent operations to erode value below the minimum
- [[missing deadline parameters allow transactions to linger in the mempool and execute at substantially worse prices than at submission time]]: temporal slippage from absent deadline parameters
- [[block.timestamp as deadline provides no protection because it references the time at execution]]: self-referencing deadline that always passes regardless of execution timing
## Oracle Manipulation
- [[flash loan oracle manipulation enables price feed attacks against defi protocols]]: $33.8M+ in losses, self-funding atomic attack; bZx (Feb 2020) founding case; UwU Lend ($23M, Curve get_p()), Mango Markets ($114M, thin-liquidity spot purchases), WOOFi ($8.75M, sPMM formula boundary), Cream Finance ($130M, vault pricePerShare donation); TWAP mitigation itself bypassable via asymmetric enforcement; tx.origin==msg.sender guard structurally broken post-Pectra (EIP-7702)
- [[vault token oracle proxies that derive price from on-chain pricePerShare are manipulable by direct token donation to the underlying vault]]: lending protocol oracle vulnerability; Cream Finance Oct 2021 canonical case; direct vault donation inflates pricePerShare without deposit accounting; distinct attack surface from AMM spot price manipulation
- [[oracle spread checks fail to detect manipulation when multiple price sources derive from the same upstream because both sources move together preserving the spread]]: bZx Incident 2 (Feb 18, 2020); spread checks between Kyber and Uniswap failed because Kyber's price derived from Uniswap; both moved together, preserving the spread while both reported manipulated values
- [[AMM spot prices are manipulable within a single transaction making them unsafe as oracle price feeds without TWAP smoothing]]: AMM prices as the specific oracle vector most commonly exploited; also covers LP token valuation via reserve ratio as a second pattern reading raw AMM reserves
- [[LP token valuation formulas using raw AMM reserve ratios are manipulable within a single transaction when reserves can be distorted by a large swap]]: LP oracle variant; `amount * reserve0 * 2 / totalSupply` formula is correct at equilibrium but inflates dramatically after large unidirectional swaps; PancakeBunny $45M canonical case; common in yield aggregator minting and vault share accounting
- [[treating LP tokens as tradeable pool assets in composable pool architectures enables atomic single-transaction manipulation of the invariant used to price those same LP tokens]]: self-referential pricing circularity; BPT is both swappable within the pool and priced from the same invariant D that swapping alters; Balancer V2 Rekt II $128M canonical case
- [[TWAP bypass via asymmetric enforcement allows attackers to exploit unprotected owner functions when calm-period checks guard only non-owner paths]]: the TWAP mitigation bypass: a correctly implemented calm-period check applied only to user-facing functions leaves owner paths unguarded, allowing manipulation during the attack window; generalizes to any safety modifier with asymmetric function coverage
- [[the Mango Markets exploit demonstrated that thin-liquidity oracle manipulation combined with unrealized PnL as collateral enables full protocol drain through controlled spot price inflation]]: $114M (Oct 2022); first DeFi criminal conviction
- [[Chainlink price feed heartbeats vary between feeds with similar names requiring per-feed verification rather than assuming uniform update frequency]]: staleness threshold mismatch from assuming uniform heartbeats across feeds; too-permissive thresholds accept genuinely stale data, too-restrictive thresholds cause false reverts
- [[Chainlink oracle front-running is possible because price feed updates are public transactions that allow sandwiching of oracle price changes]]: mempool-visible price updates enable atomic sandwich attacks exploiting the predictable timing of oracle inclusion
- [[Chainlink minAnswer and maxAnswer price bounds cause oracles to report incorrect prices during flash crashes and extreme events]]: aggregator price clamping at min/max bounds creates divergence from actual market price during extreme events
- [[permissionless oracle reporter systems with low minimum staking thresholds allow attackers to submit manipulated price data for the cost of the stake]]: TellorFlex minimum stake (~$175 at BonqDAO exploit time) was the entire attack cost; mechanistically distinct from flash loan manipulation; no borrowed capital needed; cost bounded by minimum stake not by DEX liquidity
- [[instant oracle price consumption without dispute period validation transforms permissionless oracle reports into single-transaction manipulation vectors]]: the vulnerability pattern enabling BonqDAO; dispute window is the sole manipulation-resistance layer in permissionless oracles; consuming without enforcing it eliminates the protection; correct fix is getDataBefore(queryId, block.timestamp - disputeWindow)
See [[economic-security]] for the cost-of-corruption framework that models when oracle manipulation becomes economically rational.
## MEV & Transaction Ordering
- [[frontrunning exploits public mempool visibility to insert competing transactions before profitable pending operations]]: sandwich attacks, PGAs, generalized frontrunning; $3B+ annual extraction on Ethereum
- [[sandwich attacks exploit AMM deterministic pricing to front-run and back-run victim trades within a single block]]: dominant MEV variant by value (51.56% of total); AMM deterministic pricing is the structural enabler
- [[cross-chain sandwich attacks exploit bridge event visibility to gain mempool-order advantage on destination chains]]: novel cross-chain variant with 21.4% profit rate; current same-chain defenses are structurally ineffective
- [[just-in-time liquidity extraction captures swap fees without bearing impermanent loss by sandwiching large swaps]]: parasitic MEV targeting regular LPs in concentrated liquidity pools
- [[funding rate manipulation in perpetual DEXs allows large positions to skew economic extraction at the expense of counterparties]]: economic extraction via funding rate skew
See [[economic-security]] for MEV game theory, sandwich profitability bounds, and information asymmetry analysis.
## Block Manipulation
- [[on-chain randomness from block attributes is deterministic and manipulable by validators]]: block.timestamp, blockhash, prevrandao as weak randomness
- [[block timestamp manipulation within protocol bounds enables exploitation of time-dependent contract logic]]: pre-merge ~15 second window, post-merge reduced but not eliminated; amplified on L2s via sequencer control; parent pattern for deadline and auction timing vulnerabilities
## Contract Identity
- [[CREATE2 enables contract recreation at the same address with different bytecode when the constructor queries external state]]: address-squatting attacks via deterministic address reuse with changed constructor-time state
- [[ERC-5202 blueprint contracts without preamble prefix are callable as runtime code enabling unauthorized constructor execution]]: missing 0xFE71 preamble allows direct CALL execution of stored initcode
## Account Abstraction (ERC-4337, EIP-7702, ERC-7579)
- [[ERC-4337 EntryPoint singleton concentrates unconditional trust creating a single point of failure across the entire account abstraction ecosystem]]: architectural foundation: all AA accounts must trust the shared EntryPoint
- [[ERC-4337 paymasters deferring token collection to postOp are vulnerable to systematic deposit drainage because EntryPoint continues execution when postOp reverts]]: post-execution charging pattern enables free gas sponsorship attacks
- [[ERC-4337 gas penalty exploitation drains paymaster EntryPoint deposits when users inflate callGasLimit beyond actual execution cost]]: 10% unused-gas penalty enables deposit drainage via inflated gas limits
- [[ERC-4337 multi-UserOperation bundles require manual transient storage cleanup because transient values from one sender persist into subsequent sender validation]]: EIP-1153 transient storage leaks across bundle sender boundaries (Gelato ChainSecurity finding)
- [[ERC-4337 counterfactual wallet takeover occurs when factory CREATE2 salt does not depend on the initial owner credentials allowing attacker pre-deployment]]: factory salt without owner-secret enables pre-deployment hijack (Biconomy Code4rena high)
- [[ERC-4337 malformed calldata in EntryPoint pack() functions allows post-signing mutation of UserOperation fields undermining paymaster sponsorship intent]]: March 2023: Yul assembly encoding ambiguity in pack() enables field substitution post-signature
- [[EIP-7702 delegation phishing enables persistent EOA account takeover through a single signed authorization tuple with effects invisible in standard transaction inspection]]: $12M+ drained, 90%+ on-chain delegations malicious; includes chainId=0 cross-chain amplification and sweeper contract recovery traps
- [[EIP-7702 authorization tuples encode no execution scope, expiry, or call restrictions making them semantically equivalent to unconditional persistent capability grants]]: design-level root cause: no scope field exists in the tuple format; every authorization is structurally an unconditional capability grant
- [[EIP-7702 tx.origin equals msg.sender check no longer prevents flash loan attacks because delegated EOAs can execute arbitrary contract logic while satisfying both identity checks]]: structural invalidation of the most effective runtime exploit guard; flash loan orchestration, reentrancy, and whitelist bypass all pass identity checks
- [[EIP-7702 invalidates pre-Pectra assumptions that EOAs have no code cannot revert ETH transfers and only change balances through signed transactions]]: four broken EVM invariants: contract detection, address(this) signing identity, ETH transfer safety, mempool balance tracking; includes tooling gap analysis
- [[EIP-7702 delegation combined with ERC-4337 infrastructure allows bundlers and paymasters to trigger attacker-controlled code at zero cost to the attacker]]: compositional amplification: bundler relays, paymaster covers gas, EntryPoint executes attacker logic; per-component countermeasures
- [[EIP-7702 delegation does not execute the delegate contract's constructor leaving EOA storage uninitialized unless initialization is explicitly batched with delegation]]: constructor skip + uninitialized state; init front-running window if not batched
- [[EIP-7702 storage collision attacks occur when migrating between delegate contracts with incompatible layouts because existing EOA storage is not cleared on re-delegation]]: re-delegation type confusion: bool in slot X misread as uint256 in new delegate; pre-EIP-7702 wallets categorically unsafe as delegation targets
- [[ERC-7579 modules executing via delegatecall in account storage context allow malicious or buggy modules to overwrite arbitrary storage slots and brick or drain the account]]: delegatecall module = unrestricted storage write access to entire account
## Token Standards
### Non-Standard Token Behavior
- [[the majority of deployed ERC-20 token contracts exhibit non-standard behaviors that break DeFi protocol assumptions]]: FRBScan empirical study: 65.8% of deployed ERC-20s exhibit at least one dangerous non-standard behavior; ERC-20 compliance is the exception, not the rule
- [[tokens with missing return values break IERC20 interface compatibility and revert when callers ABI-decode the absent boolean]]: USDT, BNB, OMG omit bool return value; standard IERC20 interface call reverts on absent return data
- [[tokens that return false on failure instead of reverting create phantom balances when protocols omit return value checks on transfer calls]]: false-returning tokens allow execution to continue after failed transfer; creates unbacked phantom balance
- [[fee-on-transfer tokens enable accounting mismatch exploits in any protocol that equates the amount parameter of transfer to the amount actually received]]: $500K Balancer STA drain; fix is balanceOf-before-minus-after measurement
- [[ERC-777 tokensToSend hook enables pre-transfer reentrancy by executing attacker-controlled code before the sender balance is debited]]: $25.2M dForce + $300K Uniswap imBTC; pre-debit timing bypasses CEI patterns designed for ETH
- [[double entry point tokens with two valid contract addresses sharing one balance storage allow attackers to bypass protocol-level blacklists and drain pools via the secondary address]]: legacy SNX/TUSD; Balancer-SNX DoS; blacklist bypass via secondary address
- [[token admin blocklists can freeze protocol contracts causing liveness failures and permanent fund inaccessibility for legitimate users]]: USDC/USDT Centre blocklists; Tornado Cash precedent; no on-chain defense available
- [[globally pausable collateral tokens halt liquidations in dependent lending protocols creating bad debt when the pause coincides with collateral price decline]]: USDC/USDT/WBTC pause correlated with market stress; third bad debt mechanism distinct from crash-lag and gas-paralysis
- [[upgradeable proxy tokens allow token issuers to modify transfer semantics post-deployment silently breaking protocol integrations built on prior behavior]]: USDC/USDT behind upgradeable proxies; no on-chain detection mechanism for semantic changes
- [[low-decimal tokens reduce the minimum cost of ERC-4626 vault inflation attacks because precision boundaries are coarser and easier to cross with smaller donations]]: GUSD (2 decimals) makes inflation attacks 10^16x cheaper than 18-decimal equivalents
- [[tokens with more than 18 decimals trigger arithmetic overflow in intermediate calculations causing transaction reversion rather than precision loss]]: YAM-V2 (24 decimals); hard DoS via revert rather than silent rounding; distinct failure mode from low-decimal
- [[rebasing token supply changes create free arbitrage in AMMs that cache reserves because cached values diverge from actual token balances after each rebase]]: AMPL/stETH daily rebase creates predictable free arbitrage for first post-rebase sync caller
- [[tokens with per-transfer maximum caps silently revert large liquidations allowing undercollateralized positions to persist until manually split into smaller transactions]]: GoodDollar transfer cap; large liquidations revert; chunked liquidation logic rarely implemented
- [[flash-mintable tokens expose protocols that use totalSupply for governance weight or price calculation to temporary supply inflation attacks within a single transaction]]: DAI flash mint to uint256.max; governance quorum attacks via denominator inflation
- [[USDT zero-first approval requirement breaks protocols that directly update allowances to non-zero values without first resetting to zero]]: USDT reverts on approve with non-zero existing allowance; breaks DEX routers and aggregators
- [[non-standard permit implementations that do not revert on signature failure enable silent gasless approval bypass when callers assume permit either succeeds or reverts]]: DAI/RAI/GLM permit silently returns instead of reverting; downstream transferFrom fails with misleading error
- [[zero-value transfer and approval reverts create silent integration failures in protocols that use boundary-amount operations]]: BNB reverts on approve(addr, 0), LEND on zero transfer; conflicts with USDT zero-first pattern
- [[non-string metadata encoding in ERC-20 tokens breaks standard ABI decoding of name and symbol fields]]: MKR uses bytes32 for name/symbol; standard string ABI decoding fails
- [[ERC-20 representations of native currency on L1 and L2 chains create double-spending vulnerabilities when protocols handle both native and ERC-20 paths]]: Celo/Polygon/zkSync native currency ERC-20 wrappers; critical Uniswap V4 vulnerability on Celo
- [[code injection via malicious ERC-20 token name attributes enables frontend exploitation including private key extraction]]: JavaScript in token name fields; EtherDelta private key extraction; cross-layer on-chain-to-frontend attack
- [[cUSDCv3 max-uint256 transfer semantics break vault accounting by silently transferring less than the specified amount]]: type(uint256).max treated as "transfer actual balance"; distinct from fee-on-transfer
- [[transfer amount fidelity cannot be assumed for arbitrary ERC-20 tokens because four distinct mechanisms cause actual received amounts to differ from specified amounts]]: synthesis of fee-on-transfer, max-uint256 reinterpretation, and transfer caps; balance-diff measurement as universal defense
- [[lending protocol liquidation transfer failures have three distinct mechanisms that each require different defensive patterns]]: taxonomy of global pauses, address blocklists, and transfer caps as distinct liquidation failure mechanisms
### Approval Incompatibility
- [[ERC-20 approval behaviors are mutually incompatible across major tokens making universal approval handling impossible without token-specific branching or Permit2]]: USDT zero-first, BNB zero-value revert, OZ zero-address revert, and non-standard permit create irreconcilable approval conflicts; Permit2 as resolution
### Standard ERC Vulnerabilities
- [[ERC-20 approve front-running allows a racing spender to withdraw both the old and new allowance amounts]]: multiple withdrawal attack via allowance race, open since 2017; USDT zero-first mitigates this but breaks integrations
- [[ERC-20 tokens sent to contracts without callback support are permanently lost because transfer does not verify recipient capability]]: $201M+ documented loss from tokens sent to non-ERC-20-aware contracts
- [[ERC-777 arbitrary hook assignment via ERC-1820 registry enables attacker-controlled callbacks on victim contracts]]: arbitrary call vulnerabilities used to register malicious ERC-777 hooks
- [[ERC-4626 fee-on-transfer token incompatibility breaks vault accounting because received amount differs from specified amount]]: fee-on-transfer tokens cause systematic share over-issuance in ERC-4626 vaults; $500K STA cascade documented
- [[ERC-3156 flash loan standard allows arbitrary initiators to drain unsuspecting contracts that have pre-approved lenders]]: any caller can trigger flash loan with arbitrary borrower if borrower has lender approval
- [[ERC-3156 side entrance attack allows borrowers to deposit flash-loaned funds back into the lender pool to steal liquidity]]: deposit-instead-of-repayment when lender uses push-based repayment
- [[ERC-7579 malicious modules can permanently lock modular smart accounts by reverting on uninstallation]]: hooks that revert on preCheck or prevent uninstallation permanently freeze accounts; enriched with ERC-7484 registry singleton risk
## Gas & Infrastructure
- [[EIP-1153 transient storage persists across call frames within a transaction enabling cross-call state leakage]]: SIR.trading $355K exploit from residual transient storage values in subsequent callbacks
- [[EIP-1153 TSTORE lacks the minimum gas requirement of SSTORE enabling reentrancy at lower gas thresholds]]: transient-storage reentrancy guards can be bypassed within 2300 gas transfer stipend
- [[EIP-2929 warm and cold storage access costs create gas-limit dependent reentrancy guard failures in contracts using hardcoded gas amounts]]: EIP-2929's cold SLOAD increase to 2100 gas broke contracts relying on 2300 gas stipend protection
## ZK Integration
- [[ZK bridge verifiers are vulnerable to proof replay when public inputs are not bound to transaction-specific parameters]]: valid proof submitted with modified receiver/amount; also: verification key manipulation, under-constrained bridge circuits
- [[zkEVM type classification determines compatibility-performance tradeoff with distinct security implications at each level]]: Type 1-4 spectrum; Type 4 adds compiler trust boundary; gas modifications break security assumptions
## L2 / Rollup Security
- [[optimistic rollups can finalize invalid state when all challengers are censored or offline during the challenge period]]: 1-of-N honest watcher assumption collapses under sequencer censorship; reactive model's fundamental failure mode
- [[L2 sequencer centralization creates systemic liveness censorship and regulatory risks]]: single sequencer creates liveness failure, censorship, and regulatory shutdown risk; 59.4% of 32 documented incidents are sequencer disruptions
- [[forced inclusion mechanisms in optimistic rollups are insufficient against sequencer state manipulation attacks]]: state manipulation front-running breaks the forced-inclusion censorship bypass; no guaranteed withdrawal path from L2 DeFi
- [[L2 upgrade authority creates a security council governance tradeoff between rapid incident response and centralized fund control]]: Stage 1 vs Stage 2 governance tension; 86% of L2s allow instant upgrades without exit windows; Munchables Blast rollback debate adds transaction reversal as a second centralization axis
- [[DA-saturation and prover killer attacks exploit mismatches between EVM gas costs and ZK proving costs to create L2-specific DoS]]: 2025-discovered rollup-specific DoS classes exploiting blob capacity and proving cost asymmetry
- [[ZK rollup soundness bugs represent the primary failure mode when cryptographic validity proof generation can be manipulated]]: proving system correctness failure enables invalid state finalization; Solana ZK ElGamal June 2025
- [[metamorphic contract patterns remain exploitable on L2s that have not adopted EIP-6780 Cancun changes]]: SELFDESTRUCT semantic divergence across chains enables bait-and-switch redeploys where L1 restrictions don't apply
- [[bridge upgrade transactions are a distinct exploit vector when upgrade logic introduces verification threshold bugs]]: Nomad ($190M, 0x00 root) and Ronin 2024 ($12M, vote threshold) demonstrate upgrades as the vulnerability introduction vector
- [[newer EVM opcodes introduced in recent forks are disproportionately buggy across implementations because implementations lag specification maturity]]: 26 bugs in 9 EVM implementations; 7.21% of deployed contracts affected; PUSH0/TSTORE/MCOPY disproportionate
## Lending & Liquidation
- [[lending protocol liquidation mechanisms fail through five distinct mechanisms each requiring a separate defensive pattern]]: synthesis of market-driven failure, fixed bonus revert, pause asymmetry, borrower front-running, and self-liquidation; extended with three operational sub-classes
- [[lending protocols depend on utilization-based interest rate curves that create depositor-trapping risk at 100% utilization]]: depositor stranding at full utilization
- [[liquidation cascades in lending protocols create self-reinforcing price collapse through forced selling feedback loops]]: forced selling feedback loop during market stress
- [[bad debt accumulation in lending protocols occurs when liquidations fail to clear underwater positions during extreme market events]]: socialized losses when liquidation fails
- [[borrower front-running of liquidators via tiny repayments creates denial of service against liquidation mechanisms]]: mempool-based DoS against liquidation via dust repayments
- [[fixed liquidation bonus causes revert below the bonus threshold preventing liquidation of positions that most need clearing]]: fixed bonus arithmetic inverts the incentive: most underwater positions become unliquidatable
- [[lending protocols must never pause repayments while leaving liquidations active because borrowers cannot repay to avoid unfair liquidation]]: asymmetric pause creates captive liquidation condition
- [[liquidation denial of service through callback reverts collateral hiding and data structure corruption constitutes a distinct vulnerability sub-class beyond incentive failures]]: 13 operational DoS mechanisms preventing liquidation execution
- [[unfair liquidation vulnerabilities arise when protocol design creates information or timing asymmetry between borrowers and liquidators]]: 11 timing/information asymmetry patterns enabling unfair liquidation
- [[no grace period after protocol unpause enables unfair immediate liquidation of borrowers who could not repay during the pause]]: absence of post-unpause grace period creates race condition favoring liquidator bots
See [[economic-security]] for nonlinear insolvency risk modeling, recursive borrowing leverage analysis, and liquidation cascade dynamics.
## Stablecoin
- [[algorithmic stablecoin death spirals are triggered by reflexive depegging where falling price reduces demand accelerating the fall]]: Terra/UST reflexive collapse mechanism
- [[delta-neutral stablecoins face funding rate inversion risk when perpetual markets turn negative]]: Ethena USDe's novel funding rate risk
## Bridge & Cross-Chain
- [[unrevoked cross-validator signing allowlists create residual bridge compromise paths after their intended use expires]]: Ronin $624M; off-chain RPC allowlist granting cross-entity signing authority that expired Dec 2021 but was never removed; fifth signature obtained without direct key compromise
- [[granting cross-chain relay contracts owner privileges over administrative contracts creates a circular exploit path where arbitrary message execution can modify the execution authorization system]]: architectural anti-pattern where relay executor owns keeper registry; any dispatch vulnerability converts to authorization takeover; structural root cause of the Poly Network exploit
- [[cross-chain relay contracts must not hold administrative privileges over the contracts that govern relay authorization]]: privilege separation principle; relay executor must not own the authorization registry; derived from Poly Network post-mortem as the architectural-layer defense above tactical mitigations
- [[mint-burn asymmetry in bridges enables unlimited token minting when destination minting occurs without verified source-chain locking]]: verification gap enabling unbounded minting
- [[safeTransferFrom wrappers using raw call instead of code-existence-verified dispatch allow silent success on zero-address and non-contract targets]]: raw call() vs functionCall() with extcodesize check; implementation variant determines whether address(0) reverts or silently succeeds
- [[bridge finality assumptions create reorganization attack risk when relays occur before source chain confirms]]: premature relay creates reorg attack window
## Composability & Systemic
- [[DeFi composability creates systemic exploit propagation risk because interconnected protocols transform local failures into cascades]]: November 2025 cascade: Balancer → Euler → Morpho → Lista; now includes code-inheritance cascades as a fourth propagation mechanism distinct from oracle/collateral/liquidity dependency
- [[yield aggregator strategy composition inherits vulnerabilities from every underlying protocol in the stack]]: composed risk from multi-protocol strategy chains; three inheritance directions: downward (aggregator inherits underlying flaw), upward (lending protocol inherits vault share accounting flaw), horizontal (independent aggregators converge on same flawed oracle design)
- [[permissionless market registration in yield aggregators creates implicit trust of attacker-controlled contracts enabling reentrancy via reward distribution callbacks]]: Penpie $27M canonical case
- [[LST depeg risk creates liquidation cascades in lending protocols that accept liquid staking tokens as collateral]]: LST depeg propagation into lending health factors
- [[rebasing token balance increases cause accounting errors in protocols that cache balances without accounting for daily rebases]]: stETH-style rebasing breaks balance-caching protocols
- [[ERC-4626 vault share price manipulation via direct token donation exploits the share-to-asset ratio in newly deployed vaults]]: first-depositor attack on standardized vault share pricing
See [[economic-security]] for cross-protocol contagion channels and systemic risk cascade modeling.
## Restaking
- [[restaking compounds validator slashing risk by applying multiple independent slashing conditions to the same staked capital]]: compounding slashing across N AVS services
- [[AVS-defined slashing conditions can slash honest operators due to buggy or overly punitive slashing logic]]: protocol bugs causing unintended honest operator slashing
## Governance
- [[low-participation governance votes enable protocol parameter manipulation through flash loan voting power]]: flash-loan-funded governance capture at low quorum; Build Finance DAO ($470K) and GreenField DAO ($31M)
- [[allowing governance voting and execution in the same transaction makes any governance system unconditionally vulnerable to flash loan attack regardless of quorum threshold]]: Beanstalk: compound structure (no snapshot + emergency bypass + minimum delay) created precisely stageable exploit; 78% quorum met by flash-borrowing $1B; quorum and delay are parametric controls that fail against transient voting power
- [[malicious governance proposal injection via CREATE2 and SELFDESTRUCT allows attackers to swap approved code with malicious code between proposal approval and execution]]: Tornado Cash (May 2023): CREATE2 metamorphism replaced approved bytecode post-vote
- [[emergency governance functions designed for protocol protection become the highest-value attack surface when they bypass timelock delays]]: structural paradox: emergency bypass is identical power for legitimate use and for attackers
- [[governance timelocks that block emergency fixes create a known-vulnerable window where protocol operators can observe ongoing exploitation without the ability to respond]]: the symmetric constraint: the same delay that prevents malicious changes prevents emergency patches; Compound's 7-day cycle was irremediable during a live $147M exploit
- [[OpenZeppelin TimelockController proposals remain executable indefinitely after the delay expires creating persistent unauthorized execution windows]]: no built-in expiration; stale proposals executable months after approval
- [[slow token accumulation attacks on governance succeed by amassing unilateral control below detection thresholds when snapshot protections block flash loans]]: Compound 2024 ($24M): open-market accumulation (five wallets, 81% quorum) combined with ByBit hot wallet custodial delegations (230,333 COMP, >50% quorum); two distinct stealth mechanisms that jointly bypass all on-chain governance defenses
See [[economic-security]] for governance capture cost modeling across acquisition methods and defense mechanisms.
## Cross-Cutting Synthesis Patterns
- [[temporal gap between value accumulation and distribution creates an exploitable window for parameter manipulation timing attacks and dilution]]: synthesis: any accumulate-then-distribute design is vulnerable to manipulation during the gap (CLM fees, staking rewards, vault shares, JIT liquidity, bootstrap re-entry)
- [[authorization mechanisms without explicit expiration or revocation function as indefinite capability grants that persist beyond their intended context]]: synthesis: token approvals, signed capabilities, governance proposals, and EIP-7702 delegation all share the persistent-capability structure
## Vulnerability Distribution
- [[reentrancy oracle manipulation vault share inflation slippage precision loss and access control form the universal vulnerability kernel across all DeFi protocol types]]: six classes appearing in 15+ of 31 protocol types
- [[protocol complexity measured in composable DeFi primitives drives vulnerability surface area nonlinearly]]: synthetics (22 categories), CDP (21), staking pools (21) have outsized vulnerability surfaces
## Tensions
- Gas optimization caching vs. state freshness: caching computed values in storage (yETH `packed_vbs[]`) and choosing cheaper rounding directions (Bunni `mulDiv`) are gas optimizations that create security attack surfaces. Stale cached state after lifecycle transitions and compositional rounding drift are distinct vulnerability classes that both originate from cost-motivated design choices. See [[stale cached state after lifecycle transitions enables exploitation when initialization logic conflates fresh deployment with drained state]] and [[individually safe rounding directions can produce exploitable composite errors when applied across multiple operations in sequence]].
- Gas optimization vs. safety vs. DoS: [[gas optimization via unchecked blocks creates tension with arithmetic safety guarantees]] is now a three-sided tension: checked arithmetic (DoS via panic revert), unchecked arithmetic (value manipulation via silent wrapping), or explicit require-based validation (development cost). [[inline assembly bypasses solidity safety checks including type enforcement and overflow protection]] adds a fourth dimension with even fewer guardrails. Huff and raw EVM code trade compiler safety for gas efficiency, but the resulting vulnerability surface is strictly larger: 7 distinct vulnerability classes exist exclusively in low-level code because they are prevented by compiler-generated checks.
- Compiler protection reshapes but does not eliminate risk: [[solidity 0.8.0 introduced default arithmetic overflow protection making unchecked blocks the new attack surface]] eliminated most arithmetic bugs, but [[solidity 0.8 default checked arithmetic converts overflow from a value manipulation vulnerability into a denial-of-service vulnerability|converted the same conditions into DoS vectors]] while attackers also shifted to logic errors and business-specific vulnerabilities. The threat landscape is a balloon, squeezing one side inflates another.
- send/transfer deprecation creates a DoS/reentrancy tension: removing the 2300 gas stipend makes reentrancy defense the developer's responsibility while also expanding the DoS attack surface for callback recipients.
- Reentrancy defense vs. gas costs: the CEI pattern is free but limits composability; reentrancy locks cost gas but are more flexible; the deprecated send/transfer gas stipend was implicit defense but broke with EIP-1884.
- Compiler trust boundary: [[vyper eliminates entire solidity vulnerability classes by omitting inheritance operator overloading recursive functions and inline assembly]], yet the Curve exploit proved that compiler bugs can silently break reentrancy protection. Source-level auditing is necessary but insufficient.
- Compiler optimization vs. semantic preservation: most Solidity 0.8.x bugs are optimizer/codegen bugs. Optimization creates a wider bug surface, but disabling it increases gas costs and deployment size.
- Composability is simultaneously DeFi's greatest strength and its primary systemic risk. Every protocol integration adds a dependency, failures cascade through the stack.
- Restaking multiplies capital efficiency but compounds slashing risk. The fundamental tension between "one stake secures N services" and "one failure affects N services" persists.
- The stablecoin trilemma has no known resolution, every design sacrifices at least one of decentralization, stability, or capital efficiency.
- EIP-7702 invalidates the empirically strongest runtime exploit guard: [[EOA access control invariant is the single most effective runtime exploit guard blocking 18 of 27 distinct exploits in empirical study]] found tx.origin==msg.sender blocks 66.7% of exploits, but [[EIP-7702 tx.origin equals msg.sender check no longer prevents flash loan attacks because delegated EOAs can execute arbitrary contract logic while satisfying both identity checks]] structurally breaks this. Protocols must migrate to delegation-aware detection.
<!--
## Open Questions
- What percentage of post-0.8 exploits involve unchecked blocks vs. inline assembly vs. pure logic errors? [Partially answered: logic errors dominate at ~33% of incidents, but no construct-level decomposition separating unchecked blocks from inline assembly from pure logic errors exists in published data]
- Will cross-chain reentrancy via bridge callbacks become a significant attack vector? [Partially answered: bridge callbacks create the technical capability, but cross-chain state inconsistency and message verification failures are the larger threat vector in practice]
- Does via-IR have a fundamentally higher bug surface than Solidity's legacy codegen? [Partially answered: the bug surface is different rather than fundamentally larger, via-IR triggers distinct optimizer paths and Yul helper generation (see SOL-2026-1), but has not produced more total CVEs than legacy codegen]
- How does Vyper's Venom IR backend change the compiler bug surface compared to the legacy backend? [Partially answered: Venom remains experimental with heavy verification underway; the shift from AST-direct-to-bytecode to SSA-based IR fundamentally changes which optimization bugs are possible, but insufficient production data to characterize the new surface]
- Has EIP-7201 namespaced storage eliminated storage collision vulnerabilities in practice? [The vault has [[eip-7201 namespaced storage provides structured collision avoidance for upgradeable contracts]] describing the mechanism, but adoption rate and empirical impact on collision incidents remain unknown]
- Does SafeERC20 handle all documented weird ERC-20 behaviors or does it have systematic gaps? [The existing SafeERC20 note documents what it handles (missing return values, false-returning tokens, USDT zero-first); a systematic gap analysis against the full d-xo/weird-erc20 catalog would identify undefended behavior categories]
-->
---
Topics:
- [[index]]