gasangalimov/defi-audit-agents
GitHub: gasangalimov/defi-audit-agents
Stars: 0 | Forks: 0
# defi-audit-agents
An honest exploration of multi-agent LLM systems for DeFi smart contract auditing.
5 AI agents, 14+ smart contracts tested, transparent results including failures.
[Read in Russian](#русская-версия) | [Methodology](docs/METHODOLOGY.md) | [Results](docs/RESULTS.md) | [Limitations](docs/LIMITATIONS.md)
## What is this
An independent R&D project investigating whether Large Language Models can find real vulnerabilities in DeFi smart contracts when organized into a multi-agent system.
The project tests 5 specialized AI agents (4× GPT-5.4 Mini + Claude Sonnet 4.5) on:
- 32 educational contracts (SmartBugs)
- 9 historical DeFi exploits ($94M+ in losses)
- 5 fresh hacks from 2024-2025
- 1 active bug bounty target (Morpho Blue, $2.5M max bounty)
## Key results
| Test Set | Categorical HIT | Strict HIT (LLM judge) | Notes |
|---|---|---|---|
| Historical DeFi exploits (9) | 9/9 = 100% | not measured | Models knew these in training |
| Fresh DeFi hacks 2024-2025 (5) | 5/5 = 100% | 2/5 = 40% | Real recall capacity |
| Active bug bounty (Morpho Blue) | 5 findings | 0/5 = 0% verified | Top-tier audited protocol |
| SmartBugs educational (32) | 95% precision | not applicable | Architectural validation |
The system can find known patterns in fresh code (around 40% recall) but cannot find novel 0-days in top-tier audited protocols. This is a research result, not a product.
## Architecture
The system uses a 2→4 funnel architecture with five specialized agents:
Layer 1 — Generalists (broad scan):
- Baseline (GPT-5.4 Mini) — wide net
- Precision (GPT-5.4 Mini) — high-confidence
Layer 2 — Specialists (focused):
- Ext_call (GPT-5.4 Mini) — external calls
- Time_rand (GPT-5.4 Mini) — time and randomness
- Claude_deep (Sonnet 4.5) — deep analysis
All findings then pass through strict LLM-as-judge verification.
See [METHODOLOGY.md](docs/METHODOLOGY.md) for the full breakdown.
## What is in this repository
defi-audit-agents/
├── src/ # Production scripts
│ ├── real_defi_v21.py # 5-agent system (final version)
│ ├── claude_v2_test.py # Claude with 2-pass reflection
│ ├── strict_verify.py # LLM-as-judge verification
│ ├── morpho_v2_test.py # Protocol-specific context (RAG)
│ └── ...
├── data/
│ ├── historical_hacks/ # 9 real DeFi exploit contracts
│ ├── fresh_hacks/ # 5 contracts from 2024-2025
│ └── active_bounty/ # Morpho Blue source
├── results/ # All JSON output files
├── docs/
│ ├── METHODOLOGY.md
│ ├── RESULTS.md
│ ├── INSIGHTS.md
│ ├── LIMITATIONS.md
│ └── SETUP.md
├── LICENSE
└── README.md
## Quick start
git clone https://github.com/gasangalimov/defi-audit-agents.git
cd defi-audit-agents
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your API keys
# Reproduce the 9/9 historical hacks result
python src/real_defi_v21.py
# Reproduce the 2/5 strict result on fresh hacks
python src/fresh_hacks_test.py
python src/strict_verify.py
See [SETUP.md](docs/SETUP.md) for detailed instructions.
## Key insights
LLMs find known patterns, not novel bugs. The system achieves 100% on historical exploits because models saw them in training, but only 40% on fresh 2024-2025 vulnerabilities under strict verification.
Categorical metrics overestimate capability. Our system showed 100% categorical HIT on fresh hacks. Under strict LLM-as-judge verification asking whether the specific bug was actually found, this dropped to 40%.
Independent verification is the most valuable component. On Morpho Blue, Pass 1 generated 9 "critical" findings, and every single one was a false positive caught by independent verifiers.
Protocol-specific context dramatically reduces noise. Adding Morpho whitepaper facts to the prompt reduced findings from 9 (all false positive) to 0 (honest "nothing to add"). LLMs without context generate plausible-sounding noise.
Claude outperforms GPT for deep analysis. A single Claude agent with reflection outperformed 4 GPT specialists on real DeFi contracts. Specialists are useful for SmartBugs-level code, less so for production protocols.
See [INSIGHTS.md](docs/INSIGHTS.md) for the full discussion.
## Who this is for
- Security researchers exploring LLM auditing limits
- Web3 hiring managers evaluating AI tooling capabilities
- Grant programs funding security R&D
- Students learning multi-agent system design
- DeFi teams considering LLM-based pre-audit tools
## What this is NOT
- Not a bug bounty tool. Cannot find 0-days reliably.
- Not a replacement for professional audits. Use OpenZeppelin, Trail of Bits, or Spearbit for real protection.
- Not production-ready. This is research code.
- Not a "magic" AI auditor. Methodology over marketing.
## Future directions
Paths to take this further:
- Hybrid LLM + Foundry fuzzing — generate hypotheses with Claude, verify with fuzzing
- Symbolic execution integration via Halmos — mathematical proof of properties
- Fine-tuning on professional audit reports
- RAG with a historical exploit database
See [LIMITATIONS.md](docs/LIMITATIONS.md) for technical paths forward.
## Author
Grisha ([@bnbslow](https://t.me/bnbslow))
Independent researcher exploring the limits of LLM-based smart contract auditing. Started this project as a self-directed investigation into whether multi-agent AI systems can find real DeFi vulnerabilities. Documented every experiment including failures, to contribute methodology rather than marketing to the Web3 security space.
- Telegram: [@bnbslow](https://t.me/bnbslow)
- Email: galimov5500@gmail.com
- GitHub: [@gasangalimov](https://github.com/gasangalimov)
## License
MIT — see [LICENSE](LICENSE).
## Acknowledgments
This project used:
- Anthropic Claude Sonnet 4.5 — primary deep analysis agent
- OpenAI GPT-5.4 Mini — generalist and specialist agents
- Etherscan V2 API — contract source retrieval
- SmartBugs Curated — initial validation dataset
- Morpho Blue — production-quality target for bounty experiment
# Русская версия
## Что это
Независимое R&D-исследование возможностей больших языковых моделей (LLM) для поиска уязвимостей в DeFi-контрактах через мультиагентную систему.
В проекте тестируются 5 специализированных AI-агентов (4× GPT-5.4 Mini + Claude Sonnet 4.5) на:
- 32 учебных контрактах (SmartBugs)
- 9 исторических DeFi-эксплойтах ($94M+ потерь)
- 5 свежих хаках 2024-2025 годов
- 1 активной bug bounty цели (Morpho Blue, до $2.5M вознаграждения)
Общая стоимость проекта: около $8 API-кредитов. Около 3 дней работы.
## Ключевые результаты
| Набор тестов | Категориальное HIT | Строгое HIT (LLM judge) | Примечания |
|---|---|---|---|
| Исторические DeFi-эксплойты (9) | 9/9 = 100% | не измеряли | Модели знали их из обучения |
| Свежие DeFi-хаки 2024-2025 (5) | 5/5 = 100% | 2/5 = 40% | Реальная способность |
| Активная bug bounty (Morpho) | 5 findings | 0/5 = 0% verified | Топ-протокол |
| SmartBugs учебные (32) | 95% precision | — | Валидация архитектуры |
Система находит известные паттерны в свежем коде (около 40% recall), но не находит 0-day на топ-аудированных протоколах. Это исследовательский результат, не продукт.
## Архитектура
5 специализированных агентов в архитектуре 2→4:
Слой 1 — Генералисты (широкий поиск):
- Baseline (GPT-5.4 Mini) — широкая сеть
- Precision (GPT-5.4 Mini) — высокая точность
Слой 2 — Специалисты (узкий фокус):
- Ext_call (GPT-5.4 Mini) — внешние вызовы
- Time_rand (GPT-5.4 Mini) — time/randomness
- Claude_deep (Sonnet 4.5) — глубокий анализ
Затем строгая верификация через LLM-as-judge.
## Главные уроки
LLM находят известные паттерны, не новые баги. 100% на исторических эксплойтах (модели их видели в обучении), но только 40% на свежих 2024-25 при строгой верификации.
Категориальные метрики переоценивают способности. Мы видели 100% категориально на свежих хаках. При строгой проверке "ту ли уязвимость нашли?" — упало до 40%.
Независимая верификация — самый ценный компонент. На топ-аудированном Morpho Blue Pass 1 выдал 9 "критических" findings — все оказались false positive после независимой проверки.
Protocol-specific контекст драматически снижает шум. Добавление фактов из whitepaper Morpho сократило findings с 9 (все FP) до 0 (честное "нечего добавить"). LLM без контекста генерируют правдоподобный шум.
Claude превосходит GPT для глубокого анализа. Один Claude с рефлексией работает лучше чем 4 GPT-специалиста на реальных DeFi-контрактах.
## Что это НЕ
- Не инструмент для bug bounty. Не находит 0-day надёжно.
- Не замена профессиональным аудитам. Используйте OpenZeppelin, Trail of Bits.
- Не production-ready. Это исследовательский код.
## Автор
Гриша ([@bnbslow](https://t.me/bnbslow))
Независимый исследователь, изучающий пределы LLM-аудита смарт-контрактов. Запустил этот проект как самостоятельное исследование возможностей мультиагентных AI-систем находить реальные уязвимости в DeFi. Каждый эксперимент задокументирован включая провалы, чтобы внести методологический вклад в Web3-безопасность.
- Telegram: [@bnbslow](https://t.me/bnbslow)
- Email: galimov5500@gmail.com
- GitHub: [@gasangalimov](https://github.com/gasangalimov)
## Лицензия
MIT — см. [LICENSE](LICENSE).