AI-Powered Smart Contract Security Audit Tool
A sophisticated multi-agent AI system that performs comprehensive security audits on Solidity smart contracts using adversarial reasoning, static analysis simulation, and attack scenario modeling.
SolidityGuard AI is an open-source smart contract security auditing framework powered by CrewAI. It deploys a 6-agent sequential pipeline to analyze Solidity contracts for vulnerabilities across multiple dimensions:
๐ Reentrancy & MEV attacks ๐ Access control flaws ๐งฎ Arithmetic vulnerabilities (overflow/underflow) โ๏ธ Logic errors & state inconsistencies ๐ฐ Economic incentive attacks ๐ซ Denial of Service vectors
Each agent specializes in a different stage of the audit, passing context down the pipeline to produce a professional markdown audit report with confirmed findings, attack scenarios, and remediation recommendations.
- ๐ค 6-Agent Pipeline: Contract Planner โ Static Analysis โ Vulnerability Hunter โ Exploit Crafter โ Verification โ Report Writer
- โ๏ธ Adversarial Analysis: AI agents reason about attacks from an adversary's perspective
- ๐ฏ No Manual Tool Dependencies: Doesn't require Slither, 4naly3er, or other CLI toolsโAI simulates static analysis findings
- ๐จ Attack Scenario Modeling: Full proof-of-concept attack scenarios with transaction sequences
- โ Risk Verification Layer: Independent verification agent challenges findings before final report
- ๐ Markdown Reports: Publication-ready audit reports in markdown format
- ๐ Educational & Production Ready: Built-in sample vulnerable contract for testing; supports custom audits
- ๐ API-First Design: Built on CrewAI frameworkโeasily extensible and embeddable
Prerequisites:
- ๐ Python 3.10 or higher
- ๐ฆ pip or uv package manager
Clone & Install:
git clone https://github.com/baties/smartcontract_security_crewai.git
cd smartcontract_security_crewai-project/sc_security
# Using UV (recommended)
uv sync
# OR using pip
pip install -e ".[dev]"๐ Set API Keys:
Create a .env file in sc_security/ directory:
# Required: OpenAI API key for Claude/GPT models
OPENAI_API_KEY=sk-proj-YOUR-KEY-HERE
# Optional: Serper API key for web search (used by agents)
SERPER_API_KEY=your-serper-key-here
# Optional: LLM model selection (defaults to gpt-4o-mini)
MODEL=gpt-4o-miniAudit a Contract:
# Audit the built-in vulnerable sample contract
sc_security
# Audit your own contract
sc_security path/to/YourContract.sol๐ Output:
audit_report.mdโ completed audit report with all findings and recommendations
The audit follows a sequential 6-stage pipeline:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. CONTRACT PLANNER โ
โ โณ Read contract code โ
โ โณ Produce comprehensive audit plan (functions, state, risks) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 2. STATIC ANALYSIS AGENT โ
โ โณ Simulate Slither/4naly3er findings โ
โ โณ Classify: GENUINE | FALSE_POSITIVE | NEEDS_DEEPER โ
โ โณ Identify gaps static tools cannot catch โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 3. VULNERABILITY HUNTER โ
โ โณ Adversarial deep-dive on 6 attack categories โ
โ โณ Find exploitable issues (not false positives) โ
โ โณ Rank by severity (Critical โ Low) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 4. EXPLOIT CRAFTER โ
โ โณ Model complete attack scenarios for each finding โ
โ โณ Transaction sequences, attacker profiles, PoC pseudocode โ
โ โณ Financial impact estimates โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 5. VERIFICATION AGENT โ
โ โณ Challenge every finding with skeptical reasoning โ
โ โณ Verify attack paths are actually exploitable โ
โ โณ Eliminate false positives, downgrade uncertain findings โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 6. REPORT WRITER โ
โ โณ Synthesize all findings into professional markdown report โ
โ โณ Executive summary, risk tables, recommendations โ
โ โณ Output: audit_report.md โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The system analyzes contracts across 6 primary attack vectors:
- ๐ Reentrancy โ External calls violating Checks-Effects-Interactions pattern
- ๐ Access Control โ Missing or bypassable privilege checks
- ๐ข Arithmetic โ Overflow, underflow, division by zero
- โก Logic Errors โ Incorrect state updates, broken invariants, edge cases
- ๐ธ Economic/Incentive โ Flash loan vectors, MEV, sandwich attacks, fund drainage
- ๐ซ Denial of Service โ Permanent withdrawal blocking, gas griefing, unbounded loops
cd sc_security
sc_securityThis runs the full audit on the VulnerableVault sample contract (intentionally vulnerable for demonstration). Output:
============================================================
SolidityGuard AI โ Smart Contract Security Audit
6-Agent CrewAI Pipeline
============================================================
[Contract Planner] Analyzing contract structure...
[Static Analysis Agent] Simulating tool findings...
[Vulnerability Hunter] Searching for exploitable issues...
[Exploit Crafter] Modeling attack scenarios...
[Verification Agent] Challenging findings...
[Report Writer] Generating final report...
[SolidityGuard] Audit complete. Report saved to: audit_report.md
# Single contract
sc_security /path/to/MyToken.sol
# Result: audit_report.md with findings specific to MyTokenfrom sc_security.crew import ScSecurity
# Audit a contract programmatically
contract_code = open("MyContract.sol").read()
inputs = {"contract_code": contract_code}
crew = ScSecurity().crew()
result = crew.kickoff(inputs=inputs)
print(result) # Full audit output| Variable | Required | Default | Purpose |
|---|---|---|---|
OPENAI_API_KEY |
โ Yes | โ | OpenAI API key for LLM access |
MODEL |
โ No | gpt-4o-mini |
LLM model to use |
SERPER_API_KEY |
โ No | โ | Web search API (optional) |
Agents and tasks are defined in YAML config files:
src/sc_security/config/agents.yamlโ Agent personalities, roles, goalssrc/sc_security/config/tasks.yamlโ Task descriptions, expected outputs, context chains
Modify these files to customize agent behavior, prompts, or output expectations.
Main entry point: src/sc_security/main.py
def run():
"""Run the audit crew."""
contract_path = sys.argv[1] if len(sys.argv) > 1 else None
contract_code = _load_contract(contract_path)
inputs = {"contract_code": contract_code}
ScSecurity().crew().kickoff(inputs=inputs)smartcontract_security_crewai-project/
โโโ README.md # This file
โโโ sc_security/ # Main Python package
โ โโโ pyproject.toml # Project metadata & dependencies
โ โโโ uv.lock # UV lock file
โ โโโ .env # API keys (git-ignored)
โ โโโ src/sc_security/
โ โ โโโ main.py # CLI entry point
โ โ โโโ crew.py # CrewAI crew definition
โ โ โโโ config/
โ โ โ โโโ agents.yaml # Agent configurations
โ โ โ โโโ tasks.yaml # Task configurations
โ โ โโโ tools/
โ โ โ โโโ __init__.py
โ โ โ โโโ custom_tool.py # Custom agent tools
โ โ โโโ knowledge/
โ โ โโโ user_preference.txt # Domain knowledge (optional)
โ โโโ .venv/ # Virtual environment
โโโ .gitignore # Git ignore configuration
The project includes a built-in demo contract with 3 intentional vulnerabilities:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VulnerableVault {
mapping(address => uint256) public balances;
// VULN-001: Reentrancy
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
balances[msg.sender] -= amount; // State update AFTER call
}
// VULN-002: Missing access control
function setPaused(bool _paused) external {
paused = _paused; // No msg.sender check!
}
// VULN-003: State inconsistency
function emergencyWithdraw() external {
payable(owner).transfer(address(this).balance);
// Drains contract but leaves user balances untouched
}
}When audited, the system detects:
- Reentrancy in withdraw() โ external call before state update
- Access control bypass in setPaused() โ any address can pause
- State mismatch in emergencyWithdraw() โ contract drains but balances remain
| Command | Purpose |
|---|---|
sc_security |
๐ฏ Audit the built-in sample contract |
sc_security <path> |
๐ Audit a custom contract file |
run_crew |
sc_security |
train <n_iterations> <output_file> |
๐ง Train the crew on sample contract |
replay <task_id> |
๐ Replay a specific task from previous execution |
test <n_iterations> <eval_llm> |
โ Test crew performance |
run_with_trigger |
โก Run with event triggering |
cd sc_security
python -m pytestsc_security train 3 training_results.jsonTrains the crew for 3 iterations and saves results for prompt optimization.
sc_security replay <task_id>Reruns a specific task from a previous execution using saved context.
Example: audit_report.md
---
# SMART CONTRACT SECURITY AUDIT REPORT
**Contract:** VulnerableVault
**Audit Date:** 2025-12-15
**Audited By:** SolidityGuard AI โ Multi-Agent Audit Team
## EXECUTIVE SUMMARY
The VulnerableVault contract contains 3 confirmed critical vulnerabilities that allow fund theft via reentrancy, unauthorized pause, and state inconsistency attacks.
## RISK OVERVIEW
| Severity | Count |
|----------|-------|
| Critical | 3 |
| High | 0 |
| Medium | 0 |
| Low | 0 |
## FINDINGS
### VULN-001: Reentrancy in withdraw()
**Severity:** Critical | **Category:** Reentrancy | **Affected Function:** `withdraw()`
#### Description
The withdraw() function performs an external call before updating the balance state, violating the Checks-Effects-Interactions pattern...
#### Impact
An attacker can drain the entire vault by recursively calling withdraw() through a malicious contract's receive() function.
#### Proof of Concept
1. Deploy AttackerContract with receive() that calls VulnerableVault.withdraw()
2. Call vault.deposit() with 1 ETH
3. Call vault.withdraw(1 ether)
4. receive() triggers instantly, calls withdraw() again
5. Repeat until vault empty
#### Recommendation
Move the balance update BEFORE the external call:
```solidity
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount; // Update state FIRST
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
}...
---
## ๐ค Contributing
Contributions are welcome! Areas for enhancement:
- [ ] ๐น Add support for Vyper contracts
- [ ] ๐ Integrate real Slither/4naly3er tool calls
- [ ] โฝ Add gas optimization analysis
- [ ] ๐ Support for multi-file audits
- [ ] ๐จ Web UI for report visualization
- [ ] ๐ฏ Custom agent templates for specific protocols (AMM, lending, etc.)
### ๐ Contribution Guidelines
1. **Fork the repository** ๐ด
2. **Create a feature branch** (`git checkout -b feature/amazing-feature`) ๐ณ
3. **Make your changes** with clear commit messages ๐
4. **Write tests** for new functionality ๐งช
5. **Submit a pull request** with description of changes ๐
---
## ๐ License
This project is licensed under the **MIT License** โ see [LICENSE](LICENSE) file for details.
You are free to use, modify, and distribute this software, with appropriate attribution.
---
## โ ๏ธ Disclaimer & Limitations
### โ IMPORTANT: AI-Generated Reports Require Human Review
**SolidityGuard AI** is an experimental AI-powered analysis tool. **This is NOT a substitute for professional human audits.**
#### โ Limitations:
- โ **No guarantee of finding all vulnerabilities** โ AI agents may miss edge cases
- โ **False positives possible** โ AI may flag non-issues as vulnerabilities
- โ **Cannot detect off-chain attacks** โ Only analyzes code, not external dependencies
- โ **No formal verification** โ Proofs generated are pseudocode, not mathematically formal
- โ **Depends on LLM quality** โ Output quality varies with model and prompt engineering
#### ๐ซ Unaudited Categories:
- โ๏ธ Compiler-level vulnerabilities
- ๐ Third-party library exploits
- ๐ฑ Economic attacks requiring cross-protocol interaction
- โฐ Time-dependent race conditions
- ๐ฎ Oracle manipulation (without deep DeFi context)
#### โ
Best Practices:
1. โ๏ธ **Use this as a first-pass filter** โ catches obvious issues quickly
2. โ๏ธ **Always have a human auditor review findings** โ especially Critical/High severity
3. โ๏ธ **Combine with static analysis tools** โ Slither, 4naly3er, Certora run in parallel
4. โ๏ธ **Test with multiple models** โ GPT-4, Claude, etc. for cross-validation
5. โ๏ธ **For production contracts** โ hire professional audit firms (Trail of Bits, Consensys, etc.)
---
## ๐ Resources
- ๐ค **CrewAI Framework**: https://github.com/joaomdmoura/crewai
- ๐ **Solidity Security**: https://docs.soliditylang.org/en/latest/security-considerations.html
- ๐ **OWASP Smart Contracts**: https://owasp.org/www-project-smart-contract-top-10/
- ๐ **Trail of Bits Audits**: https://trailofbits.com/
- โ
**Consensys Diligence**: https://consensys.net/diligence/
---
## ๐ก Ideas & Feedback
Have ideas for improvements? Found a bug? Feel free to:
- ๐ **Open an Issue**: https://github.com/baties/smartcontract_security_crewai/issues
- ๐ฌ **Start a Discussion**: https://github.com/baties/smartcontract_security_crewai/discussions
- ๐ **Submit a Pull Request**: https://github.com/baties/smartcontract_security_crewai/pulls
---
## ๐ Acknowledgments
This project builds on the excellent work of:
- โญ **CrewAI**: Multi-agent AI orchestration framework
- ๐ง **Anthropic/OpenAI**: Large language models powering the agents
- ๐ **Security Research Community**: OWASP, Trail of Bits, Consensys, Echidna teams
---
**Made with โค๏ธ for the Solidity & Web3 security community**
<div align="center">
[](https://twitter.com/Batis13Ab)
[](https://github.com/baties/smartcontract_security_crewai)
โญ **Star us on GitHub if you find this useful!** โญ
</div>
*Last Updated: 2025-12-15*