defi-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DeFi Security Principles

DeFi 安全原则

Language Rule

语言规则

  • Always respond in the same language the user is using. If the user asks in Chinese, respond in Chinese. If in English, respond in English.
Scope: Only applicable to DeFi projects (DEX, lending, staking, LP, yield). Non-DeFi projects can ignore this skill.
  • 始终使用与用户相同的语言回复。如果用户用中文提问,就用中文回复;如果用英文,就用英文回复。
适用范围:仅适用于DeFi项目(DEX、借贷、质押、流动性池、收益类)。非DeFi项目可忽略此技能。

Protection Decision Rules

防护决策规则

ThreatRequired Protection
Whale manipulationDaily transaction caps + per-tx amount limits + cooldown window
MEV / sandwich attackEOA-only checks (
msg.sender == tx.origin
), or use commit-reveal pattern
ArbitrageReferral binding + liquidity distribution + fixed yield model + lock period
Reentrancy
ReentrancyGuard
on all external-call functions (see solidity-security skill)
Flash loan attackCheck
block.number
change between operations, or use TWAP pricing
Price manipulationChainlink oracle or TWAP — never rely on spot AMM reserves for pricing
Approval exploitUse
safeIncreaseAllowance
/
safeDecreaseAllowance
, never raw
approve
for user flows
Governance attackVoting requires snapshot + minimum token holding period; timelock ≥ 48h on proposal execution
ERC4626 inflation attackFirst deposit must enforce minimum amount or use virtual shares to prevent share dilution via rounding
威胁类型必要防护措施
巨鲸操纵每日交易上限 + 单笔交易金额限制 + 冷却窗口期
MEV/三明治攻击仅EOA检查(
msg.sender == tx.origin
),或使用提交-揭示模式
套利行为推荐绑定 + 流动性分配 + 固定收益模型 + 锁仓期
重入攻击所有外部调用函数添加
ReentrancyGuard
(参考solidity-security技能)
闪电贷攻击检查操作之间
block.number
是否变化,或使用TWAP定价
价格操纵使用Chainlink预言机或TWAP — 绝不要依赖AMM现货储备进行定价
授权漏洞使用
safeIncreaseAllowance
/
safeDecreaseAllowance
,用户流程中绝不使用原生
approve
治理攻击投票需快照 + 最低代币持有期限;提案执行的时间锁≥48h
ERC4626通胀攻击首次存款必须强制最低金额,或使用虚拟份额防止因四舍五入导致的份额稀释

Anti-Whale Implementation Rules

反巨鲸实施规则

  • Maximum single transaction amount: configurable via
    onlyOwner
    setter
  • Daily cumulative limit per address: track with
    mapping(address => mapping(uint256 => uint256))
    (address → day → amount)
  • Cooldown between transactions: enforce minimum time gap with
    block.timestamp
    check
  • Whitelist for exempt addresses (deployer, LP pair, staking contract)
  • 单笔交易最大金额:可通过
    onlyOwner
    setter配置
  • 单地址每日累计限额:使用
    mapping(address => mapping(uint256 => uint256))
    跟踪(地址→日期→金额)
  • 交易冷却期:通过
    block.timestamp
    检查强制最小时间间隔
  • 豁免地址白名单(部署者、LP对、质押合约)

Flash Loan Protection Rules

闪电贷防护规则

  • For price-sensitive operations: require that
    block.number
    has changed since last interaction
  • For oracle-dependent calculations: use time-weighted average (TWAP) over minimum 30 minutes
  • For critical state changes: add minimum holding period before action (e.g., must hold tokens for N blocks)
  • 对价格敏感的操作:要求自上次交互以来
    block.number
    已发生变化
  • 对依赖预言机的计算:使用至少30分钟的时间加权平均价格(TWAP)
  • 对关键状态变更:添加操作前的最低持有期限(例如,必须持有代币N个区块)

Launch Checklist

上线Checklist

Before mainnet deployment, verify all items:
  • All
    onlyOwner
    functions transferred to multisig (e.g., Gnosis Safe)
  • Timelock contract deployed and configured (minimum 24h delay for critical changes)
  • Pausable
    emergency switch tested — both
    pause()
    and
    unpause()
    work correctly
  • Daily limit parameters documented and set to reasonable values
  • Third-party security audit completed and all critical/high findings resolved
  • Testnet deployment running for minimum 7 days with no issues
  • Slippage, fee, and lock period parameters reviewed and documented
  • Initial liquidity plan documented (amount, lock duration, LP token handling)
  • forge test --fuzz-runs 10000
    passes on all DeFi-critical functions
主网部署前,需验证所有项目:
  • 所有
    onlyOwner
    函数已转移至多签钱包(如Gnosis Safe)
  • 已部署并配置时间锁合约(关键变更的最短延迟≥24小时)
  • 已测试
    Pausable
    紧急开关 —
    pause()
    unpause()
    均可正常工作
  • 每日限额参数已记录并设置为合理值
  • 已完成第三方安全审计,且所有严重/高危问题已解决
  • 测试网部署已稳定运行至少7天,无任何问题
  • 滑点、手续费和锁仓期参数已审核并记录
  • 初始流动性计划已记录(金额、锁仓时长、LP代币处理方式)
  • 所有DeFi关键函数通过
    forge test --fuzz-runs 10000
    测试

Emergency Response Procedure

应急响应流程

StepAction
1. DetectMonitor alerts trigger (on-chain monitoring, community reports)
2. PauseDesignated address calls
pause()
— must respond within minutes
3. AssessTechnical lead analyzes root cause, estimates fund impact
4. CommunicatePost incident notice to community channels (Discord, Twitter, Telegram)
5. FixDeploy fix or prepare recovery plan
6. ResumeCall
unpause()
after fix verified on fork — or migrate to new contract
7. Post-mortemPublish detailed incident report within 48 hours
步骤操作
1. 检测监控警报触发(链上监控、社区反馈)
2. 暂停指定地址调用
pause()
— 必须在数分钟内响应
3. 评估技术负责人分析根本原因,估算资金影响
4. 沟通在社区渠道(Discord、Twitter、Telegram)发布事件通知
5. 修复部署修复方案或准备恢复计划
6. 恢复在分叉环境验证修复后调用
unpause()
— 或迁移至新合约
7. 事后分析48小时内发布详细的事件报告

DeFi Testing Commands

DeFi 测试命令

bash
undefined
bash
undefined

Fuzz test fund flows with high iterations

Fuzz test fund flows with high iterations

forge test --match-contract StakingTest --fuzz-runs 10000
forge test --match-contract StakingTest --fuzz-runs 10000

Fork mainnet to test against real state

Fork mainnet to test against real state

forge test --fork-url $MAINNET_RPC -vvvv
forge test --fork-url $MAINNET_RPC -vvvv

Simulate whale transaction on fork

Simulate whale transaction on fork

cast call <CONTRACT> "stake(uint256)" 1000000000000000000000000
--rpc-url $FORK_RPC --from <WHALE_ADDRESS>
undefined
cast call <CONTRACT> "stake(uint256)" 1000000000000000000000000
--rpc-url $FORK_RPC --from <WHALE_ADDRESS>
undefined