[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EVBDQ4N06JFE2DQNH69CA5":3,"skill-same:01M7EVBDQ4N06JFE2DQNH69CA5":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7EVBDQ4N06JFE2DQNH69CA5","web3-audit",null,"Smart contract security audit — 10 DeFi bug classes (accounting desync, access control, incomplete path, off-by-one, oracle, ERC4626, reentrancy, flash loan, signature replay, proxy), pre-dive kill signals (TVL \u003C $500K etc), Foundry PoC template, grep patterns for each class, and real Immunefi paid examples. Use for any Solidity\u002FRust contract audit or when deciding whether a DeFi target is worth hunting.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fweb3-audit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: web3-audit\ndescription: Smart contract security audit — 10 DeFi bug classes (accounting desync, access control, incomplete path, off-by-one, oracle, ERC4626, reentrancy, flash loan, signature replay, proxy), pre-dive kill signals (TVL \u003C $500K etc), Foundry PoC template, grep patterns for each class, and real Immunefi paid examples. Use for any Solidity\u002FRust contract audit or when deciding whether a DeFi target is worth hunting.\nsources: public_research, community\n---\n\n# WEB3 SMART CONTRACT AUDIT\n\n10 bug classes. Pre-dive kill signals. Foundry PoC template. Real paid examples.\n\n---\n\n## PRE-DIVE KILL SIGNALS (check BEFORE any code review)\n\n> ZKsync lesson: $322M TVL + OZ audit + 750K LOC + 5 sessions = 0 findings. Large well-audited bridges are extremely hard.\n\n1. **TVL \u003C $500K** → max payout capped too low for effort\n2. **2+ top-tier audits** (Halborn, ToB, Cyfrin, OpenZeppelin) on simple protocol → bugs already found\n3. **Protocol \u003C 500 lines, single A→B→C flow** → minimal attack surface\n4. **Formula**: `max_realistic_payout = min(10% × TVL, program_cap)` — if \u003C $10K, skip\n\n**Soft kill:** OZ\u002FToB\u002FCyfrin audit on current version + codebase > 500K LOC → expect 40+ hours for maybe 1 finding. Only proceed if bounty floor > $50K AND you have protocol-specific expertise.\n\n**Target scoring (go if >= 6\u002F10):**\n- TVL > $10M: +2\n- Immunefi program with Critical >= $50K: +2\n- No top-tier audit on current version: +2\n- \u003C 30 days since deploy: +1\n- Protocol you've hunted before: +1\n- Source code + natspec comments: +1\n- Upgradeable proxies: +1\n\n---\n\n## THE ONE RULE\n\n> \"Read ALL sibling functions. If `vote()` has a modifier, check `poke()`, `reset()`, `harvest()`. The missing modifier on the sibling IS the bug.\"\n\nThis single rule explains 19% of all Critical findings.\n\n---\n\n## 1. ACCOUNTING STATE DESYNCHRONIZATION\n> #1 Critical bug class — 28% of all Criticals on Immunefi.\n\n### What It Is\nTwo state variables supposed to stay in sync. One code path updates A but forgets B. Later code reads both and makes decisions based on stale B.\n\n```\nReal Value = A - B\nIf A updated but B isn't → Real Value appears larger → phantom value\n```\n\n### Root Cause Patterns\n\n**Variant 1: Phantom Yield** (Yeet protocol — 35 duplicate reports)\n```solidity\nfunction startUnstake(uint256 amount) external {\n    totalSupply -= amount;  \u002F\u002F decremented BEFORE transfer\n    \u002F\u002F aToken.balanceOf(this) still reflects old value\n    \u002F\u002F yieldAmount = aToken.balanceOf - totalSupply = phantom yield\n}\n```\n\n**Variant 2: Fast Path Skips State Update** (Alchemix V3)\n```solidity\nfunction claimRedemption(uint256 tokenId) external {\n    if (transmuter.balance >= amount) {\n        transmuter.transfer(user, amount);\n        _burn(tokenId);\n        return;  \u002F\u002F EARLY RETURN — cumulativeEarmarked, _redemptionWeight, totalDebt never updated\n    }\n    \u002F\u002F Slow path: updates all state vars correctly\n    alchemist.redeem(...);\n}\n```\n\n**Variant 3: Update Happens in Wrong Order** (Alchemix)\n```solidity\nfunction deposit(uint256 amount) external {\n    _shares = (amount * totalShares) \u002F totalAssets;  \u002F\u002F calculated BEFORE deposit\n    totalAssets += amount;   \u002F\u002F assets added AFTER shares calculated → wrong rate\n}\n```\n\n### Grep Patterns\n```bash\n# Find all accounting variables\ngrep -rn \"totalSupply\\|totalShares\\|totalAssets\\|totalDebt\\|cumulativeReward\\|rewardPerShare\" contracts\u002F\n\n# Find all early returns in claim\u002Fredeem functions\ngrep -rn \"\\breturn\\b\" contracts\u002F -B3 | grep -B3 \"if\\b\"\n\n# For each early return: which state updates in normal path are skipped?\n```\n\n---\n\n## 2. ACCESS CONTROL\n> #2 Critical — 19% of Criticals. $953M lost in 2024 alone.\n\n### Variant 1: Missing Modifier on Sibling Function\n```solidity\nfunction vote(uint256 tokenId) external onlyNewEpoch(tokenId) {  \u002F\u002F guarded\nfunction reset(uint256 tokenId) external onlyNewEpoch(tokenId) { \u002F\u002F guarded\nfunction poke(uint256 tokenId) external {                         \u002F\u002F NO GUARD → infinite FLUX inflation\n}\n```\n\n### Variant 2: Wrong Check (Existence vs Ownership)\n```solidity\nfunction split(uint256 tokenId, uint256 amount) external {\n    _requireOwned(tokenId);  \u002F\u002F checks if token EXISTS, not if caller OWNS it\n    _burn(tokenId);\n    _mint(msg.sender, amount);  \u002F\u002F attacker steals tokens they don't own\n}\n```\n\n### Variant 3: Silent Modifier (if vs require)\n```solidity\n\u002F\u002F VULNERABLE — non-admin silently gets through:\nmodifier onlyAdmin() {\n    if (msg.sender == admin) {\n        _;  \u002F\u002F body only executes for admin, but non-admin doesn't revert\n    }\n}\n\u002F\u002F CORRECT: require(msg.sender == admin, \"Not admin\"); _;\n```\n\n### Variant 4: Uninitialized Proxy\n```solidity\nfunction initialize(address _owner) public {  \u002F\u002F MISSING: initializer modifier\n    owner = _owner;  \u002F\u002F anyone can call → become owner\n}\n\u002F\u002F Fix: constructor() { _disableInitializers(); }\n```\n\n### Grep Patterns\n```bash\n# Find sibling function families — do ALL have the same modifier set?\ngrep -rn \"function vote\\|function poke\\|function reset\\|function update\\|function claim\\|function harvest\" contracts\u002F -A2\n\n# Ownership check: existence vs ownership?\ngrep -rn \"_requireOwned\\|ownerOf\\|_isApprovedOrOwner\\|_checkAuthorized\" contracts\u002F -B5\n\n# Silent modifiers\ngrep -rn \"modifier\\b\" contracts\u002F -A8 | grep -B3 \"if (\" | grep -v \"require\\|revert\"\n\n# Uninitialized initializer\ngrep -rn \"function initialize\\b\" contracts\u002F -A3\ngrep -rn \"_disableInitializers()\" contracts\u002F\n```\n\n### Real Paid Examples\n\n| Protocol | Payout | Bug |\n|---|---|---|\n| Wormhole | $10M | Uninitialized UUPS proxy → anyone calls initialize() |\n| ZeroLend | n\u002Fa | split() uses existence check, not ownership check |\n| Alchemix | n\u002Fa | poke() missing onlyNewEpoch → infinite FLUX inflation |\n| Parity | $150M frozen | No access control on initWallet() in library |\n\n---\n\n## 3. INCOMPLETE CODE PATH\n> #3 Critical — 17% of Criticals.\n\n### The Function Family Comparison Test\n```\n1. List all state changes in function A (deposit\u002Fplace\u002Fcreate)\n2. List all state changes in function B (withdraw\u002Fupdate\u002Fcancel)\n3. For each state change in A: does B have the corresponding reverse?\n4. For each token transfer in A: does B have the corresponding refund?\nIf A does X but B doesn't do the reverse of X → BUG.\n```\n\n### Variant 1: Update Function Missing Refund (ThunderNFT)\n```solidity\nfunction place_order(OrderInput calldata order) external {\n    token.safeTransferFrom(msg.sender, address(this), order.price);  \u002F\u002F takes tokens\n    orders[orderId] = order;\n}\nfunction update_order(OrderInput calldata updatedOrder) external {\n    \u002F\u002F BUG: NO REFUND for sell orders when price decreases → tokens permanently stuck\n    orders[orderId] = updatedOrder;\n}\n```\n\n### Variant 2: Partial Fill Token Stuck (Plume)\n```solidity\nfunction swapForETH(uint256 amountIn) external {\n    token.safeTransferFrom(msg.sender, address(this), amountIn);\n    uint256 filled = dex.swap(amountIn);  \u002F\u002F partial fill possible\n    _refundExcessEth(amountIn - filled);  \u002F\u002F BUG: refunds ETH only, not ERC20\n}\n```\n\n### Variant 3: mint() Bypasses Check That deposit() Has (MetaPool)\n```solidity\nfunction deposit(uint256 assets, address receiver) public override {\n    shares = _deposit(assets, receiver);  \u002F\u002F includes receipt validation\n}\nfunction mint(uint256 shares, address receiver) public override {\n    assets = convertToAssets(shares);\n    _mint(receiver, shares);  \u002F\u002F MISSING: _deposit() validation → mints without receiving assets\n}\n```\n\n### Grep Patterns\n```bash\ngrep -rn \"function place_\\|function create_\\|function add_\\|function open_\" contracts\u002F -A5\ngrep -rn \"function update_\\|function modify_\\|function cancel_\" contracts\u002F -A5\ngrep -rn \"safeApprove\\b\" contracts\u002F    # safeApprove without zero-reset before\ngrep -rn \"delete\\b\" contracts\u002F -B5 -A5  # delete before operation completes\ngrep -rn \"function deposit\\|function mint\\|function withdraw\\|function redeem\" contracts\u002F -A10\n```\n\n---\n\n## 4. OFF-BY-ONE & BOUNDARY CONDITIONS\n> #4 High — 22% of Highs. Single character change. Massive impact.\n\n### Root Cause\n```solidity\n\u002F\u002F VeChain Stargate — post-exit reward drain:\nfunction _claimableDelegationPeriods(address delegator) internal view returns (uint256) {\n    if (endPeriod > nextClaimablePeriod) {  \u002F\u002F BUG: should be >=\n        return 0;  \u002F\u002F exited users get nothing\n    }\n    return nextClaimablePeriod - lastClaimedPeriod;  \u002F\u002F rewards for period AFTER exit\n}\n```\n\n### Mental Test for Every Comparison\n> For every `if (A > B)`: \"What happens when A == B?\" Is that correct?\n\n### 6 Boundary Locations to Check\n1. Period\u002FEpoch boundaries: `>` vs `>=` at period end\n2. Time-based locks: does `block.timestamp == deadline` lock or unlock?\n3. Loop break conditions: `break` with `>` vs `>=`\n4. Array index boundaries: `i \u003C= array.length` (should be `i \u003C array.length`)\n5. Amount\u002Fbalance boundaries: `>= amount` allows exact full withdrawal?\n6. Rounding\u002Fprecision: can any input produce 0 output that should be non-zero?\n\n### Grep Patterns\n```bash\n# Boundaries in comparisons\ngrep -rn \"Period\\|Epoch\\|Round\\|Deadline\\|period\\|epoch\\|deadline\" contracts\u002F -A3 | grep \"[\u003C>][^=]\"\n\n# Loop breaks\ngrep -rn \"\\bbreak\\b\" contracts\u002F -B10\n\n# Off-by-one in array access\ngrep -rn \"\\.length\\s*-\\s*1\\|i\\s*\u003C=\\s*.*\\.length\\b\" contracts\u002F\n```\n\n---\n\n## 5. ORACLE \u002F PRICE MANIPULATION\n> 12% of all reports. Largest individual payouts. $117M Mango, $70M Curve.\n\n### Bug A: Missing Staleness Check (most common)\n```solidity\n\u002F\u002F VULNERABLE:\n(, int256 price,,,) = priceFeed.latestRoundData();\nreturn uint256(price);  \u002F\u002F If Chainlink node goes down, stale price returned indefinitely\n\n\u002F\u002F CORRECT:\n(, int256 price,, uint256 updatedAt,) = priceFeed.latestRoundData();\nrequire(block.timestamp - updatedAt \u003C= MAX_PRICE_AGE, \"Stale price\");\nrequire(price > 0, \"Invalid price\");\n```\n\n### Bug B: Missing Confidence Interval (Pyth)\n```solidity\n\u002F\u002F VULNERABLE:\nPythStructs.Price memory p = pyth.getPriceUnsafe(priceFeed);\nreturn p.price;  \u002F\u002F ignores p.conf (confidence interval)\n\n\u002F\u002F CORRECT:\nrequire(p.conf * 10 \u003C= uint64(p.price), \"Price too uncertain\");\n\u002F\u002F conf > 10% of price = untrustworthy\n```\n\n### Bug C: TWAP Too Short (flash loan manipulatable)\n```solidity\n\u002F\u002F VULNERABLE: 60-second TWAP\nuint32[] memory secondsAgos = new uint32[](2);\nsecondsAgos[0] = 60; secondsAgos[1] = 0;\n\u002F\u002F Flash loan can shift price for entire 60s window\n\n\u002F\u002F CORRECT: 1800s minimum TWAP (30 min)\n```\n\n### Bug D: Single-Source Oracle\n```solidity\n\u002F\u002F VULNERABLE: only Uniswap spot price\nuint price = getUniswapSpotPrice(token);  \u002F\u002F flash loan manipulatable\n\n\u002F\u002F CORRECT: Chainlink primary, Uniswap TWAP as fallback, require close agreement\n```\n\n### Grep Patterns\n```bash\n# Missing staleness check\ngrep -rn \"latestRoundData\" contracts\u002F -A5 | grep -v \"updatedAt\\|timestamp\"\n\n# Pyth price usage — confidence interval checked?\ngrep -rn \"getPriceUnsafe\\|getPrice\\b\" contracts\u002F -A8 | grep -v \"conf\\|confidence\"\n\n# TWAP windows — short TWAP flag\ngrep -rn \"secondsAgo\\|TWAP\\|cardinality\" contracts\u002F -A5\n```\n\n---\n\n## 6. ERC4626 VAULT ATTACKS\n\n### Exchange Rate Manipulation (near-empty vault)\n```solidity\n\u002F\u002F VULNERABLE — first depositor attack:\n\u002F\u002F 1. Attacker deposits 1 wei → gets 1 share\n\u002F\u002F 2. Attacker donates large amount directly (transfer, not deposit)\n\u002F\u002F 3. Exchange rate: 1 share = (1 + donation) assets\n\u002F\u002F 4. Victim deposits → rounds down to 0 shares → free donation to attacker\n\n\u002F\u002F CORRECT: virtual shares (OpenZeppelin v4.9+)\nfunction _decimalsOffset() internal view virtual override returns (uint8) {\n    return 9;  \u002F\u002F add 1e9 virtual shares + assets to prevent manipulation\n}\n```\n\n### ERC4626 Transfer (moves shares but not stake\u002Flock records)\n```solidity\n\u002F\u002F VULNERABLE: shares transferred, but lock records stay with original owner\n\u002F\u002F → shares stuck, can't redeem → permanent freeze (Belong pattern)\nfunction transfer(address to, uint256 amount) external override {\n    _transfer(msg.sender, to, amount);  \u002F\u002F moves shares\n    \u002F\u002F MISSING: transfer lock record from msg.sender to `to`\n}\n```\n\n### Grep Patterns\n```bash\ngrep -rn \"function transfer\\|function transferFrom\" contracts\u002F -A15\ngrep -rn \"function deposit\\|function mint\\|function withdraw\\|function redeem\" contracts\u002F -A10\n```\n\n---\n\n## 7. REENTRANCY\n> 2016–present. CEI pattern prevents it. Still found in DeFi.\n\n### Variants\n- **Single-function**: attacker re-enters same function before state updated\n- **Cross-function**: re-enters a sibling function with stale state\n- **Cross-contract**: re-enters via a callback to another protocol\n- **Read-only**: re-enters a view function that returns stale data used by attacker\n\n### Root Cause Pattern\n```solidity\n\u002F\u002F VULNERABLE (effects after interaction):\nfunction withdraw(uint256 amount) external {\n    require(balances[msg.sender] >= amount);\n    (bool success,) = msg.sender.call{value: amount}(\"\");  \u002F\u002F INTERACTION first\n    require(success);\n    balances[msg.sender] -= amount;  \u002F\u002F EFFECT after → reentrancy window\n}\n\n\u002F\u002F CORRECT (CEI — Checks, Effects, Interactions):\nfunction withdraw(uint256 amount) external {\n    require(balances[msg.sender] >= amount);  \u002F\u002F CHECK\n    balances[msg.sender] -= amount;            \u002F\u002F EFFECT\n    (bool success,) = msg.sender.call{value: amount}(\"\");  \u002F\u002F INTERACTION last\n    require(success);\n}\n```\n\n### Grep Patterns\n```bash\n# External calls before state updates\ngrep -rn \"\\.call{value\\|safeTransfer\\|transfer(\" contracts\u002F -B10 | grep -v \"require\\|revert\"\n\n# Missing nonReentrant modifier on critical functions\ngrep -rn \"function withdraw\\|function redeem\\|function claim\" contracts\u002F -A2 | grep -v \"nonReentrant\"\n\n# Storage slot for reentrancy guard\ngrep -rn \"nonReentrant\\|ReentrancyGuard\\|_notEntered\" contracts\u002F\n```\n\n---\n\n## 8. FLASH LOAN ATTACKS\n\n### Oracle Manipulation via Flash Loan\n```solidity\n\u002F\u002F Attack flow:\n\u002F\u002F 1. Borrow $100M from Aave flash loan\n\u002F\u002F 2. Dump token in Uniswap pool → crash spot price\n\u002F\u002F 3. Protocol reads Uniswap spot → undercollateralized loans accepted\n\u002F\u002F 4. Borrow max against cheap collateral\n\u002F\u002F 5. Repay flash loan, keep profits\n```\n\n### Price Oracle Sanity Checks (what to look for)\n```bash\ngrep -rn \"getReserves\\|getAmountsOut\\|slot0\\b\" contracts\u002F -A5\n# spot price from reserves = manipulatable with flash loan\n# slot0 = Uniswap V3 spot price = manipulatable\n```\n\n---\n\n## 9. SIGNATURE REPLAY\n\n### Missing Nonce\n```solidity\n\u002F\u002F VULNERABLE:\nfunction permit(address owner, address spender, uint256 value,\n                uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {\n    bytes32 hash = keccak256(abi.encodePacked(owner, spender, value, deadline));\n    \u002F\u002F MISSING: nonce not included → same signature usable multiple times\n    require(ecrecover(hash, v, r, s) == owner);\n}\n```\n\n### Missing Chain ID\n```solidity\n\u002F\u002F VULNERABLE: signature valid on mainnet AND testnet AND all forks\nbytes32 hash = keccak256(abi.encodePacked(params));\n\u002F\u002F MISSING: block.chainid not in hash → works on any chain\n```\n\n### Grep Patterns\n```bash\ngrep -rn \"ecrecover\\|ECDSA\\.recover\" contracts\u002F -B20\n# Check: does the signed hash include nonce + chainId + contract address?\n\ngrep -rn \"nonce\\|_nonces\\|nonces\\[\" contracts\u002F\n```\n\n---\n\n## 10. PROXY \u002F UPGRADE ISSUES\n\n### Storage Collision\n```solidity\n\u002F\u002F Implementation and proxy share storage layout\n\u002F\u002F Proxy slot 0: _owner\n\u002F\u002F Implementation slot 0: _initialized\n\u002F\u002F → writing to _initialized overwrites _owner\n```\n\n### Uninitialized Implementation\n```solidity\n\u002F\u002F If implementation can be initialized directly → anyone becomes owner of implementation\n\u002F\u002F Attack: call initialize() on implementation contract → call upgradeTo() → replace logic\n```\n\n### delegatecall to User-Controlled Address\n```solidity\nfunction execute(address target, bytes calldata data) external onlyOwner {\n    target.delegatecall(data);  \u002F\u002F target is validated, but what if owner is compromised?\n}\n```\n\n### Grep Patterns\n```bash\n# UUPS initialization protection\ngrep -rn \"function initialize\\b\\|_disableInitializers\\|initializer\" contracts\u002F\n\n# Delegate call\ngrep -rn \"delegatecall\\b\" contracts\u002F -B3 -A5\n\n# Storage layout — proxy uses EIP-1967 slots?\ngrep -rn \"0x360894\\|EIP1967\\|_IMPLEMENTATION_SLOT\" contracts\u002F\n```\n\n---\n\n## FOUNDRY POC TEMPLATE\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"forge-std\u002FTest.sol\";\nimport \"..\u002Fsrc\u002FVulnerableContract.sol\";\n\ncontract ExploitTest is Test {\n    VulnerableContract target;\n    address attacker = makeAddr(\"attacker\");\n    address victim = makeAddr(\"victim\");\n\n    function setUp() public {\n        \u002F\u002F Fork mainnet at specific block\n        vm.createSelectFork(\"mainnet\", BLOCK_NUMBER);\n\n        \u002F\u002F Deploy or load target\n        target = VulnerableContract(TARGET_ADDRESS);\n\n        \u002F\u002F Fund accounts\n        deal(address(token), attacker, INITIAL_BALANCE);\n        deal(address(token), victim, VICTIM_BALANCE);\n    }\n\n    function test_exploit() public {\n        console.log(\"Attacker balance before:\", token.balanceOf(attacker));\n\n        vm.startPrank(attacker);\n\n        \u002F\u002F Step 1: Setup conditions\n        \u002F\u002F Step 2: Execute exploit\n        \u002F\u002F Step 3: Verify impact\n\n        vm.stopPrank();\n\n        console.log(\"Attacker balance after:\", token.balanceOf(attacker));\n        assertGt(token.balanceOf(attacker), INITIAL_BALANCE, \"Exploit failed\");\n    }\n}\n```\n\n### Key Foundry Cheatcodes\n```solidity\nvm.prank(address)           \u002F\u002F next call from address\nvm.startPrank(address)      \u002F\u002F all calls from address until stopPrank()\nvm.deal(address, amount)    \u002F\u002F set ETH balance\ndeal(token, address, amount) \u002F\u002F set ERC20 balance\nvm.warp(timestamp)          \u002F\u002F set block.timestamp\nvm.roll(blockNumber)        \u002F\u002F set block.number\nvm.createSelectFork(\"mainnet\", blockNumber)  \u002F\u002F fork mainnet\nvm.expectRevert(bytes)      \u002F\u002F next call should revert\nvm.label(address, \"name\")   \u002F\u002F label for trace output\nvm.assume(condition)        \u002F\u002F fuzz: discard inputs where false\n```\n\n### Running Tests\n```bash\n# Run specific test\nforge test --match-test test_exploit -vvvv\n\n# Run with fork\nforge test --match-test test_exploit -vvvv --fork-url $MAINNET_RPC\n\n# Gas report\nforge test --gas-report\n\n# Coverage\nforge coverage --report summary\n```\n\n---\n\n## Related Skills & Chains\n\n- **`meme-coin-audit`** — When the target is a meme coin \u002F SPL token rather than a DeFi protocol. Workflow primitive: pre-dive kill signals diverge — this skill's \"TVL \u003C $500K skip\" doesn't apply to meme coins where the rug check (mint authority, freeze authority, LP lock) is the entire audit; route to `meme-coin-audit` instead.\n- **`triage-validation`** — When a contract finding is ready to be filed on Immunefi. Workflow primitive: Immunefi has its own report format, but the impact-validated, chain-end-to-end discipline of `triage-validation` still applies; run the 7Q gate against the Foundry PoC before submitting.\n- **`report-writing`** — When writing the Immunefi report body. Workflow primitive: `report-writing`'s Immunefi template (with Foundry PoC, root cause code snippet, quantified economic impact) is the body skeleton this skill's findings feed into.\n- **`offensive-osint`** — When auditing a protocol's off-chain attack surface (frontend, admin API, RPC gateways). Workflow primitive: on-chain audit is this skill's job; any web2 component of the protocol (web-frontend, admin panel, indexer API) routes to `offensive-osint` for recon.\n- **`bb-methodology`** — When deciding whether to dive at all. Workflow primitive: PART 0 of `bb-methodology` confirms engagement (web3 bug bounty \u002F private audit \u002F smart-contract review); this skill's pre-dive kill signals replace the standard scoring rubric for that engagement type.\n\n---\n\n## Operator Notes (Claude-BugHunter)\n\n> Engagement-derived + 2026-specific additions to the vendored foundation.\n> Wisdom from real authorized engagements + Phase 2 verification across\n> this repo's 31+ skill-area live tests. The upstream content covers the WHAT;\n> this layer covers the WHEN-IT-WORKS-vs-WHEN-IT-DOESN'T.\n\n### Bug classes still paying in 2026\n\nFlash-loan attacks remain top-paid on Immunefi (top 5 in 2024-2026 by bounty). The economic primitive — borrow $50M, manipulate price oracle, drain pool, repay — keeps reappearing because new protocols keep shipping with composability assumptions that don't hold under flash-loaned imbalance.\n\nReentrancy IS still paying because new protocols keep shipping with ERC-777 \u002F hooks \u002F callbacks. Don't assume the class is dead — the 2023-2025 paid corpus contains 40+ reentrancy bugs against post-Checks-Effects-Interactions codebases (cross-function reentrancy, read-only reentrancy via view functions called during state-mid-flight).\n\nOracle manipulation: still paid heavily but harder. Most projects use Chainlink price feeds now; the attack target is the SECONDARY oracle most projects also use (TWAP from a low-liquidity Uniswap V2 pair, the protocol's own internal oracle, a stale fallback path). Audit the failover chain, not just the primary feed.\n\n### What's new since the vendored content was written\n\n- **EIP-1153 (transient storage)** — introduced in 2024. New reentrancy classes: transient-storage reads cached across the same transaction can desync from persistent storage. Audit any `tload`\u002F`tstore` usage for read-after-external-call.\n- **EIP-7702 (Pectra hard fork 2025)** — added EOA-to-smart-account upgrades. New ATO-like primitives via re-delegation: an EOA signed-once can delegate to a contract that the attacker controls, then signature replay across delegations.\n- **Account abstraction (ERC-4337 bundlers)** — paymaster sponsorship abuse and bundler griefing. Paymaster contracts that don't enforce strict sender allowlists drain on first call.\n- **ZK-rollup bridge bugs** — proof-replay across rollups, off-chain prover compromise, sequencer censorship leading to forced-inclusion edge cases.\n- **LST\u002FLRT depeg dynamics** — liquid-staking and liquid-restaking tokens that assume 1:1 peg under loss conditions; oracle assumes peg, market reflects depeg, liquidation logic breaks.\n\n### Tool stack for 2026\n\nFoundry remains the test framework. `forge test --gas-report --debug` for invariant testing; `forge fuzz` for property-based testing; `forge inspect` for storage-layout audits. Slither + Echidna for static + fuzz. Mythril for symbolic execution on smaller contracts. tenderly.co for forking + simulation (best UX for replicating attacks against mainnet state).\n\nFor Solana: anchor framework, sealevel-attacks corpus (curated PoCs by anchor maintainers), soteria-sec \u002F sec3 scanner. For Move (Aptos, Sui): move-prover, aptos-cli `aptos move test`.\n\nFor cross-chain: hyperlane and LayerZero each have audit-tooling repos; bridge bugs require simulating both endpoints, not just one.\n\n### Where pre-dive kill signals matter\n\nTVL under $500K isn't worth the audit time unless the bounty floor is high. Audit firm already covered it = low ROI unless you find what they missed — look at the audit-report scope-exclusion section for what they EXPLICITLY didn't audit (oracles, governance, off-chain components, frontend, the admin path).\n\nMultisig signers > 5 + timelock > 48h = low rug-pull risk; if your finding requires team-malicious assumptions, it's low-impact and likely out of scope per Immunefi's \"centralization risk\" exclusion. Read the program brief — most Immunefi programs explicitly downgrade or reject findings that assume admin malice.\n\n### Reporting discipline\n\nImmunefi requires Foundry PoC. Submission without PoC is auto-rejected. Submission with a PoC that requires manual setup (\"first deploy this, then call that\") usually gets downgraded — the PoC should be a single `forge test` invocation that proves the impact, with explicit `assertEq` on the drained balance \u002F minted token \u002F corrupted state.\n\nSeverity claims must use Immunefi's severity matrix exactly; don't invent severities. The matrix gates on direct economic loss percentage of TVL — a critical against a $500K protocol pays differently than a critical against a $500M one. Read the program's specific severity assignment before claiming Critical.\n","# WEB3 SMART CONTRACT AUDIT\n\n10 bug classes. Pre-dive kill signals. Foundry PoC template. Real paid examples.\n\n---\n\n## PRE-DIVE KILL SIGNALS (check BEFORE any code review)\n\n> ZKsync lesson: $322M TVL + OZ audit + 750K LOC + 5 sessions = 0 findings. Large well-audited bridges are extremely hard.\n\n1. **TVL \u003C $500K** → max payout capped too low for effort\n2. **2+ top-tier audits** (Halborn, ToB, Cyfrin, OpenZeppelin) on simple protocol → bugs already found\n3. **Protocol \u003C 500 lines, single A→B→C flow** → minimal attack surface\n4. **Formula**: `max_realistic_payout = min(10% × TVL, program_cap)` — if \u003C $10K, skip\n\n**Soft kill:** OZ\u002FToB\u002FCyfrin audit on current version + codebase > 500K LOC → expect 40+ hours for maybe 1 finding. Only proceed if bounty floor > $50K AND you have protocol-specific expertise.\n\n**Target scoring (go if >= 6\u002F10):**\n- TVL > $10M: +2\n- Immunefi program with Critical >= $50K: +2\n- No top-tier audit on current version: +2\n- \u003C 30 days since deploy: +1\n- Protocol you've hunted before: +1\n- Source code + natspec comments: +1\n- Upgradeable proxies: +1\n\n---\n\n## THE ONE RULE\n\n> \"Read ALL sibling functions. If `vote()` has a modifier, check `poke()`, `reset()`, `harvest()`. The missing modifier on the sibling IS the bug.\"\n\nThis single rule explains 19% of all Critical findings.\n\n---\n\n## 1. ACCOUNTING STATE DESYNCHRONIZATION\n> #1 Critical bug class — 28% of all Criticals on Immunefi.\n\n### What It Is\nTwo state variables supposed to stay in sync. One code path updates A but forgets B. Later code reads both and makes decisions based on stale B.\n\n```\nReal Value = A - B\nIf A updated but B isn't → Real Value appears larger → phantom value\n```\n\n### Root Cause Patterns\n\n**Variant 1: Phantom Yield** (Yeet protocol — 35 duplicate reports)\n```solidity\nfunction startUnstake(uint256 amount) external {\n    totalSupply -= amount;  \u002F\u002F decremented BEFORE transfer\n    \u002F\u002F aToken.balanceOf(this) still reflects old value\n    \u002F\u002F yieldAmount = aToken.balanceOf - totalSupply = phantom yield\n}\n```\n\n**Variant 2: Fast Path Skips State Update** (Alchemix V3)\n```solidity\nfunction claimRedemption(uint256 tokenId) external {\n    if (transmuter.balance >= amount) {\n        transmuter.transfer(user, amount);\n        _burn(tokenId);\n        return;  \u002F\u002F EARLY RETURN — cumulativeEarmarked, _redemptionWeight, totalDebt never updated\n    }\n    \u002F\u002F Slow path: updates all state vars correctly\n    alchemist.redeem(...);\n}\n```\n\n**Variant 3: Update Happens in Wrong Order** (Alchemix)\n```solidity\nfunction deposit(uint256 amount) external {\n    _shares = (amount * totalShares) \u002F totalAssets;  \u002F\u002F calculated BEFORE deposit\n    totalAssets += amount;   \u002F\u002F assets added AFTER shares calculated → wrong rate\n}\n```\n\n### Grep Patterns\n```bash\n# Find all accounting variables\ngrep -rn \"totalSupply\\|totalShares\\|totalAssets\\|totalDebt\\|cumulativeReward\\|rewardPerShare\" contracts\u002F\n\n# Find all early returns in claim\u002Fredeem functions\ngrep -rn \"\\breturn\\b\" contracts\u002F -B3 | grep -B3 \"if\\b\"\n\n# For each early return: which state updates in normal path are skipped?\n```\n\n---\n\n## 2. ACCESS CONTROL\n> #2 Critical — 19% of Criticals. $953M lost in 2024 alone.\n\n### Variant 1: Missing Modifier on Sibling Function\n```solidity\nfunction vote(uint256 tokenId) external onlyNewEpoch(tokenId) {  \u002F\u002F guarded\nfunction reset(uint256 tokenId) external onlyNewEpoch(tokenId) { \u002F\u002F guarded\nfunction poke(uint256 tokenId) external {                         \u002F\u002F NO GUARD → infinite FLUX inflation\n}\n```\n\n### Variant 2: Wrong Check (Existence vs Ownership)\n```solidity\nfunction split(uint256 tokenId, uint256 amount) external {\n    _requireOwned(tokenId);  \u002F\u002F checks if token EXISTS, not if caller OWNS it\n    _burn(tokenId);\n    _mint(msg.sender, amount);  \u002F\u002F attacker steals tokens they don't own\n}\n```\n\n### Variant 3: Silent Modifier (if vs require)\n```solidity\n\u002F\u002F VULNERABLE — non-admin silently gets through:\nmodifier onlyAdmin() {\n    if (msg.sender == admin) {\n        _;  \u002F\u002F body only executes for admin, but non-admin doesn't revert\n    }\n}\n\u002F\u002F CORRECT: require(msg.sender == admin, \"Not admin\"); _;\n```\n\n### Variant 4: Uninitialized Proxy\n```solidity\nfunction initialize(address _owner) public {  \u002F\u002F MISSING: initializer modifier\n    owner = _owner;  \u002F\u002F anyone can call → become owner\n}\n\u002F\u002F Fix: constructor() { _disableInitializers(); }\n```\n\n### Grep Patterns\n```bash\n# Find sibling function families — do ALL have the same modifier set?\ngrep -rn \"function vote\\|function poke\\|function reset\\|function update\\|function claim\\|function harvest\" contracts\u002F -A2\n\n# Ownership check: existence vs ownership?\ngrep -rn \"_requireOwned\\|ownerOf\\|_isApprovedOrOwner\\|_checkAuthorized\" contracts\u002F -B5\n\n# Silent modifiers\ngrep -rn \"modifier\\b\" contracts\u002F -A8 | grep -B3 \"if (\" | grep -v \"require\\|revert\"\n\n# Uninitialized initializer\ngrep -rn \"function initialize\\b\" contracts\u002F -A3\ngrep -rn \"_disableInitializers()\" contracts\u002F\n```\n\n### Real Paid Examples\n\n| Protocol | Payout | Bug |\n|---|---|---|\n| Wormhole | $10M | Uninitialized UUPS proxy → anyone calls initialize() |\n| ZeroLend | n\u002Fa | split() uses existence check, not ownership check |\n| Alchemix | n\u002Fa | poke() missing onlyNewEpoch → infinite FLUX inflation |\n| Parity | $150M frozen | No access control on initWallet() in library |\n\n---\n\n## 3. INCOMPLETE CODE PATH\n> #3 Critical — 17% of Criticals.\n\n### The Function Family Comparison Test\n```\n1. List all state changes in function A (deposit\u002Fplace\u002Fcreate)\n2. List all state changes in function B (withdraw\u002Fupdate\u002Fcancel)\n3. For each state change in A: does B have the corresponding reverse?\n4. For each token transfer in A: does B have the corresponding refund?\nIf A does X but B doesn't do the reverse of X → BUG.\n```\n\n### Variant 1: Update Function Missing Refund (ThunderNFT)\n```solidity\nfunction place_order(OrderInput calldata order) external {\n    token.safeTransferFrom(msg.sender, address(this), order.price);  \u002F\u002F takes tokens\n    orders[orderId] = order;\n}\nfunction update_order(OrderInput calldata updatedOrder) external {\n    \u002F\u002F BUG: NO REFUND for sell orders when price decreases → tokens permanently stuck\n    orders[orderId] = updatedOrder;\n}\n```\n\n### Variant 2: Partial Fill Token Stuck (Plume)\n```solidity\nfunction swapForETH(uint256 amountIn) external {\n    token.safeTransferFrom(msg.sender, address(this), amountIn);\n    uint256 filled = dex.swap(amountIn);  \u002F\u002F partial fill possible\n    _refundExcessEth(amountIn - filled);  \u002F\u002F BUG: refunds ETH only, not ERC20\n}\n```\n\n### Variant 3: mint() Bypasses Check That deposit() Has (MetaPool)\n```solidity\nfunction deposit(uint256 assets, address receiver) public override {\n    shares = _deposit(assets, receiver);  \u002F\u002F includes receipt validation\n}\nfunction mint(uint256 shares, address receiver) public override {\n    assets = convertToAssets(shares);\n    _mint(receiver, shares);  \u002F\u002F MISSING: _deposit() validation → mints without receiving assets\n}\n```\n\n### Grep Patterns\n```bash\ngrep -rn \"function place_\\|function create_\\|function add_\\|function open_\" contracts\u002F -A5\ngrep -rn \"function update_\\|function modify_\\|function cancel_\" contracts\u002F -A5\ngrep -rn \"safeApprove\\b\" contracts\u002F    # safeApprove without zero-reset before\ngrep -rn \"delete\\b\" contracts\u002F -B5 -A5  # delete before operation completes\ngrep -rn \"function deposit\\|function mint\\|function withdraw\\|function redeem\" contracts\u002F -A10\n```\n\n---\n\n## 4. OFF-BY-ONE & BOUNDARY CONDITIONS\n> #4 High — 22% of Highs. Single character change. Massive impact.\n\n### Root Cause\n```solidity\n\u002F\u002F VeChain Stargate — post-exit reward drain:\nfunction _claimableDelegationPeriods(address delegator) internal view returns (uint256) {\n    if (endPeriod > nextClaimablePeriod) {  \u002F\u002F BUG: should be >=\n        return 0;  \u002F\u002F exited users get nothing\n    }\n    return nextClaimablePeriod - lastClaimedPeriod;  \u002F\u002F rewards for period AFTER exit\n}\n```\n\n### Mental Test for Every Comparison\n> For every `if (A > B)`: \"What happens when A == B?\" Is that correct?\n\n### 6 Boundary Locations to Check\n1. Period\u002FEpoch boundaries: `>` vs `>=` at period end\n2. Time-based locks: does `block.timestamp == deadline` lock or unlock?\n3. Loop break conditions: `break` with `>` vs `>=`\n4. Array index boundaries: `i \u003C= array.length` (should be `i \u003C array.length`)\n5. Amount\u002Fbalance boundaries: `>= amount` allows exact full withdrawal?\n6. Rounding\u002Fprecision: can any input produce 0 output that should be non-zero?\n\n### Grep Patterns\n```bash\n# Boundaries in comparisons\ngrep -rn \"Period\\|Epoch\\|Round\\|Deadline\\|period\\|epoch\\|deadline\" contracts\u002F -A3 | grep \"[\u003C>][^=]\"\n\n# Loop breaks\ngrep -rn \"\\bbreak\\b\" contracts\u002F -B10\n\n# Off-by-one in array access\ngrep -rn \"\\.length\\s*-\\s*1\\|i\\s*\u003C=\\s*.*\\.length\\b\" contracts\u002F\n```\n\n---\n\n## 5. ORACLE \u002F PRICE MANIPULATION\n> 12% of all reports. Largest individual payouts. $117M Mango, $70M Curve.\n\n### Bug A: Missing Staleness Check (most common)\n```solidity\n\u002F\u002F VULNERABLE:\n(, int256 price,,,) = priceFeed.latestRoundData();\nreturn uint256(price);  \u002F\u002F If Chainlink node goes down, stale price returned indefinitely\n\n\u002F\u002F CORRECT:\n(, int256 price,, uint256 updatedAt,) = priceFeed.latestRoundData();\nrequire(block.timestamp - updatedAt \u003C= MAX_PRICE_AGE, \"Stale price\");\nrequire(price > 0, \"Invalid price\");\n```\n\n### Bug B: Missing Confidence Interval (Pyth)\n```solidity\n\u002F\u002F VULNERABLE:\nPythStructs.Price memory p = pyth.getPriceUnsafe(priceFeed);\nreturn p.price;  \u002F\u002F ignores p.conf (confidence interval)\n\n\u002F\u002F CORRECT:\nrequire(p.conf * 10 \u003C= uint64(p.price), \"Price too uncertain\");\n\u002F\u002F conf > 10% of price = untrustworthy\n```\n\n### Bug C: TWAP Too Short (flash loan manipulatable)\n```solidity\n\u002F\u002F VULNERABLE: 60-second TWAP\nuint32[] memory secondsAgos = new uint32[](2);\nsecondsAgos[0] = 60; secondsAgos[1] = 0;\n\u002F\u002F Flash loan can shift price for entire 60s window\n\n\u002F\u002F CORRECT: 1800s minimum TWAP (30 min)\n```\n\n### Bug D: Single-Source Oracle\n```solidity\n\u002F\u002F VULNERABLE: only Uniswap spot price\nuint price = getUniswapSpotPrice(token);  \u002F\u002F flash loan manipulatable\n\n\u002F\u002F CORRECT: Chainlink primary, Uniswap TWAP as fallback, require close agreement\n```\n\n### Grep Patterns\n```bash\n# Missing staleness check\ngrep -rn \"latestRoundData\" contracts\u002F -A5 | grep -v \"updatedAt\\|timestamp\"\n\n# Pyth price usage — confidence interval checked?\ngrep -rn \"getPriceUnsafe\\|getPrice\\b\" contracts\u002F -A8 | grep -v \"conf\\|confidence\"\n\n# TWAP windows — short TWAP flag\ngrep -rn \"secondsAgo\\|TWAP\\|cardinality\" contracts\u002F -A5\n```\n\n---\n\n## 6. ERC4626 VAULT ATTACKS\n\n### Exchange Rate Manipulation (near-empty vault)\n```solidity\n\u002F\u002F VULNERABLE — first depositor attack:\n\u002F\u002F 1. Attacker deposits 1 wei → gets 1 share\n\u002F\u002F 2. Attacker donates large amount directly (transfer, not deposit)\n\u002F\u002F 3. Exchange rate: 1 share = (1 + donation) assets\n\u002F\u002F 4. Victim deposits → rounds down to 0 shares → free donation to attacker\n\n\u002F\u002F CORRECT: virtual shares (OpenZeppelin v4.9+)\nfunction _decimalsOffset() internal view virtual override returns (uint8) {\n    return 9;  \u002F\u002F add 1e9 virtual shares + assets to prevent manipulation\n}\n```\n\n### ERC4626 Transfer (moves shares but not stake\u002Flock records)\n```solidity\n\u002F\u002F VULNERABLE: shares transferred, but lock records stay with original owner\n\u002F\u002F → shares stuck, can't redeem → permanent freeze (Belong pattern)\nfunction transfer(address to, uint256 amount) external override {\n    _transfer(msg.sender, to, amount);  \u002F\u002F moves shares\n    \u002F\u002F MISSING: transfer lock record from msg.sender to `to`\n}\n```\n\n### Grep Patterns\n```bash\ngrep -rn \"function transfer\\|function transferFrom\" contracts\u002F -A15\ngrep -rn \"function deposit\\|function mint\\|function withdraw\\|function redeem\" contracts\u002F -A10\n```\n\n---\n\n## 7. REENTRANCY\n> 2016–present. CEI pattern prevents it. Still found in DeFi.\n\n### Variants\n- **Single-function**: attacker re-enters same function before state updated\n- **Cross-function**: re-enters a sibling function with stale state\n- **Cross-contract**: re-enters via a callback to another protocol\n- **Read-only**: re-enters a view function that returns stale data used by attacker\n\n### Root Cause Pattern\n```solidity\n\u002F\u002F VULNERABLE (effects after interaction):\nfunction withdraw(uint256 amount) external {\n    require(balances[msg.sender] >= amount);\n    (bool success,) = msg.sender.call{value: amount}(\"\");  \u002F\u002F INTERACTION first\n    require(success);\n    balances[msg.sender] -= amount;  \u002F\u002F EFFECT after → reentrancy window\n}\n\n\u002F\u002F CORRECT (CEI — Checks, Effects, Interactions):\nfunction withdraw(uint256 amount) external {\n    require(balances[msg.sender] >= amount);  \u002F\u002F CHECK\n    balances[msg.sender] -= amount;            \u002F\u002F EFFECT\n    (bool success,) = msg.sender.call{value: amount}(\"\");  \u002F\u002F INTERACTION last\n    require(success);\n}\n```\n\n### Grep Patterns\n```bash\n# External calls before state updates\ngrep -rn \"\\.call{value\\|safeTransfer\\|transfer(\" contracts\u002F -B10 | grep -v \"require\\|revert\"\n\n# Missing nonReentrant modifier on critical functions\ngrep -rn \"function withdraw\\|function redeem\\|function claim\" contracts\u002F -A2 | grep -v \"nonReentrant\"\n\n# Storage slot for reentrancy guard\ngrep -rn \"nonReentrant\\|ReentrancyGuard\\|_notEntered\" contracts\u002F\n```\n\n---\n\n## 8. FLASH LOAN ATTACKS\n\n### Oracle Manipulation via Flash Loan\n```solidity\n\u002F\u002F Attack flow:\n\u002F\u002F 1. Borrow $100M from Aave flash loan\n\u002F\u002F 2. Dump token in Uniswap pool → crash spot price\n\u002F\u002F 3. Protocol reads Uniswap spot → undercollateralized loans accepted\n\u002F\u002F 4. Borrow max against cheap collateral\n\u002F\u002F 5. Repay flash loan, keep profits\n```\n\n### Price Oracle Sanity Checks (what to look for)\n```bash\ngrep -rn \"getReserves\\|getAmountsOut\\|slot0\\b\" contracts\u002F -A5\n# spot price from reserves = manipulatable with flash loan\n# slot0 = Uniswap V3 spot price = manipulatable\n```\n\n---\n\n## 9. SIGNATURE REPLAY\n\n### Missing Nonce\n```solidity\n\u002F\u002F VULNERABLE:\nfunction permit(address owner, address spender, uint256 value,\n                uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {\n    bytes32 hash = keccak256(abi.encodePacked(owner, spender, value, deadline));\n    \u002F\u002F MISSING: nonce not included → same signature usable multiple times\n    require(ecrecover(hash, v, r, s) == owner);\n}\n```\n\n### Missing Chain ID\n```solidity\n\u002F\u002F VULNERABLE: signature valid on mainnet AND testnet AND all forks\nbytes32 hash = keccak256(abi.encodePacked(params));\n\u002F\u002F MISSING: block.chainid not in hash → works on any chain\n```\n\n### Grep Patterns\n```bash\ngrep -rn \"ecrecover\\|ECDSA\\.recover\" contracts\u002F -B20\n# Check: does the signed hash include nonce + chainId + contract address?\n\ngrep -rn \"nonce\\|_nonces\\|nonces\\[\" contracts\u002F\n```\n\n---\n\n## 10. PROXY \u002F UPGRADE ISSUES\n\n### Storage Collision\n```solidity\n\u002F\u002F Implementation and proxy share storage layout\n\u002F\u002F Proxy slot 0: _owner\n\u002F\u002F Implementation slot 0: _initialized\n\u002F\u002F → writing to _initialized overwrites _owner\n```\n\n### Uninitialized Implementation\n```solidity\n\u002F\u002F If implementation can be initialized directly → anyone becomes owner of implementation\n\u002F\u002F Attack: call initialize() on implementation contract → call upgradeTo() → replace logic\n```\n\n### delegatecall to User-Controlled Address\n```solidity\nfunction execute(address target, bytes calldata data) external onlyOwner {\n    target.delegatecall(data);  \u002F\u002F target is validated, but what if owner is compromised?\n}\n```\n\n### Grep Patterns\n```bash\n# UUPS initialization protection\ngrep -rn \"function initialize\\b\\|_disableInitializers\\|initializer\" contracts\u002F\n\n# Delegate call\ngrep -rn \"delegatecall\\b\" contracts\u002F -B3 -A5\n\n# Storage layout — proxy uses EIP-1967 slots?\ngrep -rn \"0x360894\\|EIP1967\\|_IMPLEMENTATION_SLOT\" contracts\u002F\n```\n\n---\n\n## FOUNDRY POC TEMPLATE\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"forge-std\u002FTest.sol\";\nimport \"..\u002Fsrc\u002FVulnerableContract.sol\";\n\ncontract ExploitTest is Test {\n    VulnerableContract target;\n    address attacker = makeAddr(\"attacker\");\n    address victim = makeAddr(\"victim\");\n\n    function setUp() public {\n        \u002F\u002F Fork mainnet at specific block\n        vm.createSelectFork(\"mainnet\", BLOCK_NUMBER);\n\n        \u002F\u002F Deploy or load target\n        target = VulnerableContract(TARGET_ADDRESS);\n\n        \u002F\u002F Fund accounts\n        deal(address(token), attacker, INITIAL_BALANCE);\n        deal(address(token), victim, VICTIM_BALANCE);\n    }\n\n    function test_exploit() public {\n        console.log(\"Attacker balance before:\", token.balanceOf(attacker));\n\n        vm.startPrank(attacker);\n\n        \u002F\u002F Step 1: Setup conditions\n        \u002F\u002F Step 2: Execute exploit\n        \u002F\u002F Step 3: Verify impact\n\n        vm.stopPrank();\n\n        console.log(\"Attacker balance after:\", token.balanceOf(attacker));\n        assertGt(token.balanceOf(attacker), INITIAL_BALANCE, \"Exploit failed\");\n    }\n}\n```\n\n### Key Foundry Cheatcodes\n```solidity\nvm.prank(address)           \u002F\u002F next call from address\nvm.startPrank(address)      \u002F\u002F all calls from address until stopPrank()\nvm.deal(address, amount)    \u002F\u002F set ETH balance\ndeal(token, address, amount) \u002F\u002F set ERC20 balance\nvm.warp(timestamp)          \u002F\u002F set block.timestamp\nvm.roll(blockNumber)        \u002F\u002F set block.number\nvm.createSelectFork(\"mainnet\", blockNumber)  \u002F\u002F fork mainnet\nvm.expectRevert(bytes)      \u002F\u002F next call should revert\nvm.label(address, \"name\")   \u002F\u002F label for trace output\nvm.assume(condition)        \u002F\u002F fuzz: discard inputs where false\n```\n\n### Running Tests\n```bash\n# Run specific test\nforge test --match-test test_exploit -vvvv\n\n# Run with fork\nforge test --match-test test_exploit -vvvv --fork-url $MAINNET_RPC\n\n# Gas report\nforge test --gas-report\n\n# Coverage\nforge coverage --report summary\n```\n\n---\n\n## Related Skills & Chains\n\n- **`meme-coin-audit`** — When the target is a meme coin \u002F SPL token rather than a DeFi protocol. Workflow primitive: pre-dive kill signals diverge — this skill's \"TVL \u003C $500K skip\" doesn't apply to meme coins where the rug check (mint authority, freeze authority, LP lock) is the entire audit; route to `meme-coin-audit` instead.\n- **`triage-validation`** — When a contract finding is ready to be filed on Immunefi. Workflow primitive: Immunefi has its own report format, but the impact-validated, chain-end-to-end discipline of `triage-validation` still applies; run the 7Q gate against the Foundry PoC before submitting.\n- **`report-writing`** — When writing the Immunefi report body. Workflow primitive: `report-writing`'s Immunefi template (with Foundry PoC, root cause code snippet, quantified economic impact) is the body skeleton this skill's findings feed into.\n- **`offensive-osint`** — When auditing a protocol's off-chain attack surface (frontend, admin API, RPC gateways). Workflow primitive: on-chain audit is this skill's job; any web2 component of the protocol (web-frontend, admin panel, indexer API) routes to `offensive-osint` for recon.\n- **`bb-methodology`** — When deciding whether to dive at all. Workflow primitive: PART 0 of `bb-methodology` confirms engagement (web3 bug bounty \u002F private audit \u002F smart-contract review); this skill's pre-dive kill signals replace the standard scoring rubric for that engagement type.\n\n---\n\n## Operator Notes (Claude-BugHunter)\n\n> Engagement-derived + 2026-specific additions to the vendored foundation.\n> Wisdom from real authorized engagements + Phase 2 verification across\n> this repo's 31+ skill-area live tests. The upstream content covers the WHAT;\n> this layer covers the WHEN-IT-WORKS-vs-WHEN-IT-DOESN'T.\n\n### Bug classes still paying in 2026\n\nFlash-loan attacks remain top-paid on Immunefi (top 5 in 2024-2026 by bounty). The economic primitive — borrow $50M, manipulate price oracle, drain pool, repay — keeps reappearing because new protocols keep shipping with composability assumptions that don't hold under flash-loaned imbalance.\n\nReentrancy IS still paying because new protocols keep shipping with ERC-777 \u002F hooks \u002F callbacks. Don't assume the class is dead — the 2023-2025 paid corpus contains 40+ reentrancy bugs against post-Checks-Effects-Interactions codebases (cross-function reentrancy, read-only reentrancy via view functions called during state-mid-flight).\n\nOracle manipulation: still paid heavily but harder. Most projects use Chainlink price feeds now; the attack target is the SECONDARY oracle most projects also use (TWAP from a low-liquidity Uniswap V2 pair, the protocol's own internal oracle, a stale fallback path). Audit the failover chain, not just the primary feed.\n\n### What's new since the vendored content was written\n\n- **EIP-1153 (transient storage)** — introduced in 2024. New reentrancy classes: transient-storage reads cached across the same transaction can desync from persistent storage. Audit any `tload`\u002F`tstore` usage for read-after-external-call.\n- **EIP-7702 (Pectra hard fork 2025)** — added EOA-to-smart-account upgrades. New ATO-like primitives via re-delegation: an EOA signed-once can delegate to a contract that the attacker controls, then signature replay across delegations.\n- **Account abstraction (ERC-4337 bundlers)** — paymaster sponsorship abuse and bundler griefing. Paymaster contracts that don't enforce strict sender allowlists drain on first call.\n- **ZK-rollup bridge bugs** — proof-replay across rollups, off-chain prover compromise, sequencer censorship leading to forced-inclusion edge cases.\n- **LST\u002FLRT depeg dynamics** — liquid-staking and liquid-restaking tokens that assume 1:1 peg under loss conditions; oracle assumes peg, market reflects depeg, liquidation logic breaks.\n\n### Tool stack for 2026\n\nFoundry remains the test framework. `forge test --gas-report --debug` for invariant testing; `forge fuzz` for property-based testing; `forge inspect` for storage-layout audits. Slither + Echidna for static + fuzz. Mythril for symbolic execution on smaller contracts. tenderly.co for forking + simulation (best UX for replicating attacks against mainnet state).\n\nFor Solana: anchor framework, sealevel-attacks corpus (curated PoCs by anchor maintainers), soteria-sec \u002F sec3 scanner. For Move (Aptos, Sui): move-prover, aptos-cli `aptos move test`.\n\nFor cross-chain: hyperlane and LayerZero each have audit-tooling repos; bridge bugs require simulating both endpoints, not just one.\n\n### Where pre-dive kill signals matter\n\nTVL under $500K isn't worth the audit time unless the bounty floor is high. Audit firm already covered it = low ROI unless you find what they missed — look at the audit-report scope-exclusion section for what they EXPLICITLY didn't audit (oracles, governance, off-chain components, frontend, the admin path).\n\nMultisig signers > 5 + timelock > 48h = low rug-pull risk; if your finding requires team-malicious assumptions, it's low-impact and likely out of scope per Immunefi's \"centralization risk\" exclusion. Read the program brief — most Immunefi programs explicitly downgrade or reject findings that assume admin malice.\n\n### Reporting discipline\n\nImmunefi requires Foundry PoC. Submission without PoC is auto-rejected. Submission with a PoC that requires manual setup (\"first deploy this, then call that\") usually gets downgraded — the PoC should be a single `forge test` invocation that proves the impact, with explicit `assertEq` on the drained balance \u002F minted token \u002F corrupted state.\n\nSeverity claims must use Immunefi's severity matrix exactly; don't invent severities. The matrix gates on direct economic loss percentage of TVL — a critical against a $500K protocol pays differently than a critical against a $500M one. Read the program's specific severity assignment before claiming Critical.\n",{"name":5,"sources":24,"description":7},"public_research, community","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fweb3-audit",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill web3-audit",{"tool":39,"command":40},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill web3-audit",{"tool":42,"command":43},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill web3-audit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fweb3-audit\u002FSKILL.md",true,[],[48,56,61,68,75,82],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":55},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":57,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":55},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":55},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":55},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":55},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":55},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]