Solidity Smart Contract Audit Assistant
A structured smart contract security audit workflow based on EEA EthTrust Security Levels V3 specification.
Audit Process Overview
CODEBLOCK0
⚡ Quick Audit Mode (Within 30 minutes)
Suitable for emergency situations or preliminary assessment:
CODEBLOCK1
📊 Audit Capability Baseline (Based on 10 rounds of training)
| Capability Dimension | AI Audit | Professional Audit | Gap |
|---|
| Basic Vulnerabilities | 90% | 100% | -10% |
| Business Logic |
75% | 95% | -20% |
| Math Boundaries | 50% | 85% | -35% |
| Complex Interactions | 60% | 90% | -30% |
AI Advantages: Fast coverage, pattern matching, broad knowledge
AI Disadvantages: Missing toolchain, limited depth analysis, boundary conditions
Step 1: Project Scope & Preparation
Input Confirmation
- - Contract source code (preferably frozen version for audit)
- Compiler version and optimization settings
- Project documentation (architecture diagrams, functional descriptions)
- Test cases (if available)
Audit Scope Definition
CODEBLOCK2
Security Level Selection
| Level | Applicable Scenarios | Core Requirements |
|---|
| [S] Basic | Simple token contracts, basic DeFi | No known high-risk vulnerabilities, basic protection |
| [M] Intermediate |
Complex DeFi, NFT markets, DAOs | External call security, access control, oracle verification |
| [Q] Advanced | Cross-chain bridges, lending protocols, treasury management | Business logic verification, MEV protection, complete documentation |
Pre-Audit Checklist
- - [ ] Code is frozen, no modifications during audit period
- [ ] Compiler version is fixed (e.g.,
pragma solidity 0.8.20) - [ ] All dependency versions are locked
- [ ] Deployment scripts or configurations are provided
- [ ] Test coverage report is available (if exists)
Step 2: Automated Tool Scanning
Static Analysis Tools
Slither (Trail of Bits)
CODEBLOCK3
Aderyn (Rust-based, fast)
CODEBLOCK4
Tool Output Mapping to EEA Specification
| Tool Detection | EEA Requirement | Security Level |
|---|
| INLINECODE1 usage | [S] No tx.origin | S |
| INLINECODE2 |
[S] No selfdestruct() | S |
|
CREATE2 | [S] No CREATE2 | S |
|
assembly blocks | [S] No assembly {} | S |
| Reentrancy detection | [M] External Calls | M |
| Uninitialized variables | [S] Initialize State | S |
| Unchecked return values | [M] Check Return Values | M |
Compiler Version Check
CODEBLOCK5
Refer to EEA § 3.9 Source code, pragma, and compilers for compiler-related security requirements.
Step 3: Manual Review Checklist
[S] Basic Level Review
3.1 Replay Attack Protection
CODEBLOCK6
3.2 Dangerous Opcodes
- - [ ] Check
CREATE2 usage justification, whether necessary - [ ] Check
selfdestruct calls, confirm legitimate reason - [ ] Verify
delegatecall target address controllability
3.3 Permission Verification
CODEBLOCK7
3.4 Encoding Security
CODEBLOCK8
3.5 Inline Assembly
- - [ ] List all
assembly blocks - [ ] Check if detailed comments explain the reason
- [ ] Focus on memory operations and storage operations
[M] Intermediate Level Review
3.6 External Calls & Reentrancy
CODEBLOCK9
3.7 Oracle Dependencies
- - [ ] Is the price data source trustworthy?
- [ ] Is there a TWAP time window?
- [ ] Is there a data staleness detection mechanism?
- [ ] Is there a failover plan?
CODEBLOCK10
3.8 Access Control
- - [ ] Check permission modifiers on critical functions
- [ ] Is role management correctly implemented
- [ ] Can initialization functions be called repeatedly
CODEBLOCK11
3.9 Integer Overflow
CODEBLOCK12
[Q] Advanced Level Review
3.10 Logic & Documentation Consistency
- - [ ] Compare code implementation with whitepaper/documentation
- [ ] Check for undocumented "hidden features"
- [ ] Verify mathematical formula implementation correctness
3.11 MEV Attack Surface
- - [ ] Sandwich attack risk (AMM pricing)
- [ ] Front-running risk (public mempool)
- [ ] Liquidation mechanism exploitable
CODEBLOCK13
3.12 Upgradeable Contract Security
CODEBLOCK14
Special Focus: Governance Module
Governance contract vulnerabilities are often more subtle but have greater impact, requiring specialized review.
3.13 Voting Power & Stake Synchronization
CODEBLOCK15
3.14 Voting Mechanism Security
- - [ ] Can users manipulate results through extreme voting
- [ ] Is voting weight calculation correct
- [ ] Is voting cooldown period reasonable
3.15 Copy-Paste Error Detection
CODEBLOCK16
Special Focus: System Architecture
3.16 Contract Dependency Analysis
Must Complete:
- 1. Draw contract dependency graph
- Mark external call directions
- Identify trust boundaries
CODEBLOCK17
Check Points:
- - [ ] Do Slave contracts trust Master
- [ ] Can external contract addresses be replaced
- [ ] Is state synchronization safe
3.17 Trust Assumption Verification
- - [ ] "Only contracts deployed by factory are trusted" → Is there verification?
- [ ] "Governance tokens have no callbacks" → Is there checking?
- [ ] "Price oracle returns real price" → Is there boundary checking?
Special Focus: Permission Model
3.18 Admin Permission Scope
CODEBLOCK18
3.19 Permission Bypass Check
- - [ ] Can removeMarket + addMarket bypass time restrictions
- [ ] Does adding/removing sub-modules affect fund safety
- [ ] Does modifying contract addresses bypass security checks
3.20 Timelock Integrity
- - [ ] Do all critical parameter changes have timelock
- [ ] Does timelock cover all bypass paths
- [ ] Do users have enough time to respond
Special Focus: Flash Loans & Oracles
3.21 Flash Loan Attack Surface
CODEBLOCK19
3.22 Oracle Manipulation Protection
CODEBLOCK20
3.23 Governance Voting Power Persistence
CODEBLOCK21
SecureUM Quick Checklist
See references/secureum-knowledge.md for details
Top 30 Must-Check Items
| # | Check Item | Description | Reference |
|---|
| 1 | pragma version locked | INLINECODE9 not INLINECODE10 | #2 |
| 2 |
Access control completeness | All sensitive functions have permission modifiers | #4-8 |
| 3 | delegatecall target verification | Target address must be trusted | #12 |
| 4 | Reentrancy protection | CEI pattern or ReentrancyGuard | #13-15 |
| 5 | Random number safety | Don't use block.timestamp/blockhash as random source | #17 |
| 6 | Integer overflow | Check unchecked blocks | #19 |
| 7 | Multiply before divide | Avoid precision loss | #20 |
| 8 | ERC20 approve race | approve(0) then approve(new) | #22, #105 |
| 9 | Signature malleability | Verify signature format before ecrecover | #23 |
| 10 | ERC20 return values | Use SafeERC20 | #24 |
| 11 | Unexpected ETH | selfdestruct can force send ETH | #26 |
| 12 | tx.origin authorization | Prohibit for authorization checks | #30 |
| 13 | mapping deletion | Deleting struct doesn't clear internal mapping | #32 |
| 14 | Low-level call return values | Check call/send/delegatecall return values | #37 |
| 15 | External calls in loops | May cause DoS | #43 |
| 16 | Unbounded loops | May cause out of gas | #44 |
| 17 | Event emission | Emit events for critical state changes | #45 |
| 18 | Zero address validation | Check address parameters | #49 |
| 19 | require vs assert | require for conditions, assert for invariants | #52 |
| 20 | Deprecated keywords | Avoid throw/callcode/suicide | #53 |
| 21 | Function visibility | Must be explicitly declared | #54 |
| 22 | Inheritance order | Affects initialization order | #55 |
| 23 | Hash collision |
abi.encodePacked with multiple variable parameters | #60 |
| 24 | Assembly code | Needs detailed comments and review | #63 |
| 25 | Uninitialized variables | Especially storage pointers | #67-68 |
| 26 | Proxy initialization protection | initializer modifier | #95-96 |
| 27 | Proxy storage layout | Maintain consistency during upgrades | #99 |
| 28 | ERC777 hooks | May trigger reentrancy | #106 |
| 29 | Deflationary/inflationary tokens | Transfer amounts may not match | #107-108 |
| 30 | Two-step permission change | Critical operations need timelock or two-step verification | #162-163 |
Audit Process
CODEBLOCK22
Manual Review Approaches
| Method | Starting Point |
|---|
| Access Control | Start with permission checks |
| Asset Flow |
Start with asset flow |
| Control Flow | Evaluate control flow |
| Data Flow | Evaluate data flow |
| Constraints | Infer constraint conditions |
| Dependencies | Understand dependencies |
| Assumptions | Evaluate assumptions |
| Checklists | Use checklists |
Security Design Principles
- 1. Least Privilege - Grant only necessary permissions
- Separation of Privilege | Critical operations require multiple authorizations
- Fail-safe Defaults - Default to deny, not allow
- Complete Mediation - Check permissions on every access
- Open Design - Security doesn't depend on secrecy
Step 4: Testing & Verification
Foundry Test Framework
CODEBLOCK23
Vulnerability PoC Template
CODEBLOCK24
Fuzz Testing Example
CODEBLOCK25
Test Coverage Requirements
| Vulnerability Type | Test Method | Coverage Target |
|---|
| Reentrancy attacks | Unit tests + PoC | All external call points |
| Integer overflow |
Fuzz testing | unchecked blocks |
| Access control | Unit tests | All permission functions |
| Business logic | Integration tests | Core functionality paths |
Step 5: Report Generation
Report Structure Template
CODEBLOCK26 solidity
// Use ReentrancyGuard or CEI pattern
function withdraw() external nonReentrant {
// ...
}
CODEBLOCK27
References
Detailed Reference Documents
External Resources
- - EEA EthTrust V3 Specification: https://entethalliance.org/specs/ethtrust-sl/v3/
- Secureum Knowledge Graph: https://github.com/x676f64/secureum-mind_map
- OpenZeppelin Contracts: https://docs.openzeppelin.com/contracts
- EIP Standards List: https://eips.ethereum.org/all
- Mastering Ethereum: https://masteringethereum.xyz/
Common Tools
| Tool | Purpose | Link |
|---|
| Slither | Static analysis | https://github.com/crytic/slither |
| Aderyn |
Fast scanning | https://github.com/Cyfrin/aderyn |
| Foundry | Test framework | https://github.com/foundry-rs/foundry |
| Echidna | Fuzz testing | https://github.com/crytic/echidna |
| Mythril | Symbolic execution | https://github.com/ConsenSys/mythril |
Usage Example
CODEBLOCK28
Audit Capability Assessment Framework
Audit Quality Self-Assessment
After completing an audit, use this framework for self-evaluation:
| Dimension | Check Item | Assessment Method |
|---|
| Coverage | Did you review all core contracts | Contract checklist |
| Depth |
Did you discover complex logic vulnerabilities | PoC verification |
| Tools | Did you use automated tools | Slither/Aderyn reports |
| Comparison | Compare with professional reports | Gap analysis |
Capability Level Classification
| Level | Standard | Typical Performance |
|---|
| Junior | Can find basic vulnerabilities | Reentrancy, permission issues, overflow |
| Intermediate |
Can find business logic issues | Price manipulation, liquidation issues |
| Senior | Can find complex interaction vulnerabilities | Cross-chain, composability attacks |
| Expert | Can design security architecture | Formal verification, zero-knowledge proofs |
Audit Time Reference
| Contract Size | Junior | Intermediate | Senior |
|---|
| <500 lines | 2 hours | 1 hour | 30 minutes |
| 500-2000 lines |
8 hours | 4 hours | 2 hours |
| 2000-10000 lines | 40 hours | 20 hours | 10 hours |
| >10000 lines | 2 weeks+ | 1 week+ | 3 days+ |
Common Missed Checks
After completing an audit, check if you missed:
- - [ ] Callback function security
- [ ] Multi-signature/timelock configuration
- [ ] Special token compatibility (rebasing, fee-on-transfer)
- [ ] Cross-chain message verification
- [ ] Price precision issues
- [ ] Gas limit boundary conditions
- [ ] Upgrade pattern security
- [ ] Signature verification security
🎯 Professional Audit Comparison Template
After completing an audit, compare using this format:
CODEBLOCK29
📈 Audit Capability Improvement Path
| Stage | Target | Method |
|---|
| Junior→Intermediate | 78→85 points | More practice cases, learn vulnerability patterns |
| Intermediate→Senior |
85→92 points | Use toolchain, deep protocol research |
| Senior→Expert | 92→98 points | Formal verification, innovative attack vectors |
🔧 Toolchain Gap Solution (Addressing 60% gap)
Problem: AI cannot directly run Slither/Foundry
Solution: Request user to run tools, AI analyzes results
CODEBLOCK30
Tool Output Mapping:
| Slither Detector | AI Analysis Focus |
|---|
| reentrancy-eth | Verify reentrancy protection |
| uninitialized-state |
Check initialization |
| arbitrary-send | Verify sending logic |
| controlled-delegatecall | Verify target address |
⏱️ Time Optimization Solution (Addressing 25% gap)
Problem: Limited audit time
Solution: Focus on high-risk modules
35-minute Allocation:
CODEBLOCK31
High-Risk Function Priority:
- 1. withdraw/transfer/claim
- liquidate/absorb/seize
- setOwner/setConfig
- getPrice/updatePrice
📚 Knowledge Gap Solution (Addressing 15% gap)
Problem: Unfamiliar with new protocol features
Solution: Protocol type knowledge base
| Protocol Type | Core Check Points |
|---|
| AMM | Price calculation, liquidity, slippage |
| Lending |
Liquidation factors, interest rates, oracles |
| Cross-chain | Signature verification, message replay |
| Aggregator | Interaction order, composability risks |
| NFT | Transfers, royalties, authorization |
See: references/toolchain-guide.md for details
Solidity 智能合约审计助手
基于EEA EthTrust安全等级V3规范的结构化智能合约安全审计工作流。
审计流程概览
- 1. 项目准备 → 2. 自动化扫描 → 3. 人工审查 → 4. 测试与验证 → 5. 报告生成
⚡ 快速审计模式(30分钟内)
适用于紧急情况或初步评估:
- 1. 访问控制检查(5分钟)
- 所有者权限
- 敏感函数修饰符
- 2. 重入风险检查(5分钟)
- 外部调用位置
- 状态更新顺序
- 3. 代币安全检查(10分钟)
- SafeERC20使用
- 返回值检查
- 4. 关键漏洞扫描(10分钟)
- 整数溢出
- 签名验证
- 权限绕过
📊 审计能力基线(基于10轮训练)
| 能力维度 | AI审计 | 专业审计 | 差距 |
|---|
| 基础漏洞 | 90% | 100% | -10% |
| 业务逻辑 |
75% | 95% | -20% |
| 数学边界 | 50% | 85% | -35% |
| 复杂交互 | 60% | 90% | -30% |
AI优势:快速覆盖、模式匹配、知识面广
AI劣势:缺少工具链、深度分析有限、边界条件处理不足
第一步:项目范围与准备
输入确认
- - 合约源代码(建议使用冻结版本进行审计)
- 编译器版本和优化设置
- 项目文档(架构图、功能描述)
- 测试用例(如有)
审计范围定义
□ 逻辑合约数量及其功能
□ 是否包含代理合约(可升级性)
□ 外部依赖(预言机、跨链桥等)
□ 部署网络(主网/L2/测试网)
安全等级选择
| 等级 | 适用场景 | 核心要求 |
|---|
| [S] 基础 | 简单代币合约、基础DeFi | 无已知高危漏洞、基本保护 |
| [M] 中级 |
复杂DeFi、NFT市场、DAO | 外部调用安全、访问控制、预言机验证 |
| [Q] 高级 | 跨链桥、借贷协议、金库管理 | 业务逻辑验证、MEV保护、完整文档 |
审计前检查清单
- - [ ] 代码已冻结,审计期间无修改
- [ ] 编译器版本已固定(例如 pragma solidity 0.8.20)
- [ ] 所有依赖版本已锁定
- [ ] 已提供部署脚本或配置
- [ ] 测试覆盖率报告可用(如有)
第二步:自动化工具扫描
静态分析工具
Slither(Trail of Bits)
bash
安装
pip install slither-analyzer
基础扫描
slither . --exclude-dependencies
输出JSON格式
slither . --exclude-dependencies --json output.json
特定检测器
slither . --detect reentrancy-eth,uninitialized-state
Aderyn(基于Rust,速度快)
bash
安装
cargo install aderyn
扫描
aderyn .
输出报告
aderyn . -o report.md
工具输出映射到EEA规范
| 工具检测 | EEA要求 | 安全等级 |
|---|
| tx.origin使用 | [S] 无tx.origin | S |
| selfdestruct |
[S] 无selfdestruct() | S |
| CREATE2 | [S] 无CREATE2 | S |
| assembly块 | [S] 无assembly {} | S |
| 重入检测 | [M] 外部调用 | M |
| 未初始化变量 | [S] 初始化状态 | S |
| 未检查返回值 | [M] 检查返回值 | M |
编译器版本检查
bash
检查已知编译器漏洞
slither . --check-compiler-bugs
关于编译器相关的安全要求,请参考EEA § 3.9 源代码、编译指示和编译器。
第三步:人工审查清单
[S] 基础等级审查
3.1 重放攻击保护
solidity
// 检查:交易哈希是否包含chainId?
// 正确示例:
keccak256(abi.encodePacked(
\x19\x01,
DOMAIN_SEPARATOR, // 包含chainId
hashStruct
))
// 危险:缺少chainId会导致跨链重放
3.2 危险操作码
- - [ ] 检查CREATE2使用理由,是否必要
- [ ] 检查selfdestruct调用,确认合法原因
- [ ] 验证delegatecall目标地址可控性
3.3 权限验证
solidity
// 危险:使用tx.origin进行授权
require(tx.origin == owner); // 钓鱼攻击风险
// 正确:使用msg.sender
require(msg.sender == owner);
3.4 编码安全
solidity
// 危险:连续可变长度参数导致哈希碰撞
keccak256(abi.encodePacked(str1, str2)); // str1=ab, str2=c == str1=a, str2=bc
// 安全:使用encode或固定长度
keccak256(abi.encode(str1, str2));
3.5 内联汇编
- - [ ] 列出所有assembly块
- [ ] 检查是否有详细注释说明原因
- [ ] 重点关注内存操作和存储操作
[M] 中级等级审查
3.6 外部调用与重入
solidity
// CEI模式检查(检查-效果-交互)
function withdraw() external {
// 1. 检查
require(balances[msg.sender] > 0, 余额不足);
// 2. 效果(先更新状态)
balances[msg.sender] = 0;
// 3. 交互(最后进行外部调用)
(bool success, ) = msg.sender.call{value: amount}();
require(success, 转账失败);
}
// 只读重入检查:在状态更新前是否调用了外部view函数?
3.7 预言机依赖
- - [ ] 价格数据源是否可信?
- [ ] 是否有TWAP时间窗口?
- [ ] 是否有数据过期检测机制?
- [ ] 是否有备用方案?
solidity
// 检查:是否有价格偏差检测?
uint256 price = oracle.getPrice();
require(price > 0 && price < MAX_PRICE, 价格无效);
// 检查:是否有时间戳验证?
require(block.timestamp - oracle.lastUpdate() < HEARTBEAT, 数据过期);
3.8 访问控制
- - [ ] 检查关键函数的权限修饰符
- [ ] 角色管理是否正确实现
- [ ] 初始化函数是否可重复调用
solidity
// 危险:未保护的初始化函数
function initialize() external {
owner = msg.sender; // 任何人都可以调用!
}
// 安全:使用OpenZeppelin Initializable
function initialize() external initializer {
owner = msg.sender;
}
3.9 整数溢出
solidity
// Solidity 0.8+默认检查溢出
// 但需要检查unchecked块:
unchecked {
// 这里的溢出不会被检测到!
uint256 result = a + b; // 危险
}
// 特殊情况:循环计数器可以安全使用unchecked
for (uint256 i; i < n; ) {
// ...
unchecked { i++; }
}
[Q] 高级等级审查
3.10 逻辑与文档一致性
- - [ ] 比较代码实现与白皮书/文档
- [ ] 检查是否有未记录的“隐藏功能”
- [ ] 验证数学公式实现正确性
3.11 MEV攻击面
- - [ ] 三明治攻击风险(AMM定价)
- [ ] 抢跑风险(公共mempool)
- [ ] 清算机制是否可被利用
solidity
// AMM三明治攻击示例
// 用户交易:A -> B
// 攻击者:在用户交易前买入B,在用户交易后卖出B
// 保护措施:使用TWAP、滑点保护
3.12 可升级合约安全
solidity
// 检查项:
// 1. 代理合约实现是否正确?
// 2. 初始化函数是否有重入保护?
// 3. 升级权限是否合理?
// 4. 是否存在存储布局冲突?
// 危险:存储布局冲突
// V