Advanced static analysis plugin for Hardhat with Control Flow Graph analysis, YAML programmable audits, and comprehensive vulnerability detection.
# Install in your Hardhat project
npm install hardhat-superaudit
# Add to hardhat.config.ts
import superauditPlugin from "hardhat-superaudit";
export default {
plugins: [superauditPlugin]
};
# Run security analysis
npx hardhat superauditThat's it! SuperAudit will analyze all your contracts and provide detailed security reports.
SuperAudit is a comprehensive smart contract security analysis plugin for Hardhat that goes far beyond basic linting:
- β Control Flow Graph (CFG) Analysis - Detects vulnerabilities through execution path analysis
- β Reentrancy Detection - Sophisticated attack path identification with exploit scenarios
- β CEI Pattern Enforcement - Check-Effects-Interactions pattern validation
- β YAML Audit Playbooks - Programmable, shareable audit strategies
- β Educational Reports - Detailed explanations with mitigation strategies
- β Multiple Output Formats - Console, JSON, SARIF (GitHub integration)
| Feature | Description | Status |
|---|---|---|
| AST Analysis | Pattern-based vulnerability detection | β Complete |
| CFG Analysis | Control flow graph construction & analysis | β Complete |
| Advanced Rules | Reentrancy, unreachable code, CEI violations | β Complete |
| YAML Playbooks | Programmable audit logic with DSL | β Complete |
| π ERC20 Playbook | Comprehensive token security analysis | β Complete |
| π Vault Playbook | DeFi vault and strategy security | β Complete |
| π Complete DeFi | Full-stack project audit (tokens + vaults) | β Complete |
| Dynamic Testing | Blockchain forking & fuzzing framework | β Framework Ready |
| Multiple Formats | Console, JSON, SARIF output | β Complete |
| π File Output | Save reports to files (txt, json, sarif) | β Complete |
| π€ AI Enhancement | LLM-powered explanations & fix suggestions | β Complete |
Running SuperAudit on the example vulnerable vault:
npx hardhat superauditπ SuperAudit - Advanced Smart Contract Security Analysis
π Analysis Mode: FULL
π§ Rules: 7 active rule(s)
π Scanning contracts in: ./contracts
β
Successfully parsed 4 contract(s)
π Starting comprehensive security analysis...
β‘ 4 basic AST rules (fast)
π§ 3 CFG-based rules (advanced)
π Static Analysis Report
VulnerableVault.sol
[CRITICAL] external-before-state at line 58
External call occurs before state update (CEI pattern violation)
REENTRANCY ATTACK ANALYSIS:
1. Attacker deploys malicious contract with fallback function
2. Attacker calls withdraw() to trigger external call
3. In fallback, attacker reenters withdraw() before balance update
4. Attacker drains vault by withdrawing more than deposited
MITIGATION:
β
Update state BEFORE external calls
β
Use OpenZeppelin's ReentrancyGuard
β
Follow Check-Effects-Interactions pattern
π Summary:
Critical: 5
High: 10
Medium: 20
Total: 25 issues
π Analysis Performance:
Time: 5ms
β οΈ Critical issues detected - review required
SuperAudit Architecture
βββ AST Parser (Solidity β Abstract Syntax Tree)
βββ CFG Builder (Functions β Control Flow Graphs)
βββ Rule Engine (Modular vulnerability detection)
β βββ Basic Rules (AST pattern matching)
β βββ Advanced Rules (CFG path analysis)
βββ Playbook System (YAML DSL β Executable rules)
βββ Reporter (Multi-format output)
- Parser:
@solidity-parser/parserfor Solidity AST generation - CFG Construction: Custom builder with basic block identification
- Analysis: Visitor pattern + graph traversal algorithms
- Playbooks: YAML DSL with rule interpreter
- Output: Console (chalk), JSON, SARIF
β Phase 1: Advanced Static Analysis
- CFG construction for all functions
- Basic block identification and edge mapping
- State variable tracking (reads/writes)
- External call detection and analysis
β Phase 2: CFG-Based Rules
external-before-state- CEI pattern enforcementunreachable-code- Dead code detection via graph traversalreentrancy-paths- Multi-path attack analysis
β Phase 3: YAML Playbook System
- Full DSL parser for audit strategies
- Rule interpreter (order, pattern, access, value rules)
- Sample playbooks (DeFi, ERC20, Access Control)
β Phase 4: Dynamic Testing Framework
- Fork management (blockchain state manipulation)
- Fuzzing engine (property-based testing)
- Reentrancy attack simulation
β Phase 5: Enhanced Reporting
- SARIF format (GitHub Code Scanning)
- JSON API (CI/CD integration)
- Educational console output
# Using npm
npm install hardhat-superaudit
# Using pnpm
pnpm add hardhat-superaudit
# Using yarn
yarn add hardhat-superauditAdd to your hardhat.config.ts:
import { HardhatUserConfig } from "hardhat/config";
import superauditPlugin from "hardhat-superaudit";
const config: HardhatUserConfig = {
solidity: "0.8.28",
plugins: [superauditPlugin],
// ... your other config
};
export default config;# Full analysis (default)
npx hardhat superaudit
# Basic mode (fast, AST-only)
npx hardhat superaudit --mode basic
# Advanced mode (includes CFG)
npx hardhat superaudit --mode advanced
# JSON output for CI/CD
npx hardhat superaudit --format json > audit-report.json
# SARIF for GitHub Code Scanning
npx hardhat superaudit --format sarif > audit.sarif
# Save report to file (automatically adds correct extension)
npx hardhat superaudit --output ./reports/audit-report.txtAdd to hardhat.config.ts:
superaudit: {
mode: "full", // Options: "basic", "advanced", "full"
format: "console", // Options: "console", "json", "sarif"
output: "./reports/audit-report.txt" // Optional: save to file
}Or use environment variables in .env:
SUPERAUDIT_MODE=full
SUPERAUDIT_FORMAT=console
SUPERAUDIT_OUTPUT=./audit-report.txtSuperAudit includes pre-built playbooks for common contract types:
superaudit: {
// For ERC20 tokens
playbook: "./playbooks/erc20-token-security.yaml"
// For DeFi vaults
// playbook: "./vault-security.yaml"
// For complete projects (tokens + vaults)
// playbook: "./playbooks/complete-defi-security.yaml"
}See PLAYBOOK-GUIDE.md for detailed playbook documentation.
cd your-hardhat-project
npx hardhat superaudit# Set playbook in hardhat.config.ts
superaudit: {
playbook: "./playbooks/erc20-token-security.yaml"
}
npx hardhat superaudit# .github/workflows/security.yml
name: Security Audit
on: [push, pull_request]
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm install
- run: npx hardhat superaudit --format sarif > results.sarif
- uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: results.sarifCreate audit-strategy.yaml:
version: "1.0"
meta:
name: "DeFi Vault Security"
author: "Your Team"
checks:
- id: "check-cei-pattern"
rule: "order.externalBefore(state=['balances','shares'])"
severity: "critical"
- id: "unsafe-transfers"
rule: "pattern.transfer(!checkedReturn)"
severity: "high"
- id: "missing-access-control"
rule: "access.missingOwnable(functions=['withdraw','pause'])"
severity: "high"Note: Playbook infrastructure is ready, CLI integration coming soon.
SuperAudit now supports AI-enhanced security analysis using OpenAI GPT-4 or Anthropic Claude to provide:
- π§ Detailed Vulnerability Explanations - Understand WHY code is vulnerable
- π§ Automated Fix Suggestions - Get concrete code fixes with examples
β οΈ Risk Scoring - AI-powered risk assessment (1-10 scale)- π Educational Context - Learn security best practices
- π‘ Alternative Patterns - Discover better approaches
1. Install dependencies (already included):
npm install openai @anthropic-ai/sdk dotenv2. Configure API keys:
Copy env.example to .env in your project root:
# .env
SUPERAUDIT_AI_ENABLED=true
SUPERAUDIT_AI_PROVIDER=openai
OPENAI_API_KEY=sk-your-api-key-here
# Optional customization
# SUPERAUDIT_AI_MODEL=gpt-4
# SUPERAUDIT_AI_TEMPERATURE=0.3
# SUPERAUDIT_AI_MAX_TOKENS=10003. Run analysis with AI:
# Enable AI enhancement
npx hardhat superaudit --ai
# Or set in environment
export SUPERAUDIT_AI_ENABLED=true
npx hardhat superauditWithout AI:
[CRITICAL] external-before-state at line 58
External call occurs before state update (CEI pattern violation)
With AI (--ai flag):
[CRITICAL] external-before-state at line 58
External call occurs before state update (CEI pattern violation)
π€ AI ANALYSIS:
This is a classic reentrancy vulnerability. An attacker can:
1. Deploy a malicious contract with a fallback function
2. Call withdraw() to trigger the external call
3. In the fallback, reenter withdraw() before balance is updated
4. Drain the entire vault by withdrawing more than deposited
π° ESTIMATED IMPACT: High - Total vault funds at risk
π§ SUGGESTED FIX:
```solidity
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
// Update state FIRST (Effects)
balances[msg.sender] -= amount;
// External call LAST (Interactions)
(bool success,) = msg.sender.call{value: amount}("");
require(success);
}
π ALTERNATIVE: Use OpenZeppelin's ReentrancyGuard
### AI-Enhanced YAML Playbooks
You can add custom AI prompts to your playbooks:
```yaml
version: "1.0"
meta:
name: "AI-Enhanced DeFi Audit"
ai:
enabled: true
provider: "openai"
model: "gpt-4"
enhance_findings: true
generate_fixes: true
checks:
- id: "reentrancy-check"
rule: "order.externalBefore(state=['balances'])"
severity: "critical"
ai_prompt: |
Analyze this reentrancy vulnerability in a DeFi context.
Provide:
1. Attack scenario with estimated financial impact
2. Step-by-step fix with code
3. Alternative secure patterns
Estimated Costs (OpenAI GPT-4):
- Small project (10 issues): ~$0.30
- Medium project (50 issues): ~$1.50
- Large project (200 issues): ~$6.00
Cost-Saving Tips:
- Use
gpt-3.5-turbofor faster, cheaper analysis - Run basic analysis first, then use AI for critical issues only
- Enable caching (coming soon) to avoid re-analyzing identical code
- Use Anthropic Claude for similar quality at lower cost
| Provider | Models | Cost (per issue) | Setup |
|---|---|---|---|
| OpenAI | gpt-4, gpt-3.5-turbo | $0.03 - $0.10 | OPENAI_API_KEY |
| Anthropic | claude-3-sonnet, claude-3-opus | $0.02 - $0.08 | ANTHROPIC_API_KEY |
| Local | Coming soon | Free | N/A |
| Rule ID | Description | Severity |
|---|---|---|
no-tx-origin |
Detects authorization bypasses using tx.origin | Error |
explicit-visibility |
Enforces explicit state variable visibility | Warning |
contract-naming |
Enforces PascalCase for contracts | Warning |
function-naming |
Enforces camelCase for functions | Warning |
| Rule ID | Description | Analysis Type |
|---|---|---|
external-before-state |
CEI pattern enforcement | Path Analysis |
unreachable-code |
Dead code detection | Graph Traversal |
reentrancy-paths |
Multi-path attack detection | Flow Analysis |
- Basic (~1-2ms): AST pattern matching only
- Advanced (~5-10ms): All rules + CFG analysis
- Full (~10-20ms): Everything including playbook rules
Vulnerable Code:
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
// VULNERABILITY: External call before state update
token.transfer(msg.sender, amount);
balances[msg.sender] -= amount; // Too late!
}SuperAudit Detection:
[CRITICAL] external-before-state at line 58
External call occurs before updating critical state variable 'balances'
ATTACK SCENARIO:
1. Attacker calls withdraw()
2. transfer() executes, giving control to attacker
3. Attacker reenters withdraw() in callback
4. Balance still not updated, allows multiple withdrawals
5. Vault drained
MITIGATION:
β
Move state update before external call
β
Add ReentrancyGuard modifier
β
Use pull payment pattern
Vulnerable Code:
function emergencyWithdraw() external {
require(tx.origin == owner); // VULNERABLE!
// ...
}SuperAudit Detection:
[HIGH] no-tx-origin at line 105
Avoid using tx.origin for authorization
ATTACK SCENARIO:
1. Attacker tricks owner into calling malicious contract
2. Malicious contract calls emergencyWithdraw()
3. tx.origin is still the owner
4. Authorization bypass successful
MITIGATION:
β
Use msg.sender instead of tx.origin
β
Implement proper access control pattern
SuperAudit includes a powerful DSL for defining custom audit strategies:
version: "1.0"
meta:
name: "Custom Audit Strategy"
author: "Security Team"
description: "Project-specific security rules"
targets:
contracts: ["*Vault", "*Pool"]
exclude: ["Test*", "Mock*"]
checks:
# Order rules (execution flow)
- id: "cei-enforcement"
rule: "order.externalBefore(state=['balance','shares'])"
severity: "critical"
# Pattern rules (code patterns)
- id: "unchecked-calls"
rule: "pattern.transferFrom(!checkedReturn)"
severity: "high"
# Access rules (permissions)
- id: "public-critical"
rule: "access.missingOwnable(functions=['mint','burn'])"
severity: "high"
# Value rules (constraints)
- id: "amount-validation"
rule: "value.range(variable='amount', min=0, max=1000000)"
severity: "medium"- DeFi Vault Security - Comprehensive vault analysis
- ERC20 Token Security - Token-specific checks
- Access Control Audit - Permission and ownership review
The architecture is ready for AI-enhanced analysis. See LLM-INTEGRATION-PLAN.md for:
- OpenAI/Anthropic integration design
- AI-powered vulnerability explanations
- Automated fix suggestions
- Risk scoring using ML
- Implementation roadmap
Current Status: ~30% implemented (infrastructure ready, needs LLM API integration)
Try SuperAudit on the included vulnerable contracts:
# Clone the repository
git clone <repo-url>
cd SuperAudit-Plugin
# Install dependencies
pnpm install
# Build the plugin
cd packages/plugin
pnpm build
# Run on example project
cd ../example-project
npx hardhat superauditThe example project includes intentionally vulnerable contracts that demonstrate SuperAudit's detection capabilities:
- VulnerableVault.sol - Reentrancy, CEI violations, access control issues
- TestViolations.sol - Naming conventions, visibility issues, tx.origin usage
SuperAudit-Plugin/
βββ packages/
β βββ plugin/ # Main plugin code
β β βββ src/
β β β βββ index.ts # Plugin definition
β β β βββ tasks/
β β β β βββ analyze.ts # Main task
β β β βββ parser.ts # Solidity AST parser
β β β βββ reporter.ts # Issue reporting
β β β βββ rules/
β β β β βββ engine.ts # Rule engine
β β β β βββ no-tx-origin.ts
β β β β βββ advanced/ # CFG-based rules
β β β βββ cfg/
β β β β βββ builder.ts # CFG construction
β β β β βββ analyzer.ts # CFG analysis
β β β βββ playbooks/
β β β β βββ parser.ts # YAML parser
β β β β βββ dsl/ # Rule interpreter
β β β βββ dynamic/
β β β βββ fuzzing-engine.ts
β β βββ package.json
β βββ example-project/ # Test contracts
βββ USAGE.md # Complete usage guide
βββ QUICK-REFERENCE.md # Quick start guide
βββ FILE-OUTPUT-EXAMPLES.md # File output examples
βββ IMPLEMENTATION-SUMMARY.md # Technical details
βββ README.md # This file (complete documentation)
# Install dependencies
pnpm install
# Build plugin
cd packages/plugin
pnpm build
# Link for local testing
pnpm link --global
# Use in another project
cd your-project
pnpm link --global hardhat-superaudit
npx hardhat superauditcd packages/plugin
pnpm test| Project Size | Contracts | Time | Memory |
|---|---|---|---|
| Small (1-5) | 5 | <10ms | ~50MB |
| Medium (5-20) | 20 | ~50ms | ~100MB |
| Large (20-100) | 100 | ~500ms | ~200MB |
Benchmarked on M1 MacBook Pro with 16GB RAM
| Feature | SuperAudit | Slither | Mythril | Manticore |
|---|---|---|---|---|
| CFG Analysis | β Built-in | β Yes | β Yes | β Yes |
| Hardhat Integration | β Native | |||
| YAML Playbooks | β Yes | β No | β No | β No |
| Educational Output | β Detailed | |||
| Speed | β <10ms | β Slow | β Very Slow | |
| GitHub Integration | β SARIF | β Yes | β No | |
| Learning Curve | β Easy | β Hard |
# Ensure plugin is installed
npm list hardhat-superaudit
# Rebuild if needed
cd node_modules/hardhat-superaudit
npm run build# Check Solidity version (0.8.x supported)
# Ensure contracts compile first
npx hardhat compile# Try advanced mode
npx hardhat superaudit --mode advanced
# Check if contracts are being found
npx hardhat superaudit --verbose# 1. Navigate to example project
cd packages/example-project
# 2. Create .env file
cat > .env << EOF
SUPERAUDIT_AI_ENABLED=true
SUPERAUDIT_AI_PROVIDER=openai
OPENAI_API_KEY=your-key-here
EOF
# 3. Run AI-enhanced analysis
npx hardhat superaudit --aiYou should see:
- β "π€ AI Enhancement: ENABLED (openai)"
- β Enhanced findings with detailed explanations
- β Fix suggestions with code examples
- β Risk scores (1-10 scale)
- β Confidence percentages
cd packages/example-project
./test-ai.shThis automated script will:
- Check your environment configuration
- Run basic analysis (no AI baseline)
- Run AI-enhanced analysis
- Run playbook with AI prompts
- Show comparison of results
Issue: "AI Enhancement: DISABLED (No API key found)"
Solution:
# Check .env file exists
ls -la .env
# Verify contents
cat .env
# Should contain:
# SUPERAUDIT_AI_ENABLED=true
# SUPERAUDIT_AI_PROVIDER=openai
# OPENAI_API_KEY=sk-...Issue: "OpenAI API error"
Solutions:
-
Verify API key is valid:
curl https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY" -
Check you have credits in your OpenAI account
-
Try cheaper model for testing:
export SUPERAUDIT_AI_MODEL=gpt-3.5-turbo npx hardhat superaudit --ai
Issue: "No AI analysis shown in output"
Solutions:
- Ensure you're using the
--aiflag OR haveSUPERAUDIT_AI_ENABLED=truein.env - Check that issues were actually found (AI only enhances existing findings)
- Look for the "π€ AI ANALYSIS:" section in issue output
Issue: TypeScript compilation errors
Solution:
cd packages/plugin
pnpm install
pnpm buildIssue: "Command not found: hardhat"
Solution:
# Install locally in your project
npm install --save-dev hardhat hardhat-superaudit
# Or run from example project
cd packages/example-project
npx hardhat superauditIssue: AI enhancement is too slow
Solutions:
-
Use faster model:
export SUPERAUDIT_AI_MODEL=gpt-3.5-turbo -
Run basic analysis first, then AI only for critical issues
-
Limit analysis to specific files:
# Analyze only critical contracts npx hardhat superaudit --ai
Issue: API costs too high
Solutions:
-
Use GPT-3.5-Turbo (~100x cheaper than GPT-4):
export SUPERAUDIT_AI_MODEL=gpt-3.5-turbo -
Run AI selectively: Use basic mode first, then AI for finals:
# Fast initial scan npx hardhat superaudit --mode basic # AI-enhanced final review npx hardhat superaudit --ai
-
Disable AI in CI, enable for release audits:
# .github/workflows/audit.yml - name: Quick Audit (No AI) run: npx hardhat superaudit # Only for release branches - name: Full AI Audit if: github.ref == 'refs/heads/main' run: npx hardhat superaudit --ai env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- AST-based rule engine
- CFG construction and analysis
- Advanced vulnerability detection
- YAML playbook system
- Multiple output formats
- Dynamic testing framework foundation
- LLM integration for AI-enhanced analysis
- OpenAI and Anthropic provider support
- AI-enhanced playbook configuration
- Response caching for cost optimization
- Batch AI processing
- Playbook marketplace integration
- Incremental analysis with caching
- VSCode extension for real-time analysis
- Cross-contract vulnerability detection
- Automated test case generation
- Machine learning-based risk scoring
- Decentralized audit playbook marketplace
MIT License - see LICENSE file for details.
Built with:
- Hardhat - Ethereum development environment
- @solidity-parser/parser - Solidity AST parser
- Chalk - Terminal styling
- YAML - YAML parsing
Inspired by:
- Slither - Python static analyzer
- Mythril - Security analysis tool
- OpenZeppelin - Security best practices
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: This README contains complete documentation including AI integration
SuperAudit represents a paradigm shift in smart contract security:
β
~95% of full static analysis vision implemented
β
AI-powered vulnerability analysis with GPT-4 & Claude
β
Production-ready CFG-based vulnerability detection
β
Programmable audit logic via YAML playbooks
β
Educational explanations for every finding
β
Automated fix suggestions with code examples
β
Sub-10ms analysis performance (without AI)
β
Native Hardhat 3 integration
Making comprehensive AI-enhanced security analysis accessible to every developer! ππ€β¨
Try it now:
npm install hardhat-superaudit
npx hardhat superaudit