web3-audit

skillupstreamWeb3۲۳ کیلوبایت۱۶ بخش

‏‏audit امنیتی قرارداد هوشمند — ‏۱۰ کلاس باگ DeFi ‏(desync مربوط به accounting، ‏کنترل دسترسی، ‏مسیر ناقص، ‏off-by-one، ‏oracle، ‏ERC4626، ‏reentrancy، ‏flash loan، ‏replay مربوط به امضا، ‏proxy)، ‏سیگنال‌های kill مربوط به pre-dive ‏(TVL < ‏۵۰۰هزار دلار و غیره)، ‏تمپلیت PoC مربوط به Foundry، ‏الگوهای grep برای هر کلاس و مثال‌های واقعی پرداخت‌شده‌ی Immunefi. ‏برای هر audit مربوط به قرارداد Solidity/Rust استفاده کن یا وقتی تصمیم می‌گیری هدف DeFi ارزش hunt دارد یا نه.

توضیح انگلیسی اصلی (مرجع)

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 < $500K etc), Foundry PoC template, grep patterns for each class, and real Immunefi paid examples. Use for any Solidity/Rust contract audit or when deciding whether a DeFi target is worth hunting.

نقشه‌ی ساختار اسکیل

web3-auditWeb3 · ۱۶ بخش۱نمای کلی و کاربرد۲سطح حمله وسیگنال‌ها۳بخش تکمیلی۴بخش تکمیلی۵بخش تکمیلی۶بخش تکمیلی۷بخش تکمیلی۸بخش تکمیلی۹بخش تکمیلی۱۰بخش تکمیلی۱۱بخش تکمیلی۱۲بخش تکمیلی۱۳بخش تکمیلی۱۴بخش تکمیلی۱۵دروازه‌ی اعتبارسنجی۱۶ابزار و نکاتعملیاتی
نمای کلی و کاربرد · ۱۴سطح حمله و سیگنال‌ها · ۱دروازه‌ی اعتبارسنجی · ۱

روی هر گره کلیک کنید تا به بخش مربوطه بروید؛ دکمه‌ی «سورس MD» در هدر هر بخش، متن اصلی را با شماره‌ی خط می‌آورد.

بخش‌های اسکیل

هر بخش با عنوان فارسی، نوع محتوا و توضیح فارسی نمایش داده شده. روی «سورس MD» کلیک کنید تا متن اصلی انگلیسی با شماره‌ی خطوط فایل در نمایشگر کناری باز شود.

۱

نمای کلی و کاربرد

Introduction
ترجمه‌ی کامل ✓بخش ۱ از ۱۶

توضیح کلی، دامنه‌ی پوشش و زمان به‌کارگیری اسکیل

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

# WEB3 SMART CONTRACT AUDIT

10 bug classes. Pre-dive kill signals. Foundry PoC template. Real paid examples.


۲

سطح حمله و سیگنال‌ها

PRE-DIVE KILL SIGNALS (check BEFORE any code review)
ترجمه‌ی کامل ✓بخش ۲ از ۱۶

نشانه‌های URL، header، JS و tech stack که نشان می‌دهد این تکنیک اینجا جواب می‌دهد

‏درس ZKsync: ‏TVL مربوط به ۳۲۲ میلیون دلار + ‏audit مربوط به OZ + ‏۷۵۰هزار LOC + ‏۵ session = ‏۰ یافته. ‏bridgeهای بزرگ خوب-audit‌شده فوق‌العاده سخت‌اند.
  1. ‏‏TVL < ‏۵۰۰ هزار دلار ← ‏سقف payout واقعی برای تلاش خیلی کم است
  2. ‏‏۲+ audit سطح-بالا ‏(Halborn، ‏ToB، ‏Cyfrin، ‏OpenZeppelin) روی پروتکل ساده ← ‏باگ‌ها قبلاً پیدا شده‌اند
  3. ‏‏پروتکل < ‏۵۰۰ خط، ‏جریان تکی A←B←C ← ‏سطح حمله حداقلی
  4. ‏فرمول: max_realistic_payout = min(10% × TVL, program_cap) — اگر < ‏۱۰ هزار دلار، رد کن

‏kill نرم: ‏audit مربوط به OZ/ToB/Cyfrin روی نسخه‌ی فعلی + ‏کدبیس > ‏۵۰۰هزار LOC ← ‏انتظار +۴۰ ساعت برای شاید ۱ یافته. ‏فقط ادامه بده اگر کف bounty > ‏۵۰ هزار دلار و تخصص مخصوص-پروتکل داری.

‏امتیازدهی هدف ‏(برو اگر >= ‏۶/۱۰):

  • ‏‏TVL > ‏۱۰ میلیون دلار: ‏+۲
  • ‏برنامه‌ی Immunefi با Critical >= ‏۵۰ هزار دلار: ‏+۲
  • ‏بدون audit سطح-بالا روی نسخه‌ی فعلی: ‏+۲
  • ‏‏< ‏۳۰ روز از deploy: ‏+۱
  • ‏پروتکلی که قبلاً hunt کرده‌ای: ‏+۱
  • ‏سورس‌کد + ‏کامنت‌های natspec: ‏+۱
  • ‏‏proxyهای قابل-ارتقا: ‏+۱
۳

بخش تکمیلی

THE ONE RULE
ترجمه‌ی کامل ✓بخش ۳ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

"Read ALL sibling functions. If vote() has a modifier, check poke(), reset(), harvest(). The missing modifier on the sibling IS the bug."

This single rule explains 19% of all Critical findings.


۴

بخش تکمیلی

1. ACCOUNTING STATE DESYNCHRONIZATION
ترجمه‌ی کامل ✓بخش ۴ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏کلاس باگ Critical شماره‌ی ۱ — ‏۲۸٪ همه‌ی Criticalها روی Immunefi.
‏چیست

‏دو متغیر state که باید sync بمانند. ‏یک مسیر کد A را به‌روز می‌کند ولی B را فراموش می‌کند. ‏کد بعدی هر دو را می‌خواند و بر اساس B مربوط به stale تصمیم می‌گیرد.

Real Value = A - B
If A updated but B isn't → Real Value appears larger → phantom value
‏‏الگوهای علت ریشه‌ای

‏واریانت ۱: ‏Yield مربوط به Phantom ‏(پروتکل Yeet — ‏۳۵ گزارش تکراری)

function startUnstake(uint256 amount) external {
    totalSupply -= amount;  // decremented BEFORE transfer
    // aToken.balanceOf(this) still reflects old value
    // yieldAmount = aToken.balanceOf - totalSupply = phantom yield
}

‏واریانت ۲: ‏مسیر سریع به‌روزرسانی State را رد می‌کند ‏(Alchemix V3)

function claimRedemption(uint256 tokenId) external {
    if (transmuter.balance >= amount) {
        transmuter.transfer(user, amount);
        _burn(tokenId);
        return;  // EARLY RETURN — cumulativeEarmarked, _redemptionWeight, totalDebt never updated
    }
    // Slow path: updates all state vars correctly
    alchemist.redeem(...);
}

‏واریانت ۳: ‏به‌روزرسانی به ترتیب غلط اتفاق می‌افتد ‏(Alchemix)

function deposit(uint256 amount) external {
    _shares = (amount * totalShares) / totalAssets;  // calculated BEFORE deposit
    totalAssets += amount;   // assets added AFTER shares calculated → wrong rate
}
‏‏الگوهای Grep
# Find all accounting variables
grep -rn "totalSupply\|totalShares\|totalAssets\|totalDebt\|cumulativeReward\|rewardPerShare" contracts/

# Find all early returns in claim/redeem functions
grep -rn "\breturn\b" contracts/ -B3 | grep -B3 "if\b"

# For each early return: which state updates in normal path are skipped?
۵

بخش تکمیلی

2. ACCESS CONTROL
ترجمه‌ی کامل ✓بخش ۵ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

#2 Critical — 19% of Criticals. $953M lost in 2024 alone.
Variant 1: Missing Modifier on Sibling Function
function vote(uint256 tokenId) external onlyNewEpoch(tokenId) {  // guarded
function reset(uint256 tokenId) external onlyNewEpoch(tokenId) { // guarded
function poke(uint256 tokenId) external {                         // NO GUARD → infinite FLUX inflation
}
Variant 2: Wrong Check (Existence vs Ownership)
function split(uint256 tokenId, uint256 amount) external {
    _requireOwned(tokenId);  // checks if token EXISTS, not if caller OWNS it
    _burn(tokenId);
    _mint(msg.sender, amount);  // attacker steals tokens they don't own
}
Variant 3: Silent Modifier (if vs require)
// VULNERABLE — non-admin silently gets through:
modifier onlyAdmin() {
    if (msg.sender == admin) {
        _;  // body only executes for admin, but non-admin doesn't revert
    }
}
// CORRECT: require(msg.sender == admin, "Not admin"); _;
Variant 4: Uninitialized Proxy
function initialize(address _owner) public {  // MISSING: initializer modifier
    owner = _owner;  // anyone can call → become owner
}
// Fix: constructor() { _disableInitializers(); }
Grep Patterns
# Find sibling function families — do ALL have the same modifier set?
grep -rn "function vote\|function poke\|function reset\|function update\|function claim\|function harvest" contracts/ -A2

# Ownership check: existence vs ownership?
grep -rn "_requireOwned\|ownerOf\|_isApprovedOrOwner\|_checkAuthorized" contracts/ -B5

# Silent modifiers
grep -rn "modifier\b" contracts/ -A8 | grep -B3 "if (" | grep -v "require\|revert"

# Uninitialized initializer
grep -rn "function initialize\b" contracts/ -A3
grep -rn "_disableInitializers()" contracts/
Real Paid Examples
ProtocolPayoutBug
Wormhole$10MUninitialized UUPS proxy → anyone calls initialize()
ZeroLendn/asplit() uses existence check, not ownership check
Alchemixn/apoke() missing onlyNewEpoch → infinite FLUX inflation
Parity$150M frozenNo access control on initWallet() in library

۶

بخش تکمیلی

3. INCOMPLETE CODE PATH
ترجمه‌ی کامل ✓بخش ۶ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

#3 Critical — 17% of Criticals.
The Function Family Comparison Test
1. List all state changes in function A (deposit/place/create)
2. List all state changes in function B (withdraw/update/cancel)
3. For each state change in A: does B have the corresponding reverse?
4. For each token transfer in A: does B have the corresponding refund?
If A does X but B doesn't do the reverse of X → BUG.
Variant 1: Update Function Missing Refund (ThunderNFT)
function place_order(OrderInput calldata order) external {
    token.safeTransferFrom(msg.sender, address(this), order.price);  // takes tokens
    orders[orderId] = order;
}
function update_order(OrderInput calldata updatedOrder) external {
    // BUG: NO REFUND for sell orders when price decreases → tokens permanently stuck
    orders[orderId] = updatedOrder;
}
Variant 2: Partial Fill Token Stuck (Plume)
function swapForETH(uint256 amountIn) external {
    token.safeTransferFrom(msg.sender, address(this), amountIn);
    uint256 filled = dex.swap(amountIn);  // partial fill possible
    _refundExcessEth(amountIn - filled);  // BUG: refunds ETH only, not ERC20
}
Variant 3: mint() Bypasses Check That deposit() Has (MetaPool)
function deposit(uint256 assets, address receiver) public override {
    shares = _deposit(assets, receiver);  // includes receipt validation
}
function mint(uint256 shares, address receiver) public override {
    assets = convertToAssets(shares);
    _mint(receiver, shares);  // MISSING: _deposit() validation → mints without receiving assets
}
Grep Patterns
grep -rn "function place_\|function create_\|function add_\|function open_" contracts/ -A5
grep -rn "function update_\|function modify_\|function cancel_" contracts/ -A5
grep -rn "safeApprove\b" contracts/    # safeApprove without zero-reset before
grep -rn "delete\b" contracts/ -B5 -A5  # delete before operation completes
grep -rn "function deposit\|function mint\|function withdraw\|function redeem" contracts/ -A10

۷

بخش تکمیلی

4. OFF-BY-ONE & BOUNDARY CONDITIONS
ترجمه‌ی کامل ✓بخش ۷ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏‏High شماره‌ی ۴ — ‏۲۲٪ Highها. ‏تغییر تک‌کاراکتری. ‏impact عظیم.
‏‏علت ریشه‌ای
// VeChain Stargate — post-exit reward drain:
function _claimableDelegationPeriods(address delegator) internal view returns (uint256) {
    if (endPeriod > nextClaimablePeriod) {  // BUG: should be >=
        return 0;  // exited users get nothing
    }
    return nextClaimablePeriod - lastClaimedPeriod;  // rewards for period AFTER exit
}
‏‏تست ذهنی برای هر مقایسه
‏برای هر if (A > B): «وقتی A == ‏B چه اتفاقی می‌افتد؟» ‏آیا درست است؟
‏‏۶ مکان مرزی برای چک
  1. ‏مرزهای Period/Epoch: ‏> در برابر >= در پایان period
  2. ‏قفل‌های مبتنی-بر-زمان: ‏آیا block.timestamp == deadline قفل می‌کند یا باز؟
  3. ‏شرایط break مربوط به حلقه: ‏break با > در برابر >=
  4. ‏مرزهای ایندکس آرایه: ‏i <= array.length ‏(باید i < array.length باشد)
  5. ‏مرزهای مقدار/بالانس: ‏>= amount اجازه‌ی برداشت دقیق کامل می‌دهد؟
  6. ‏‏rounding/precision: ‏آیا ورودی‌ای می‌تواند خروجی ۰ تولید کند که باید غیرصفر باشد؟
‏‏الگوهای Grep
# Boundaries in comparisons
grep -rn "Period\|Epoch\|Round\|Deadline\|period\|epoch\|deadline" contracts/ -A3 | grep "[<>][^=]"

# Loop breaks
grep -rn "\bbreak\b" contracts/ -B10

# Off-by-one in array access
grep -rn "\.length\s*-\s*1\|i\s*<=\s*.*\.length\b" contracts/
۸

بخش تکمیلی

5. ORACLE / PRICE MANIPULATION
ترجمه‌ی کامل ✓بخش ۸ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

12% of all reports. Largest individual payouts. $117M Mango, $70M Curve.
Bug A: Missing Staleness Check (most common)
// VULNERABLE:
(, int256 price,,,) = priceFeed.latestRoundData();
return uint256(price);  // If Chainlink node goes down, stale price returned indefinitely

// CORRECT:
(, int256 price,, uint256 updatedAt,) = priceFeed.latestRoundData();
require(block.timestamp - updatedAt <= MAX_PRICE_AGE, "Stale price");
require(price > 0, "Invalid price");
Bug B: Missing Confidence Interval (Pyth)
// VULNERABLE:
PythStructs.Price memory p = pyth.getPriceUnsafe(priceFeed);
return p.price;  // ignores p.conf (confidence interval)

// CORRECT:
require(p.conf * 10 <= uint64(p.price), "Price too uncertain");
// conf > 10% of price = untrustworthy
Bug C: TWAP Too Short (flash loan manipulatable)
// VULNERABLE: 60-second TWAP
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = 60; secondsAgos[1] = 0;
// Flash loan can shift price for entire 60s window

// CORRECT: 1800s minimum TWAP (30 min)
Bug D: Single-Source Oracle
// VULNERABLE: only Uniswap spot price
uint price = getUniswapSpotPrice(token);  // flash loan manipulatable

// CORRECT: Chainlink primary, Uniswap TWAP as fallback, require close agreement
Grep Patterns
# Missing staleness check
grep -rn "latestRoundData" contracts/ -A5 | grep -v "updatedAt\|timestamp"

# Pyth price usage — confidence interval checked?
grep -rn "getPriceUnsafe\|getPrice\b" contracts/ -A8 | grep -v "conf\|confidence"

# TWAP windows — short TWAP flag
grep -rn "secondsAgo\|TWAP\|cardinality" contracts/ -A5

۹

بخش تکمیلی

6. ERC4626 VAULT ATTACKS
ترجمه‌ی کامل ✓بخش ۹ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

Exchange Rate Manipulation (near-empty vault)
// VULNERABLE — first depositor attack:
// 1. Attacker deposits 1 wei → gets 1 share
// 2. Attacker donates large amount directly (transfer, not deposit)
// 3. Exchange rate: 1 share = (1 + donation) assets
// 4. Victim deposits → rounds down to 0 shares → free donation to attacker

// CORRECT: virtual shares (OpenZeppelin v4.9+)
function _decimalsOffset() internal view virtual override returns (uint8) {
    return 9;  // add 1e9 virtual shares + assets to prevent manipulation
}
ERC4626 Transfer (moves shares but not stake/lock records)
// VULNERABLE: shares transferred, but lock records stay with original owner
// → shares stuck, can't redeem → permanent freeze (Belong pattern)
function transfer(address to, uint256 amount) external override {
    _transfer(msg.sender, to, amount);  // moves shares
    // MISSING: transfer lock record from msg.sender to `to`
}
Grep Patterns
grep -rn "function transfer\|function transferFrom" contracts/ -A15
grep -rn "function deposit\|function mint\|function withdraw\|function redeem" contracts/ -A10

۱۰

بخش تکمیلی

7. REENTRANCY
ترجمه‌ی کامل ✓بخش ۱۰ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

2016–present. CEI pattern prevents it. Still found in DeFi.
Variants
  • Single-function: attacker re-enters same function before state updated
  • Cross-function: re-enters a sibling function with stale state
  • Cross-contract: re-enters via a callback to another protocol
  • Read-only: re-enters a view function that returns stale data used by attacker
Root Cause Pattern
// VULNERABLE (effects after interaction):
function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);
    (bool success,) = msg.sender.call{value: amount}("");  // INTERACTION first
    require(success);
    balances[msg.sender] -= amount;  // EFFECT after → reentrancy window
}

// CORRECT (CEI — Checks, Effects, Interactions):
function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);  // CHECK
    balances[msg.sender] -= amount;            // EFFECT
    (bool success,) = msg.sender.call{value: amount}("");  // INTERACTION last
    require(success);
}
Grep Patterns
# External calls before state updates
grep -rn "\.call{value\|safeTransfer\|transfer(" contracts/ -B10 | grep -v "require\|revert"

# Missing nonReentrant modifier on critical functions
grep -rn "function withdraw\|function redeem\|function claim" contracts/ -A2 | grep -v "nonReentrant"

# Storage slot for reentrancy guard
grep -rn "nonReentrant\|ReentrancyGuard\|_notEntered" contracts/

۱۱

بخش تکمیلی

8. FLASH LOAN ATTACKS
ترجمه‌ی کامل ✓بخش ۱۱ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

Oracle Manipulation via Flash Loan
// Attack flow:
// 1. Borrow $100M from Aave flash loan
// 2. Dump token in Uniswap pool → crash spot price
// 3. Protocol reads Uniswap spot → undercollateralized loans accepted
// 4. Borrow max against cheap collateral
// 5. Repay flash loan, keep profits
Price Oracle Sanity Checks (what to look for)
grep -rn "getReserves\|getAmountsOut\|slot0\b" contracts/ -A5
# spot price from reserves = manipulatable with flash loan
# slot0 = Uniswap V3 spot price = manipulatable

۱۲

بخش تکمیلی

9. SIGNATURE REPLAY
ترجمه‌ی کامل ✓بخش ۱۲ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

Missing Nonce
// VULNERABLE:
function permit(address owner, address spender, uint256 value,
                uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
    bytes32 hash = keccak256(abi.encodePacked(owner, spender, value, deadline));
    // MISSING: nonce not included → same signature usable multiple times
    require(ecrecover(hash, v, r, s) == owner);
}
Missing Chain ID
// VULNERABLE: signature valid on mainnet AND testnet AND all forks
bytes32 hash = keccak256(abi.encodePacked(params));
// MISSING: block.chainid not in hash → works on any chain
Grep Patterns
grep -rn "ecrecover\|ECDSA\.recover" contracts/ -B20
# Check: does the signed hash include nonce + chainId + contract address?

grep -rn "nonce\|_nonces\|nonces\[" contracts/

۱۳

بخش تکمیلی

10. PROXY / UPGRADE ISSUES
ترجمه‌ی کامل ✓بخش ۱۳ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

Storage Collision
// Implementation and proxy share storage layout
// Proxy slot 0: _owner
// Implementation slot 0: _initialized
// → writing to _initialized overwrites _owner
Uninitialized Implementation
// If implementation can be initialized directly → anyone becomes owner of implementation
// Attack: call initialize() on implementation contract → call upgradeTo() → replace logic
delegatecall to User-Controlled Address
function execute(address target, bytes calldata data) external onlyOwner {
    target.delegatecall(data);  // target is validated, but what if owner is compromised?
}
Grep Patterns
# UUPS initialization protection
grep -rn "function initialize\b\|_disableInitializers\|initializer" contracts/

# Delegate call
grep -rn "delegatecall\b" contracts/ -B3 -A5

# Storage layout — proxy uses EIP-1967 slots?
grep -rn "0x360894\|EIP1967\|_IMPLEMENTATION_SLOT" contracts/

۱۴

بخش تکمیلی

FOUNDRY POC TEMPLATE
ترجمه‌ی کامل ✓بخش ۱۴ از ۱۶

بخش تکمیلی سند که در دسته‌بندی استاندارد نگنجیده است

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "forge-std/Test.sol";
import "../src/VulnerableContract.sol";

contract ExploitTest is Test {
    VulnerableContract target;
    address attacker = makeAddr("attacker");
    address victim = makeAddr("victim");

    function setUp() public {
        // Fork mainnet at specific block
        vm.createSelectFork("mainnet", BLOCK_NUMBER);

        // Deploy or load target
        target = VulnerableContract(TARGET_ADDRESS);

        // Fund accounts
        deal(address(token), attacker, INITIAL_BALANCE);
        deal(address(token), victim, VICTIM_BALANCE);
    }

    function test_exploit() public {
        console.log("Attacker balance before:", token.balanceOf(attacker));

        vm.startPrank(attacker);

        // Step 1: Setup conditions
        // Step 2: Execute exploit
        // Step 3: Verify impact

        vm.stopPrank();

        console.log("Attacker balance after:", token.balanceOf(attacker));
        assertGt(token.balanceOf(attacker), INITIAL_BALANCE, "Exploit failed");
    }
}
Key Foundry Cheatcodes
vm.prank(address)           // next call from address
vm.startPrank(address)      // all calls from address until stopPrank()
vm.deal(address, amount)    // set ETH balance
deal(token, address, amount) // set ERC20 balance
vm.warp(timestamp)          // set block.timestamp
vm.roll(blockNumber)        // set block.number
vm.createSelectFork("mainnet", blockNumber)  // fork mainnet
vm.expectRevert(bytes)      // next call should revert
vm.label(address, "name")   // label for trace output
vm.assume(condition)        // fuzz: discard inputs where false
Running Tests
# Run specific test
forge test --match-test test_exploit -vvvv

# Run with fork
forge test --match-test test_exploit -vvvv --fork-url $MAINNET_RPC

# Gas report
forge test --gas-report

# Coverage
forge coverage --report summary

۱۵

دروازه‌ی اعتبارسنجی

Related Skills & Chains
ترجمه‌ی کامل ✓بخش ۱۵ از ۱۶

چک‌لیست‌ها و قواعد پیش از گزارش برای جلوگیری از false positive و N/A

‏این بخش صرفاً کد / دستور است — بدون تغییر حفظ شده:

  • meme-coin-audit — When the target is a meme coin / SPL token rather than a DeFi protocol. Workflow primitive: pre-dive kill signals diverge — this skill's "TVL < $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.
  • 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.
  • 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.
  • 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.
  • bb-methodology — When deciding whether to dive at all. Workflow primitive: PART 0 of bb-methodology confirms engagement (web3 bug bounty / private audit / smart-contract review); this skill's pre-dive kill signals replace the standard scoring rubric for that engagement type.

مراحل استخراج‌شده
  1. ۱`meme-coin-audit` — When the target is a meme coin / SPL token rather than a DeFi protocol. Workflow primitive: pre-dive kill signals diverge — this skill's "TVL < $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.
  2. ۲`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.
  3. ۳`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.
  4. ۴`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.
  5. ۵`bb-methodology` — When deciding whether to dive at all. Workflow primitive: PART 0 of `bb-methodology` confirms engagement (web3 bug bounty / private audit / smart-contract review); this skill's pre-dive kill signals replace the standard scoring rubric for that engagement type.
۱۶

ابزار و نکات عملیاتی

Operator Notes (Claude-BugHunter)
ترجمه‌ی کامل ✓بخش ۱۶ از ۱۶

ابزارهای کمکی، نصب، خروجی‌های مورد انتظار و یادداشت‌های اپراتور

‏افزوده‌های مشتق‌شده-از-engagement + ‏مخصوص-۲۰۲۶ روی بنیان vendored.
‏حکمت از engagementهای authorised واقعی + ‏verification مربوط به فاز ۲ در سراسر
‏تست‌های زنده‌ی +۳۱ ناحیه‌ی-اسکیل این repo. ‏محتوای upstream مقدار WHAT را پوشش می‌دهد؛
‏این لایه مقدار کی-کار-می‌کند-در-برابر-کی-نمی‌کند را پوشش می‌دهد.
‏‏کلاس‌های باگ که هنوز در ۲۰۲۶ پرداخت می‌شوند

‏حملات flash-loan همچنان بالاترین-پرداخت روی Immunefi‌اند ‏(۵ برتر ۲۰۲۴-۲۰۲۶ بر اساس bounty). ‏‏primitive اقتصادی — ‏قرض ۵۰ میلیون دلار، ‏دستکاری oracle مربوط به قیمت، ‏خالی‌کردن pool، ‏بازپرداخت — ‏به‌خاطر اینکه پروتکل‌های جدید پیوسته با فرض‌های composability ship می‌کنند که زیر عدم‌تعادل flash-loan‌شده نمی‌ایستند، دوباره‌ودوباره ظاهر می‌شود.

‏‏Reentrancy هنوز دارد پرداخت می‌شود چون پروتکل‌های جدید پیوسته با ERC-777 / ‏hookها / ‏callbackها ship می‌کنند. ‏فرض نکن کلاس مرده — ‏کورپوس پرداخت‌شده‌ی ۲۰۲۳-۲۰۲۵ شامل +۴۰ باگ reentrancy علیه کدبیس‌های پس-از-Checks-Effects-Interactions است ‏(reentrancy مربوط به بین-تابعی، ‏reentrancy مربوط به فقط-خواندنی از طریق تابع‌های view که وسط-pروازِ state صدا می‌شوند).

‏‏دستکاری Oracle: ‏هنوز سنگین پرداخت می‌شود ولی سخت‌تر. ‏اکثر پروژه‌ها حالا از feedهای قیمت Chainlink استفاده می‌کنند؛ ‏هدف حمله oracle مربوط به ثانویه است که اکثر پروژه‌ها هم استفاده می‌کنند ‏(TWAP از جفت Uniswap V2 کم-نقدینگی، ‏oracle داخلی خود پروتکل، ‏مسیر fallback مربوط به stale). ‏زنجیره‌ی failover را audit کن، نه فقط feed اصلی.

‏‏چه چیزی از زمان نوشته‌شدن محتوای vendored جدید است
  • ‏‏EIP-1153 ‏(storage مربوط به transient) — ‏در ۲۰۲۴ معرفی شد. ‏کلاس‌های جدید reentrancy: ‏خوان‌های transient-storage که در همان تراکنش کش می‌شوند می‌توانند از storage ماندگار desync شوند. ‏هر استفاده‌ی tload/tstore را برای read-after-external-call اudit کن.
  • ‏‏EIP-7702 ‏(هاردفورک Pectra مربوط به ۲۰۲۵) — ‏ارتقاهای EOA-به-smart-account را افزود. ‏‏primitiveهای جدید شبه-ATO از طریق re-delegation: ‏یک EOA یک‌بار-امضاشده می‌تواند به قراردادی که مهاجم کنترل می‌کند delegate کند، بعد replay مربوط به امضا در سراسر delegationها.
  • ‏‏abstraction مربوط به اکانت ‏(bundlerهای ERC-4337) — ‏سوء‌استفاده‌ی اسپانسرشیپ paymaster و griefing مربوط به bundler. ‏قراردادهای paymaster که allowlistهای سخت فرستنده را enforce نمی‌کنند در اولین call خالی می‌شوند.
  • ‏‏باگ‌های bridge مربوط به ZK-rollup — ‏proof-replay در سراسر rollupها، ‏مصالحه‌ی prover مربوط به off-chain، ‏سانسور sequencer که به edge-caseهای forced-inclusion می‌انجامد.
  • ‏‏دینامیک‌های depeg مربوط به LST/LRT — ‏توکن‌های liquid-staking و liquid-restaking که peg مربوط به ۱:۱ را زیر شرایط ضرر فرض می‌کنند؛ ‏oracle مقدار peg را فرض می‌کند، ‏بازار depeg را منعکس می‌کند، ‏منطق liquidation می‌شکند.
‏‏استک ابزار برای ۲۰۲۶

‏‏Foundry همچنان فریم‌ورک تست است. ‏forge test --gas-report --debug برای تست invariant؛ ‏forge fuzz برای تست property-based؛ ‏forge inspect برای auditهای storage-layout. ‏‏Slither + ‏Echidna برای استاتیک + ‏فاز. ‏‏Mythril برای اجرای symbolic روی قراردادهای کوچک‌تر. ‏‏tenderly.co برای forking + ‏simulation ‏(بهترین UX برای تکرار حملات علیه state مربوط به mainnet).

‏برای Solana: ‏فریم‌ورک anchor، ‏کورپوس sealevel-attacks ‏(PoCهای کیوریت‌شده توسط نگه‌دارندگان anchor)، ‏اسکنر soteria-sec / ‏sec3. ‏برای Move ‏(Aptos، ‏Sui): ‏move-prover، ‏aptos move test مربوط به aptos-cli.

‏برای بین-زنجیره‌ای: ‏hyperlane و LayerZero هرکدام repoهای audit-tooling دارند؛ ‏باگ‌های bridge به شبیه‌سازی هر دو endpoint نیاز دارند، نه فقط یکی.

‏‏کجا سیگنال‌های kill مربوط به pre-dive مهم‌اند

‏‏TVL زیر ۵۰۰ هزار دلار ارزش زمان audit را ندارد مگر کف bounty بالا باشد. ‏شرکت audit قبلاً پوششش داده = ‏ROI کم مگر اینکه چیزی را که آن‌ها از دست دادند پیدا کنی — به بخش scope-exclusion مربوط به گزارش audit نگاه کن برای چیزهایی که صراحتاً audit نکردند ‏(oracleها، ‏governance، ‏کامپوننت‌های off-chain، ‏فرانت‌اند، ‏مسیر admin).

‏‏امضاکنندگان Multisig > ‏۵ + ‏timelock > ‏۴۸ ساعت = ‏ریسک rug-pull کم؛ ‏اگر یافته‌ات به فرض‌های تیم-بدخواه نیاز دارد، ‏impact کم است و احتمالاً out-of-scope طبق استثنای «centralization risk» مربوط به Immunefi. ‏برف برنامه را بخوان — اکثر برنامه‌های Immunefi صراحتاً یافته‌هایی که بدخواهی admin را فرض می‌کنند تنزل یا رد می‌کنند.

‏‏انضباط گزارش‌دهی

‏‏Immunefi به PoC مربوط به Foundry نیاز دارد. ‏‏submission بدون PoC خودکار رد می‌شود. ‏‏submission با PoCای که setup دستی می‌خواهد ‏(«اول این را deploy کن، بعد آن را call کن») معمولاً تنزل می‌یابد — ‏PoC باید یک فراخوان تکی forge test باشد که impact را ثابت کند، با assertEq صریح روی بالانس خالی‌شده / ‏توکن mint‌شده / ‏state خراب‌شده.

‏ادعاهای شدت باید دقیقاً از ماتریس شدت Immunefi استفاده کنند؛ ‏شدت‌هایی از خود نساز. ‏ماتریس روی درصد ضرر اقتصادی مستقیم از TVL گیت می‌کند — ‏critical علیه پروتکل ۵۰۰هزاری متفاوت از critical علیه ۵۰۰‌میلیونی پرداخت می‌شود. ‏تخصیص شدت مخصوص-برنامه را قبل از ادعای Critical بخوان.