tool-dev-quick-audit 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: tool-dev-quick-audit
3
+ Version: 1.0.0
4
+ Summary: Executa for the Quick-Audit Anna App: static 10-class audit for Solidity contracts
5
+ Requires-Python: >=3.10
@@ -0,0 +1,1115 @@
1
+ #!/usr/bin/env python3
2
+ """Quick-Audit — static heuristic scanner for Solidity contracts.
3
+
4
+ Implements the 10 bug classes from the web3-audit skill as regex/AST-lite
5
+ detectors over Solidity source:
6
+
7
+ 1. Accounting state desynchronization
8
+ 2. Access control
9
+ 3. Incomplete code path
10
+ 4. Off-by-one & boundary conditions
11
+ 5. Oracle / price manipulation
12
+ 6. ERC4626 vault attacks
13
+ 7. Reentrancy
14
+ 8. Flash loan attacks
15
+ 9. Signature replay
16
+ 10. Proxy / upgrade issues
17
+
18
+ Pure Python standard library, zero network, zero cost.
19
+
20
+ IMPORTANT: this is a heuristic pre-screen, not a proof. Every finding is a
21
+ *CANDIDATE* that needs manual review and (for anything filed) a Foundry PoC.
22
+ Static patterns cannot prove exploitability, so severities are capped at High
23
+ and every finding carries a confidence level. See README.md.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ from dataclasses import dataclass, field
30
+
31
+ __version__ = "1.0.0"
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Data model
35
+ # ---------------------------------------------------------------------------
36
+
37
+ SEVERITY_ORDER = {"Critical": 4, "High": 3, "Medium": 2, "Low": 1, "Info": 0}
38
+
39
+
40
+ @dataclass
41
+ class Finding:
42
+ rule_id: str
43
+ bug_class: str
44
+ severity: str # Critical | High | Medium | Low | Info
45
+ confidence: str # High | Medium | Low
46
+ title: str
47
+ location: str # e.g. "Vault.sol:42 (function withdraw)"
48
+ line: int
49
+ code: str
50
+ recommendation: str
51
+ reference: str
52
+
53
+ def to_dict(self) -> dict:
54
+ return {
55
+ "rule_id": self.rule_id,
56
+ "class": self.bug_class,
57
+ "severity": self.severity,
58
+ "confidence": self.confidence,
59
+ "title": self.title,
60
+ "location": self.location,
61
+ "line": self.line,
62
+ "code": self.code,
63
+ "recommendation": self.recommendation,
64
+ "reference": self.reference,
65
+ }
66
+
67
+
68
+ @dataclass
69
+ class FunctionInfo:
70
+ name: str
71
+ modifiers: list
72
+ visibility: str
73
+ start_line: int
74
+ end_line: int
75
+ body: str
76
+ body_lines: list # [(line_no, text)]
77
+
78
+
79
+ @dataclass
80
+ class ContractInfo:
81
+ name: str
82
+ start_line: int
83
+ functions: list = field(default_factory=list)
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Source preparation: strip comments but keep line numbers
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def strip_comments(source: str) -> list:
91
+ """Return [(line_no, code_without_comments)] keeping 1:1 line mapping."""
92
+ lines = source.split("\n")
93
+ out = []
94
+ in_block = False
95
+ for i, raw in enumerate(lines, start=1):
96
+ line = raw
97
+ if in_block:
98
+ end = line.find("*/")
99
+ if end == -1:
100
+ out.append((i, ""))
101
+ continue
102
+ line = line[end + 2:]
103
+ in_block = False
104
+ while True:
105
+ start = line.find("/*")
106
+ slash = line.find("//")
107
+ if start != -1 and (slash == -1 or start < slash):
108
+ end = line.find("*/", start + 2)
109
+ if end == -1:
110
+ line = line[:start]
111
+ in_block = True
112
+ break
113
+ line = line[:start] + " " + line[end + 2:]
114
+ continue
115
+ if slash != -1:
116
+ line = line[:slash]
117
+ break
118
+ out.append((i, line))
119
+ return out
120
+
121
+
122
+ def joined_code(lines: list) -> str:
123
+ return "\n".join(text for _, text in lines)
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Parsing: contracts and functions (brace matching, line aware)
128
+ # ---------------------------------------------------------------------------
129
+
130
+ _FUNC_RE = re.compile(
131
+ r"^[ \t]*function\s+(\w+)\s*\(([^)]*)\)\s*"
132
+ r"((?:external|public|internal|private|view|pure|payable|virtual|override"
133
+ r"(?:\([^)]*\))?|\w+)(?:\s+(?:external|public|internal|private|view|pure|payable|virtual|override(?:\([^)]*\))?|\w+))*)\s*"
134
+ r"(?:returns\s*\([^;{]*\))?\s*\{",
135
+ re.MULTILINE,
136
+ )
137
+
138
+ _MODIFIER_RE = re.compile(
139
+ r"^[ \t]*modifier\s+(\w+)\s*\([^)]*\)\s*\{", re.MULTILINE
140
+ )
141
+
142
+ _CONTRACT_RE = re.compile(
143
+ r"^[ \t]*(?:abstract\s+)?contract\s+(\w+)(?:\s+is\s+[^{]+)?\{", re.MULTILINE
144
+ )
145
+
146
+ ACCESS_MODIFIERS = {
147
+ "onlyOwner", "onlyAdmin", "onlyRole", "onlyGovernance", "onlyManager",
148
+ "onlyOperator", "onlyGuardian", "onlyNewEpoch", "onlyAuthorized",
149
+ "whenNotPaused", "nonReentrant", "initializer", "reinitializer",
150
+ }
151
+
152
+
153
+ def _brace_end(lines: list, start_idx: int) -> int:
154
+ """Index into lines[] of the line holding the matching closing brace."""
155
+ depth = 0
156
+ for idx in range(start_idx, len(lines)):
157
+ depth += lines[idx][1].count("{") - lines[idx][1].count("}")
158
+ if depth <= 0:
159
+ return idx
160
+ return len(lines) - 1
161
+
162
+
163
+ def parse_functions(lines: list) -> list:
164
+ text = joined_code(lines)
165
+ funcs = []
166
+ for m in _FUNC_RE.finditer(text):
167
+ # line number of the match start
168
+ start_line = text[: m.start()].count("\n") + 1
169
+ start_idx = start_line - 1
170
+ end_idx = _brace_end(lines, start_idx)
171
+ raw_mods = m.group(3) or ""
172
+ modifiers = [w for w in re.split(r"\s+", raw_mods.strip()) if w]
173
+ visibility = "public"
174
+ for vis in ("external", "public", "internal", "private"):
175
+ if vis in modifiers:
176
+ visibility = vis
177
+ break
178
+ body_lines = lines[start_idx: end_idx + 1]
179
+ funcs.append(FunctionInfo(
180
+ name=m.group(1),
181
+ modifiers=modifiers,
182
+ visibility=visibility,
183
+ start_line=start_line,
184
+ end_line=end_idx + 1,
185
+ body="\n".join(t for _, t in body_lines),
186
+ body_lines=body_lines,
187
+ ))
188
+ return funcs
189
+
190
+
191
+ def parse_modifiers(lines: list) -> dict:
192
+ """modifier name -> (start_line, end_line, body)."""
193
+ text = joined_code(lines)
194
+ out = {}
195
+ for m in _MODIFIER_RE.finditer(text):
196
+ start_line = text[: m.start()].count("\n") + 1
197
+ start_idx = start_line - 1
198
+ end_idx = _brace_end(lines, start_idx)
199
+ body = "\n".join(t for _, t in lines[start_idx: end_idx + 1])
200
+ out[m.group(1)] = (start_line, end_idx + 1, body)
201
+ return out
202
+
203
+
204
+ def parse_contracts(lines: list, funcs: list) -> list:
205
+ text = joined_code(lines)
206
+ contracts = []
207
+ for m in _CONTRACT_RE.finditer(text):
208
+ start_line = text[: m.start()].count("\n") + 1
209
+ members = [f for f in funcs if f.start_line >= start_line]
210
+ contracts.append(ContractInfo(name=m.group(1), start_line=start_line,
211
+ functions=members))
212
+ if not contracts and funcs:
213
+ contracts.append(ContractInfo(name="(no contract)", start_line=1,
214
+ functions=funcs))
215
+ return contracts
216
+
217
+
218
+ def snippet(lines: list, line_no: int, context: int = 0) -> str:
219
+ lo = max(1, line_no - context)
220
+ hi = min(len(lines), line_no + context)
221
+ return " ".join(t.strip() for _, t in lines[lo - 1: hi]).strip()[:220]
222
+
223
+
224
+ def first_match_line(body_lines: list, pattern: str, flags: int = 0) -> int:
225
+ rx = re.compile(pattern, flags)
226
+ for ln, text in body_lines:
227
+ if rx.search(text):
228
+ return ln
229
+ return body_lines[0][0] if body_lines else 0
230
+
231
+
232
+ def _is_declaration_match(text: str, match_start: int) -> bool:
233
+ """True if the match sits on a function/interface declaration line
234
+ (e.g. `function latestRoundData() ...` in an interface), not a call."""
235
+ line_start = text.rfind("\n", 0, match_start) + 1
236
+ line_end = text.find("\n", match_start)
237
+ line = text[line_start: line_end if line_end != -1 else len(text)]
238
+ kw_pos = match_start - line_start
239
+ return "function" in line[:kw_pos]
240
+
241
+ # ---------------------------------------------------------------------------
242
+ # Class 1 — Accounting state desynchronization
243
+ # ---------------------------------------------------------------------------
244
+
245
+ ACCT_VARS = (
246
+ r"totalSupply|totalShares|totalAssets|totalDebt|cumulative\w+|"
247
+ r"rewardPerShare|rewardPerToken|totalStaked|totalDeposited"
248
+ )
249
+
250
+ # an `if (...) { ... return ...; }` early return inside a function body
251
+ _EARLY_RETURN_RE = re.compile(
252
+ r"if\s*\([^;{]*\)\s*\{[^}]*?\breturn\b[^;]*;", re.DOTALL
253
+ )
254
+
255
+
256
+ def _check_early_return(lines, fn, findings, filename):
257
+ body = fn.body
258
+ ret_match = _EARLY_RETURN_RE.search(body)
259
+ if not ret_match:
260
+ return
261
+ # Does the function update accounting state AFTER the early return?
262
+ acct_writes = [
263
+ ln for ln, t in fn.body_lines
264
+ if re.search(r"\b(" + ACCT_VARS + r")\b\s*[-+*/]?=", t)
265
+ ]
266
+ ret_line = fn.start_line + body[: ret_match.start()].count("\n")
267
+ later = [ln for ln in acct_writes if ln > ret_line]
268
+ if later:
269
+ findings.append(Finding(
270
+ rule_id="ACCT-2",
271
+ bug_class="Accounting Desync",
272
+ severity="High",
273
+ confidence="Medium",
274
+ title=f"Early return in {fn.name}() may skip accounting updates",
275
+ location=f"{filename}:{ret_line} (function {fn.name})",
276
+ line=ret_line,
277
+ code=snippet(lines, ret_line),
278
+ recommendation=(
279
+ "Apply the Function Family Comparison Test: list every state "
280
+ "change the slow path performs and make the fast/early-return "
281
+ "path perform the same updates (or route it through the same "
282
+ "internal function). An early return that skips a "
283
+ "totalSupply/totalDebt/cumulative update creates phantom value."
284
+ ),
285
+ reference="web3-audit skill §1 Accounting Desync (variant: fast path skips state update)",
286
+ ))
287
+
288
+
289
+ def _check_accounting(lines, funcs, findings, filename):
290
+ for fn in funcs:
291
+ lname = fn.name.lower()
292
+ if any(k in lname for k in ("claim", "redeem", "withdraw", "unstake",
293
+ "harvest", "exit")):
294
+ _check_early_return(lines, fn, findings, filename)
295
+ # ACCT-3: share math computed BEFORE the deposit updates totals
296
+ if "deposit" in lname:
297
+ share_math = None
298
+ total_update = None
299
+ for ln, t in fn.body_lines:
300
+ if re.search(r"totalShares|totalAssets", t) and "=" in t \
301
+ and re.search(r"\*|/", t):
302
+ share_math = share_math or ln
303
+ if re.search(r"\b(totalAssets|totalShares)\s*\+=", t):
304
+ total_update = total_update or ln
305
+ if share_math and total_update and share_math < total_update:
306
+ findings.append(Finding(
307
+ rule_id="ACCT-3",
308
+ bug_class="Accounting Desync",
309
+ severity="High",
310
+ confidence="Medium",
311
+ title=f"Shares priced before totals update in {fn.name}()",
312
+ location=f"{filename}:{share_math} (function {fn.name})",
313
+ line=share_math,
314
+ code=snippet(lines, share_math),
315
+ recommendation=(
316
+ "Update totalAssets/totalShares BEFORE computing the share "
317
+ "price (or compute shares from the post-deposit totals). "
318
+ "Pricing shares from pre-deposit totals gives the depositor "
319
+ "a wrong rate."
320
+ ),
321
+ reference="web3-audit skill §1 Accounting Desync (variant: update in wrong order)",
322
+ ))
323
+
324
+
325
+ # ---------------------------------------------------------------------------
326
+ # Class 2 — Access control
327
+ # ---------------------------------------------------------------------------
328
+
329
+ _PRIVILEGED_NAMES = (
330
+ "setowner", "setadmin", "setguardian", "pause", "unpause",
331
+ "mint", "upgrade", "upgradeto", "initialize", "setimplementation",
332
+ "sweep", "rescue", "setoracle", "settreasury", "grantrole",
333
+ "revokerole", "setpaused",
334
+ )
335
+
336
+
337
+ def _check_access_control(lines, funcs, modifiers, findings, filename):
338
+ text = joined_code(lines)
339
+
340
+ # AC-3: silent modifier — `if (...) { _; }` with no require/revert
341
+ for name, (start, _end, body) in modifiers.items():
342
+ if re.search(r"\bif\s*\(", body) and not re.search(
343
+ r"\brequire\s*\(|\brevert\b|\bassert\s*\(", body):
344
+ findings.append(Finding(
345
+ rule_id="AC-3",
346
+ bug_class="Access Control",
347
+ severity="Medium",
348
+ confidence="High",
349
+ title=f"Silent modifier {name}() — non-authorized callers pass silently",
350
+ location=f"{filename}:{start} (modifier {name})",
351
+ line=start,
352
+ code=snippet(lines, start),
353
+ recommendation=(
354
+ "Use require(msg.sender == admin, \"Not admin\"); _; — a "
355
+ "modifier whose body only runs inside an `if` lets everyone "
356
+ "else through without reverting."
357
+ ),
358
+ reference="web3-audit skill §2 Access Control (variant: silent modifier)",
359
+ ))
360
+
361
+ # AC-4: initialize() without the initializer modifier
362
+ for fn in funcs:
363
+ if fn.name == "initialize" and "initializer" not in fn.modifiers \
364
+ and "reinitializer" not in fn.modifiers:
365
+ findings.append(Finding(
366
+ rule_id="AC-4",
367
+ bug_class="Access Control",
368
+ severity="High",
369
+ confidence="High",
370
+ title="initialize() has no `initializer` modifier — anyone can call it",
371
+ location=f"{filename}:{fn.start_line} (function initialize)",
372
+ line=fn.start_line,
373
+ code=snippet(lines, fn.start_line),
374
+ recommendation=(
375
+ "Add the `initializer` modifier and put "
376
+ "`_disableInitializers()` in the implementation constructor so "
377
+ "the implementation itself cannot be initialized and hijacked."
378
+ ),
379
+ reference="web3-audit skill §2 Access Control (variant: uninitialized proxy)",
380
+ ))
381
+
382
+ # AC-1: sibling comparison — same verb family, some guarded, some not
383
+ families = {}
384
+ for fn in funcs:
385
+ if fn.visibility not in ("external", "public"):
386
+ continue
387
+ stem = re.split(r"(?=[A-Z])", fn.name)[0].lower() if fn.name else ""
388
+ families.setdefault(stem, []).append(fn)
389
+ for stem, members in families.items():
390
+ if len(members) < 2:
391
+ continue
392
+ guarded = [f for f in members
393
+ if set(f.modifiers) & ACCESS_MODIFIERS]
394
+ unguarded = [f for f in members
395
+ if not (set(f.modifiers) & ACCESS_MODIFIERS)]
396
+ if guarded and unguarded:
397
+ for fn in unguarded:
398
+ findings.append(Finding(
399
+ rule_id="AC-1",
400
+ bug_class="Access Control",
401
+ severity="High",
402
+ confidence="Medium",
403
+ title=(
404
+ f"{fn.name}() has no access guard while sibling "
405
+ f"{guarded[0].name}() in the same family does"
406
+ ),
407
+ location=f"{filename}:{fn.start_line} (function {fn.name})",
408
+ line=fn.start_line,
409
+ code=snippet(lines, fn.start_line),
410
+ recommendation=(
411
+ "Read ALL sibling functions. If vote()/reset() carry a "
412
+ "modifier, poke() must carry it too — the missing modifier "
413
+ "on the sibling IS the bug. Add the same guard."
414
+ ),
415
+ reference="web3-audit skill §2 Access Control (variant: missing modifier on sibling)",
416
+ ))
417
+
418
+ # AC-1b: privileged function with no guard at all
419
+ for fn in funcs:
420
+ if fn.name.lower() in _PRIVILEGED_NAMES \
421
+ and fn.visibility in ("external", "public") \
422
+ and not (set(fn.modifiers) & ACCESS_MODIFIERS) \
423
+ and fn.name != "initialize":
424
+ findings.append(Finding(
425
+ rule_id="AC-1b",
426
+ bug_class="Access Control",
427
+ severity="Medium",
428
+ confidence="Medium",
429
+ title=f"Privileged function {fn.name}() has no access control",
430
+ location=f"{filename}:{fn.start_line} (function {fn.name})",
431
+ line=fn.start_line,
432
+ code=snippet(lines, fn.start_line),
433
+ recommendation=(
434
+ "Confirm this function is intentionally permissionless. If it "
435
+ "changes ownership, fees, oracles, pauses, or mints, restrict "
436
+ "it with onlyOwner / onlyRole."
437
+ ),
438
+ reference="web3-audit skill §2 Access Control",
439
+ ))
440
+
441
+ # AC-2: existence check used where ownership is needed
442
+ for m in re.finditer(r"_requireOwned\s*\(", text):
443
+ ln = text[: m.start()].count("\n") + 1
444
+ ctx = "\n".join(t for _, t in lines[max(0, ln - 3): ln + 5])
445
+ if not re.search(r"ownerOf\s*\(\s*tokenId\s*\)\s*==\s*msg\.sender|"
446
+ r"_checkAuthorized|_isApprovedOrOwner", ctx):
447
+ findings.append(Finding(
448
+ rule_id="AC-2",
449
+ bug_class="Access Control",
450
+ severity="High",
451
+ confidence="Medium",
452
+ title="_requireOwned() checks existence, not ownership",
453
+ location=f"{filename}:{ln}",
454
+ line=ln,
455
+ code=snippet(lines, ln),
456
+ recommendation=(
457
+ "Verify the caller actually owns the token "
458
+ "(ownerOf(tokenId) == msg.sender or _checkAuthorized) — an "
459
+ "existence check lets anyone act on tokens they do not own."
460
+ ),
461
+ reference="web3-audit skill §2 Access Control (variant: existence vs ownership)",
462
+ ))
463
+
464
+
465
+ # ---------------------------------------------------------------------------
466
+ # Class 3 — Incomplete code path
467
+ # ---------------------------------------------------------------------------
468
+
469
+ def _check_incomplete_path(lines, funcs, findings, filename):
470
+ by_name = {f.name: f for f in funcs}
471
+
472
+ # INC-1: mint() bypasses the validation deposit() performs
473
+ if "deposit" in by_name and "mint" in by_name:
474
+ dep, mint = by_name["deposit"], by_name["mint"]
475
+ dep_takes = bool(re.search(r"safeTransferFrom|transferFrom", dep.body))
476
+ mint_takes = bool(re.search(
477
+ r"safeTransferFrom|transferFrom|_deposit\(", mint.body))
478
+ if dep_takes and not mint_takes:
479
+ ln = first_match_line(mint.body_lines, r"\b_mint\s*\(")
480
+ findings.append(Finding(
481
+ rule_id="INC-1",
482
+ bug_class="Incomplete Path",
483
+ severity="High",
484
+ confidence="Medium",
485
+ title="mint() bypasses the receipt validation deposit() performs",
486
+ location=f"{filename}:{ln} (function mint)",
487
+ line=ln,
488
+ code=snippet(lines, ln),
489
+ recommendation=(
490
+ "Route mint() through the same internal _deposit() path as "
491
+ "deposit() so shares are never minted without receiving the "
492
+ "underlying assets."
493
+ ),
494
+ reference="web3-audit skill §3 Incomplete Path (variant: mint bypasses deposit check)",
495
+ ))
496
+
497
+ # INC-2: update/cancel without the refund the create/place path takes
498
+ for create_name in ("place_order", "create_order", "placeOrder", "createOrder"):
499
+ if create_name not in by_name:
500
+ continue
501
+ create = by_name[create_name]
502
+ if not re.search(r"safeTransferFrom|transferFrom", create.body):
503
+ continue
504
+ for fn in funcs:
505
+ lname = fn.name.lower()
506
+ if ("update" in lname or "cancel" in lname or "modify" in lname) \
507
+ and not re.search(r"transfer|refund", fn.body):
508
+ ln = first_match_line(fn.body_lines, r"function\s+" + fn.name)
509
+ findings.append(Finding(
510
+ rule_id="INC-2",
511
+ bug_class="Incomplete Path",
512
+ severity="Medium",
513
+ confidence="Medium",
514
+ title=f"{fn.name}() has no refund path while {create_name}() takes tokens",
515
+ location=f"{filename}:{ln} (function {fn.name})",
516
+ line=ln,
517
+ code=snippet(lines, ln),
518
+ recommendation=(
519
+ "For every token transfer in the create path, the "
520
+ "update/cancel path needs the corresponding refund — "
521
+ "otherwise tokens get permanently stuck."
522
+ ),
523
+ reference="web3-audit skill §3 Incomplete Path (variant: update missing refund)",
524
+ ))
525
+
526
+ # INC-3: safeApprove without a zero reset first
527
+ text = joined_code(lines)
528
+ for m in re.finditer(r"safeApprove\s*\(([^)]*)\)", text):
529
+ args = m.group(1)
530
+ if re.search(r",\s*0\s*\)", args) or "0" in args.split(",")[-1]:
531
+ continue
532
+ ln = text[: m.start()].count("\n") + 1
533
+ ctx = "\n".join(t for _, t in lines[max(0, ln - 6): ln])
534
+ if not re.search(r"safeApprove\s*\([^)]*,\s*0\s*\)", ctx):
535
+ findings.append(Finding(
536
+ rule_id="INC-3",
537
+ bug_class="Incomplete Path",
538
+ severity="Low",
539
+ confidence="Medium",
540
+ title="safeApprove() without resetting allowance to zero first",
541
+ location=f"{filename}:{ln}",
542
+ line=ln,
543
+ code=snippet(lines, ln),
544
+ recommendation=(
545
+ "Set the allowance to 0 before setting a new value "
546
+ "(safeApprove(spender, 0) then safeApprove(spender, amount)), "
547
+ "or use forceApprove / safeIncreaseAllowance."
548
+ ),
549
+ reference="web3-audit skill §3 Incomplete Path",
550
+ ))
551
+
552
+
553
+ # ---------------------------------------------------------------------------
554
+ # Class 4 — Off-by-one & boundary conditions
555
+ # ---------------------------------------------------------------------------
556
+
557
+ _BOUNDARY_WORDS = r"Period|Epoch|Round|Deadline|period|epoch|deadline|expiry|lockUntil|unlockTime"
558
+
559
+
560
+ def _check_off_by_one(lines, funcs, findings, filename):
561
+ text = joined_code(lines)
562
+
563
+ # OB-2: loop over array with <= length (out-of-bounds on last iteration)
564
+ for m in re.finditer(r"for\s*\([^;]*;\s*\w+\s*<=\s*[\w.]+\.length", text):
565
+ ln = text[: m.start()].count("\n") + 1
566
+ findings.append(Finding(
567
+ rule_id="OB-2",
568
+ bug_class="Off-by-One",
569
+ severity="High",
570
+ confidence="High",
571
+ title="Loop uses `i <= array.length` — reads one past the end",
572
+ location=f"{filename}:{ln}",
573
+ line=ln,
574
+ code=snippet(lines, ln),
575
+ recommendation="Use `i < array.length`. `<=` accesses index "
576
+ "`length`, which does not exist and reverts (or, in "
577
+ "unchecked code, reads garbage).",
578
+ reference="web3-audit skill §4 Off-by-One (array index boundaries)",
579
+ ))
580
+ for m in re.finditer(r"\[\s*[\w.]+\.length\s*-\s*1\s*\]", text):
581
+ ln = text[: m.start()].count("\n") + 1
582
+ findings.append(Finding(
583
+ rule_id="OB-2b",
584
+ bug_class="Off-by-One",
585
+ severity="Medium",
586
+ confidence="Low",
587
+ title="Indexing `array[array.length - 1]` — check the empty-array case",
588
+ location=f"{filename}:{ln}",
589
+ line=ln,
590
+ code=snippet(lines, ln),
591
+ recommendation="If the array can be empty, `length - 1` underflows. "
592
+ "Guard with `require(array.length > 0)`.",
593
+ reference="web3-audit skill §4 Off-by-One",
594
+ ))
595
+
596
+ # OB-1: strict > / < on period/deadline boundaries — what happens at ==?
597
+ for m in re.finditer(
598
+ r"\bif\s*\([^;{]*(" + _BOUNDARY_WORDS + r")[^;{]*"
599
+ r"([<>])(?!=)[^;{]*\)", text):
600
+ ln = text[: m.start()].count("\n") + 1
601
+ findings.append(Finding(
602
+ rule_id="OB-1",
603
+ bug_class="Off-by-One",
604
+ severity="Medium",
605
+ confidence="Low",
606
+ title=f"Strict `{m.group(2)}` comparison on a {m.group(1)} boundary — check the == case",
607
+ location=f"{filename}:{ln}",
608
+ line=ln,
609
+ code=snippet(lines, ln),
610
+ recommendation=(
611
+ "For every `if (A > B)`, ask: what happens when A == B? "
612
+ "Period-end and deadline checks are the classic off-by-one — "
613
+ "exited users either lose rewards or keep earning them."
614
+ ),
615
+ reference="web3-audit skill §4 Off-by-One (mental test for every comparison)",
616
+ ))
617
+
618
+ # ---------------------------------------------------------------------------
619
+ # Class 5 — Oracle / price manipulation
620
+ # ---------------------------------------------------------------------------
621
+
622
+ def _check_oracle(lines, funcs, findings, filename):
623
+ text = joined_code(lines)
624
+
625
+ # OR-1: latestRoundData without a staleness check
626
+ for m in re.finditer(r"latestRoundData\s*\(", text):
627
+ if _is_declaration_match(text, m.start()):
628
+ continue
629
+ ln = text[: m.start()].count("\n") + 1
630
+ fn = next((f for f in funcs if f.start_line <= ln <= f.end_line), None)
631
+ if fn is None:
632
+ continue # interface-level declaration, not a call
633
+ scope = fn.body
634
+ if not re.search(r"updatedAt|MAX_PRICE_AGE|stale|STALE", scope):
635
+ findings.append(Finding(
636
+ rule_id="OR-1",
637
+ bug_class="Oracle",
638
+ severity="High",
639
+ confidence="High",
640
+ title="Chainlink price used without a staleness check",
641
+ location=f"{filename}:{ln}" + (f" (function {fn.name})" if fn else ""),
642
+ line=ln,
643
+ code=snippet(lines, ln),
644
+ recommendation=(
645
+ "Read updatedAt from latestRoundData() and require "
646
+ "block.timestamp - updatedAt <= MAX_PRICE_AGE, plus "
647
+ "require(price > 0). A dead Chainlink node returns a stale "
648
+ "price indefinitely."
649
+ ),
650
+ reference="web3-audit skill §5 Oracle (bug A: missing staleness check)",
651
+ ))
652
+ if not re.search(r"price\s*>\s*0|price\s*!=\s*0", scope):
653
+ findings.append(Finding(
654
+ rule_id="OR-1b",
655
+ bug_class="Oracle",
656
+ severity="Medium",
657
+ confidence="Medium",
658
+ title="Chainlink price used without a validity check (price > 0)",
659
+ location=f"{filename}:{ln}" + (f" (function {fn.name})" if fn else ""),
660
+ line=ln,
661
+ code=snippet(lines, ln),
662
+ recommendation="require(price > 0, \"Invalid price\") before "
663
+ "using the feed value.",
664
+ reference="web3-audit skill §5 Oracle",
665
+ ))
666
+
667
+ # OR-2: Pyth price without a confidence-interval check
668
+ for m in re.finditer(r"getPriceUnsafe\s*\(|getPrice\s*\(", text):
669
+ if _is_declaration_match(text, m.start()):
670
+ continue
671
+ ln = text[: m.start()].count("\n") + 1
672
+ fn = next((f for f in funcs if f.start_line <= ln <= f.end_line), None)
673
+ if fn is None:
674
+ continue # interface-level declaration, not a call
675
+ scope = fn.body
676
+ if not re.search(r"\bconf\b|confidence", scope):
677
+ findings.append(Finding(
678
+ rule_id="OR-2",
679
+ bug_class="Oracle",
680
+ severity="High",
681
+ confidence="High",
682
+ title="Pyth price used without checking the confidence interval",
683
+ location=f"{filename}:{ln}" + (f" (function {fn.name})" if fn else ""),
684
+ line=ln,
685
+ code=snippet(lines, ln),
686
+ recommendation=(
687
+ "Require p.conf to be small relative to p.price (e.g. "
688
+ "conf * 10 <= price). A wide confidence interval means the "
689
+ "price is untrustworthy."
690
+ ),
691
+ reference="web3-audit skill §5 Oracle (bug B: missing confidence interval)",
692
+ ))
693
+
694
+ # OR-3: TWAP window shorter than 1800s (0 = the "now" endpoint, not a window)
695
+ for m in re.finditer(r"secondsAgos\s*\[\s*\d+\s*\]\s*=\s*(\d+)", text):
696
+ window = int(m.group(1))
697
+ if 0 < window < 1800:
698
+ ln = text[: m.start()].count("\n") + 1
699
+ findings.append(Finding(
700
+ rule_id="OR-3",
701
+ bug_class="Oracle",
702
+ severity="Medium",
703
+ confidence="High",
704
+ title=f"TWAP window of {m.group(1)}s is too short (flash-loan manipulable)",
705
+ location=f"{filename}:{ln}",
706
+ line=ln,
707
+ code=snippet(lines, ln),
708
+ recommendation="Use a minimum 1800s (30 min) TWAP. A 60s window "
709
+ "can be shifted for its entire length by one flash "
710
+ "loan.",
711
+ reference="web3-audit skill §5 Oracle (bug C: TWAP too short)",
712
+ ))
713
+
714
+ # OR-4 / FL-1: spot price from reserves / slot0
715
+ for m in re.finditer(r"getReserves\s*\(|getAmountsOut\s*\(|\bslot0\s*\(", text):
716
+ if _is_declaration_match(text, m.start()):
717
+ continue
718
+ ln = text[: m.start()].count("\n") + 1
719
+ fn = next((f for f in funcs if f.start_line <= ln <= f.end_line), None)
720
+ if fn is None:
721
+ continue # interface-level declaration, not a call
722
+ findings.append(Finding(
723
+ rule_id="OR-4",
724
+ bug_class="Oracle / Flash Loan",
725
+ severity="High",
726
+ confidence="Medium",
727
+ title="Spot price read from pool reserves / slot0 — flash-loan manipulable",
728
+ location=f"{filename}:{ln}",
729
+ line=ln,
730
+ code=snippet(lines, ln),
731
+ recommendation=(
732
+ "Never price from a single spot source. Use Chainlink as "
733
+ "primary with a Uniswap TWAP fallback and require the two to "
734
+ "agree closely."
735
+ ),
736
+ reference="web3-audit skill §5 Oracle (bug D) + §8 Flash Loan",
737
+ ))
738
+
739
+
740
+ # ---------------------------------------------------------------------------
741
+ # Class 6 — ERC4626 vault attacks
742
+ # ---------------------------------------------------------------------------
743
+
744
+ def _check_erc4626(lines, funcs, findings, filename):
745
+ text = joined_code(lines)
746
+ names = {f.name for f in funcs}
747
+ is_vault = bool(names & {"deposit", "mint", "withdraw", "redeem"}) \
748
+ and re.search(r"ERC4626|ERC-4626|4626", text)
749
+ if not is_vault:
750
+ return
751
+ if "_decimalsOffset" not in text:
752
+ ln = next((f.start_line for f in funcs if f.name == "deposit"), 1)
753
+ findings.append(Finding(
754
+ rule_id="E4626-1",
755
+ bug_class="ERC4626 Vault",
756
+ severity="Medium",
757
+ confidence="Medium",
758
+ title="ERC4626 vault has no virtual-share offset (first-depositor attack)",
759
+ location=f"{filename}:{ln}",
760
+ line=ln,
761
+ code=snippet(lines, ln),
762
+ recommendation=(
763
+ "Override _decimalsOffset() to return 9 (OpenZeppelin v4.9+ "
764
+ "virtual shares). Without it, an attacker deposits 1 wei, "
765
+ "donates assets directly, and later depositors round down to "
766
+ "0 shares."
767
+ ),
768
+ reference="web3-audit skill §6 ERC4626 (exchange rate manipulation)",
769
+ ))
770
+ # E4626-2: transfer moves shares but lock records stay behind
771
+ for fn in funcs:
772
+ if fn.name in ("transfer", "transferFrom") and re.search(
773
+ r"lock|stake|vest", text, re.IGNORECASE):
774
+ if not re.search(r"lock|stake|vest", fn.body, re.IGNORECASE):
775
+ ln = first_match_line(fn.body_lines, r"\b_transfer\s*\(")
776
+ findings.append(Finding(
777
+ rule_id="E4626-2",
778
+ bug_class="ERC4626 Vault",
779
+ severity="Medium",
780
+ confidence="Medium",
781
+ title=f"{fn.name}() moves shares but does not move lock/stake records",
782
+ location=f"{filename}:{ln} (function {fn.name})",
783
+ line=ln,
784
+ code=snippet(lines, ln),
785
+ recommendation=(
786
+ "Transfer the lock/stake record together with the shares, "
787
+ "or the new owner holds shares that can never be redeemed "
788
+ "(permanent freeze)."
789
+ ),
790
+ reference="web3-audit skill §6 ERC4626 (transfer without stake records)",
791
+ ))
792
+
793
+
794
+ # ---------------------------------------------------------------------------
795
+ # Class 7 — Reentrancy
796
+ # ---------------------------------------------------------------------------
797
+
798
+ _EXTERNAL_CALL_RE = re.compile(
799
+ r"\.call\s*\{[^}]*value|\.call\s*\(|"
800
+ r"\.transfer\s*\(|\.send\s*\(|safeTransfer\s*\(|safeTransferFrom\s*\("
801
+ )
802
+ _STATE_WRITE_RE = re.compile(
803
+ r"\b(balances|shares|total\w+|amounts|deposits|stakes)\b\s*(\[[^\]]*\])?\s*[-+*/]?="
804
+ )
805
+
806
+
807
+ def _check_reentrancy(lines, funcs, findings, filename):
808
+ for fn in funcs:
809
+ if fn.visibility not in ("external", "public"):
810
+ continue
811
+ call_lines = [ln for ln, t in fn.body_lines
812
+ if _EXTERNAL_CALL_RE.search(t)]
813
+ if not call_lines:
814
+ continue
815
+ first_call = call_lines[0]
816
+ writes_after = [ln for ln, t in fn.body_lines
817
+ if ln > first_call and _STATE_WRITE_RE.search(t)]
818
+ if writes_after:
819
+ findings.append(Finding(
820
+ rule_id="RE-1",
821
+ bug_class="Reentrancy",
822
+ severity="High",
823
+ confidence="Medium",
824
+ title=f"State updated AFTER an external call in {fn.name}() (CEI violation)",
825
+ location=f"{filename}:{writes_after[0]} (function {fn.name})",
826
+ line=writes_after[0],
827
+ code=snippet(lines, writes_after[0]),
828
+ recommendation=(
829
+ "Follow Checks-Effects-Interactions: update all state "
830
+ "BEFORE the external call, and add nonReentrant to "
831
+ "withdraw/redeem/claim functions. Cross-function and "
832
+ "read-only reentrancy still apply even with CEI."
833
+ ),
834
+ reference="web3-audit skill §7 Reentrancy",
835
+ ))
836
+ if fn.name.lower() in ("withdraw", "redeem", "claim", "harvest",
837
+ "unstake", "exit") \
838
+ and "nonReentrant" not in fn.modifiers:
839
+ findings.append(Finding(
840
+ rule_id="RE-2",
841
+ bug_class="Reentrancy",
842
+ severity="Low",
843
+ confidence="Low",
844
+ title=f"{fn.name}() has no nonReentrant guard",
845
+ location=f"{filename}:{fn.start_line} (function {fn.name})",
846
+ line=fn.start_line,
847
+ code=snippet(lines, fn.start_line),
848
+ recommendation=(
849
+ "Consider adding nonReentrant. It is defense-in-depth if "
850
+ "the function already follows CEI, and essential if it does "
851
+ "not."
852
+ ),
853
+ reference="web3-audit skill §7 Reentrancy",
854
+ ))
855
+
856
+
857
+ # ---------------------------------------------------------------------------
858
+ # Class 9 — Signature replay
859
+ # ---------------------------------------------------------------------------
860
+
861
+ def _check_signatures(lines, funcs, findings, filename):
862
+ text = joined_code(lines)
863
+ for m in re.finditer(r"ecrecover\s*\(|ECDSA\.recover\s*\(", text):
864
+ if _is_declaration_match(text, m.start()):
865
+ continue
866
+ ln = text[: m.start()].count("\n") + 1
867
+ fn = next((f for f in funcs if f.start_line <= ln <= f.end_line), None)
868
+ scope = fn.body if fn else text
869
+ # the signed hash: look for the keccak256/abi.encode near it
870
+ if not re.search(r"\bnonce\b|_nonces|nonces\[", scope):
871
+ findings.append(Finding(
872
+ rule_id="SIG-1",
873
+ bug_class="Signature Replay",
874
+ severity="High",
875
+ confidence="Medium",
876
+ title="Signature verified without a nonce — replayable",
877
+ location=f"{filename}:{ln}" + (f" (function {fn.name})" if fn else ""),
878
+ line=ln,
879
+ code=snippet(lines, ln),
880
+ recommendation=(
881
+ "Include a per-user nonce in the signed hash and mark it "
882
+ "used after verification, so the same signature cannot be "
883
+ "submitted twice."
884
+ ),
885
+ reference="web3-audit skill §9 Signature Replay (missing nonce)",
886
+ ))
887
+ if not re.search(r"chainid|chainId|block\.chainid", scope):
888
+ findings.append(Finding(
889
+ rule_id="SIG-2",
890
+ bug_class="Signature Replay",
891
+ severity="Medium",
892
+ confidence="Medium",
893
+ title="Signed hash does not include the chain ID — valid on every chain",
894
+ location=f"{filename}:{ln}" + (f" (function {fn.name})" if fn else ""),
895
+ line=ln,
896
+ code=snippet(lines, ln),
897
+ recommendation=(
898
+ "Include block.chainid (and the contract address) in the "
899
+ "signed hash so a signature cannot be replayed on a fork or "
900
+ "another chain."
901
+ ),
902
+ reference="web3-audit skill §9 Signature Replay (missing chain ID)",
903
+ ))
904
+
905
+
906
+ # ---------------------------------------------------------------------------
907
+ # Class 10 — Proxy / upgrade issues
908
+ # ---------------------------------------------------------------------------
909
+
910
+ def _check_proxy(lines, funcs, findings, filename):
911
+ text = joined_code(lines)
912
+ if re.search(r"\binitialize\s*\(", text) \
913
+ and "_disableInitializers" not in text:
914
+ for fn in funcs:
915
+ if fn.name == "initialize":
916
+ findings.append(Finding(
917
+ rule_id="PX-1",
918
+ bug_class="Proxy / Upgrade",
919
+ severity="Medium",
920
+ confidence="Medium",
921
+ title="No _disableInitializers() — the implementation itself can be initialized",
922
+ location=f"{filename}:{fn.start_line} (function initialize)",
923
+ line=fn.start_line,
924
+ code=snippet(lines, fn.start_line),
925
+ recommendation=(
926
+ "Add constructor() { _disableInitializers(); } so nobody "
927
+ "can call initialize() on the implementation contract and "
928
+ "then upgradeTo() a malicious logic contract."
929
+ ),
930
+ reference="web3-audit skill §10 Proxy (uninitialized implementation)",
931
+ ))
932
+ break
933
+ for m in re.finditer(r"\.delegatecall\s*\(", text):
934
+ if _is_declaration_match(text, m.start()):
935
+ continue
936
+ ln = text[: m.start()].count("\n") + 1
937
+ fn = next((f for f in funcs if f.start_line <= ln <= f.end_line), None)
938
+ # target is a function parameter => user-controlled
939
+ user_controlled = False
940
+ if fn:
941
+ params = re.search(r"function\s+\w+\s*\(([^)]*)\)", fn.body)
942
+ if params:
943
+ param_names = [p.strip().split()[-1] for p in
944
+ params.group(1).split(",") if p.strip()]
945
+ call_ctx = snippet(lines, ln)
946
+ user_controlled = any(p in call_ctx for p in param_names)
947
+ findings.append(Finding(
948
+ rule_id="PX-2",
949
+ bug_class="Proxy / Upgrade",
950
+ severity="High" if user_controlled else "Medium",
951
+ confidence="Medium",
952
+ title="delegatecall" + (" to a caller-supplied address" if user_controlled else " present — verify the target is trusted"),
953
+ location=f"{filename}:{ln}" + (f" (function {fn.name})" if fn else ""),
954
+ line=ln,
955
+ code=snippet(lines, ln),
956
+ recommendation=(
957
+ "delegatecall runs the target's code in this contract's storage "
958
+ "context. Only ever delegatecall to a fixed, audited "
959
+ "implementation — never to an address supplied by the caller."
960
+ ),
961
+ reference="web3-audit skill §10 Proxy (delegatecall to user-controlled address)",
962
+ ))
963
+
964
+
965
+ # ---------------------------------------------------------------------------
966
+ # Entry point
967
+ # ---------------------------------------------------------------------------
968
+
969
+ CHECKS = [
970
+ ("Accounting Desync", _check_accounting),
971
+ ("Access Control", _check_access_control),
972
+ ("Incomplete Path", _check_incomplete_path),
973
+ ("Off-by-One", _check_off_by_one),
974
+ ("Oracle", _check_oracle),
975
+ ("ERC4626 Vault", _check_erc4626),
976
+ ("Reentrancy", _check_reentrancy),
977
+ ("Signature Replay", _check_signatures),
978
+ ("Proxy / Upgrade", _check_proxy),
979
+ ]
980
+
981
+ CHECKLIST = [
982
+ {"class": "Accounting Desync", "share": "28% of Criticals",
983
+ "what": "Two state variables that must stay in sync; one path updates A and forgets B.",
984
+ "checks": ["Early return in claim/redeem skipping state updates",
985
+ "Share price computed before totals update"]},
986
+ {"class": "Access Control", "share": "19% of Criticals",
987
+ "what": "Missing modifier on a sibling function; existence vs ownership; silent modifier; uninitialized proxy.",
988
+ "checks": ["Sibling functions with different modifier sets",
989
+ "initialize() without `initializer`",
990
+ "Modifier body with `if` but no require/revert",
991
+ "_requireOwned() without an ownership check"]},
992
+ {"class": "Incomplete Path", "share": "17% of Criticals",
993
+ "what": "Function A does X; the reverse function B does not do the reverse of X.",
994
+ "checks": ["mint() bypassing deposit() validation",
995
+ "update/cancel without the refund the create path takes",
996
+ "safeApprove() without a zero reset"]},
997
+ {"class": "Off-by-One", "share": "22% of Highs",
998
+ "what": "Single-character boundary errors: > vs >=, i <= length.",
999
+ "checks": ["Strict comparisons on period/deadline boundaries",
1000
+ "`i <= array.length` loops", "`array[length - 1]` without an empty check"]},
1001
+ {"class": "Oracle", "share": "12% of reports",
1002
+ "what": "Stale prices, ignored confidence intervals, short TWAPs, single spot sources.",
1003
+ "checks": ["latestRoundData() without a staleness check",
1004
+ "Pyth getPriceUnsafe() without conf",
1005
+ "TWAP window under 1800s", "Spot price from reserves / slot0"]},
1006
+ {"class": "ERC4626 Vault", "share": "High",
1007
+ "what": "First-depositor exchange-rate manipulation; shares moved without lock records.",
1008
+ "checks": ["Vault without _decimalsOffset()",
1009
+ "transfer() without moving lock/stake records"]},
1010
+ {"class": "Reentrancy", "share": "Still paying in 2026",
1011
+ "what": "External call before state update; cross-function and read-only variants.",
1012
+ "checks": ["State writes after an external call (CEI violation)",
1013
+ "withdraw/redeem/claim without nonReentrant"]},
1014
+ {"class": "Flash Loan", "share": "Top-paid class on Immunefi",
1015
+ "what": "Borrow, manipulate a spot price, drain, repay — in one transaction.",
1016
+ "checks": ["Price reads from getReserves / getAmountsOut / slot0"]},
1017
+ {"class": "Signature Replay", "share": "High",
1018
+ "what": "Same signature usable twice, or on another chain.",
1019
+ "checks": ["ecrecover without a nonce in the signed hash",
1020
+ "Signed hash without block.chainid"]},
1021
+ {"class": "Proxy / Upgrade", "share": "High",
1022
+ "what": "Uninitialized implementation, storage collision, delegatecall to attacker address.",
1023
+ "checks": ["No _disableInitializers()",
1024
+ "delegatecall to a caller-supplied address"]},
1025
+ ]
1026
+
1027
+
1028
+ def audit_source(source: str, filename: str = "Contract.sol") -> dict:
1029
+ """Run all detectors over Solidity source. Returns a JSON-able report."""
1030
+ lines = strip_comments(source)
1031
+ funcs = parse_functions(lines)
1032
+ modifiers = parse_modifiers(lines)
1033
+ findings = []
1034
+ _check_accounting(lines, funcs, findings, filename)
1035
+ _check_access_control(lines, funcs, modifiers, findings, filename)
1036
+ _check_incomplete_path(lines, funcs, findings, filename)
1037
+ _check_off_by_one(lines, funcs, findings, filename)
1038
+ _check_oracle(lines, funcs, findings, filename)
1039
+ _check_erc4626(lines, funcs, findings, filename)
1040
+ _check_reentrancy(lines, funcs, findings, filename)
1041
+ _check_signatures(lines, funcs, findings, filename)
1042
+ _check_proxy(lines, funcs, findings, filename)
1043
+
1044
+ # de-duplicate identical (rule_id, line) hits
1045
+ seen = set()
1046
+ unique = []
1047
+ for f in findings:
1048
+ key = (f.rule_id, f.line, f.title)
1049
+ if key not in seen:
1050
+ seen.add(key)
1051
+ unique.append(f)
1052
+ unique.sort(key=lambda f: (-SEVERITY_ORDER[f.severity], f.line))
1053
+
1054
+ by_severity = {}
1055
+ for f in unique:
1056
+ by_severity[f.severity] = by_severity.get(f.severity, 0) + 1
1057
+ by_class = {}
1058
+ for f in unique:
1059
+ by_class[f.bug_class] = by_class.get(f.bug_class, 0) + 1
1060
+
1061
+ contracts = parse_contracts(lines, funcs)
1062
+ loc = len([t for _, t in lines if t.strip()])
1063
+
1064
+ return {
1065
+ "engine": "quick-audit",
1066
+ "engine_version": __version__,
1067
+ "filename": filename,
1068
+ "disclaimer": (
1069
+ "Static heuristic pre-screen. Findings are CANDIDATES, not confirmed "
1070
+ "vulnerabilities — verify each one manually, and prove impact with a "
1071
+ "Foundry PoC before treating it as a real finding."
1072
+ ),
1073
+ "stats": {
1074
+ "lines_of_code": loc,
1075
+ "contracts": [c.name for c in contracts],
1076
+ "functions": len(funcs),
1077
+ "findings_total": len(unique),
1078
+ "by_severity": by_severity,
1079
+ "by_class": by_class,
1080
+ },
1081
+ "findings": [f.to_dict() for f in unique],
1082
+ }
1083
+
1084
+
1085
+ def render_markdown(report: dict) -> str:
1086
+ """Render the report as Markdown (for copy/download)."""
1087
+ out = [f"# Quick-Audit Report — {report['filename']}", ""]
1088
+ out.append(f"> {report['disclaimer']}")
1089
+ out.append("")
1090
+ s = report["stats"]
1091
+ out.append(f"- Lines of code: {s['lines_of_code']}")
1092
+ out.append(f"- Contracts: {', '.join(s['contracts']) or '(none)'}")
1093
+ out.append(f"- Functions: {s['functions']}")
1094
+ out.append(f"- Findings: {s['findings_total']}")
1095
+ if s["by_severity"]:
1096
+ out.append("- By severity: " + ", ".join(
1097
+ f"{k} {v}" for k, v in sorted(
1098
+ s["by_severity"].items(),
1099
+ key=lambda kv: -SEVERITY_ORDER[kv[0]])))
1100
+ out.append("")
1101
+ if not report["findings"]:
1102
+ out.append("No findings. The 10-class heuristic scan found nothing — "
1103
+ "this is a good sign, not a guarantee.")
1104
+ return "\n".join(out)
1105
+ for i, f in enumerate(report["findings"], 1):
1106
+ out.append(f"## {i}. [{f['severity']}] {f['title']}")
1107
+ out.append("")
1108
+ out.append(f"- Rule: {f['rule_id']} · Class: {f['class']} · "
1109
+ f"Confidence: {f['confidence']}")
1110
+ out.append(f"- Location: {f['location']}")
1111
+ out.append(f"- Code: `{f['code']}`")
1112
+ out.append(f"- Fix: {f['recommendation']}")
1113
+ out.append(f"- Reference: {f['reference']}")
1114
+ out.append("")
1115
+ return "\n".join(out)
@@ -0,0 +1,15 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tool-dev-quick-audit"
7
+ version = "1.0.0"
8
+ description = "Executa for the Quick-Audit Anna App: static 10-class audit for Solidity contracts"
9
+ requires-python = ">=3.10"
10
+
11
+ [project.scripts]
12
+ "tool-dev-quick-audit" = "quick_audit_plugin:main"
13
+
14
+ [tool.setuptools]
15
+ py-modules = ["quick_audit_plugin", "audit_engine"]
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env python3
2
+ """quick-audit — Anna Executa plugin (Python, stdio JSON-RPC 2.0).
3
+
4
+ Tools:
5
+ audit_contract — run the 10-class static audit over Solidity source.
6
+ get_checklist — return the 10-class audit checklist (reference).
7
+
8
+ Protocol: one JSON-RPC request per line on stdin, one response per line on
9
+ stdout. Logs go to stderr only (anything else on stdout breaks the protocol).
10
+ See https://anna.partners/developers/tools/executa-python
11
+ """
12
+
13
+ import json
14
+ import os
15
+ import sys
16
+
17
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18
+
19
+ from audit_engine import CHECKLIST, audit_source, render_markdown # noqa: E402
20
+
21
+ MANIFEST = {
22
+ "name": "tool-dev-quick-audit",
23
+ "display_name": "Quick-Audit Smart Contract",
24
+ "version": "1.0.0",
25
+ "description": (
26
+ "Static pre-screen for Solidity contracts across 10 DeFi bug classes "
27
+ "(accounting desync, access control, incomplete path, off-by-one, "
28
+ "oracle, ERC4626, reentrancy, flash loan, signature replay, proxy). "
29
+ "Paste source or upload a .sol file; returns findings with severity, "
30
+ "confidence, code location and fix guidance. No paid APIs."
31
+ ),
32
+ "author": "saroka",
33
+ "category": "developer-tools",
34
+ "license": "MIT",
35
+ "tools": [
36
+ {
37
+ "name": "audit_contract",
38
+ "description": (
39
+ "Audit Solidity source code with the 10-class static checklist. "
40
+ "Returns findings (severity, confidence, location, evidence, "
41
+ "fix) plus a Markdown report. Findings are candidates — verify "
42
+ "manually before acting."
43
+ ),
44
+ "timeout": 120,
45
+ "parameters": {
46
+ "type": "object",
47
+ "properties": {
48
+ "source": {
49
+ "type": "string",
50
+ "description": "Solidity source code to audit",
51
+ },
52
+ "filename": {
53
+ "type": "string",
54
+ "description": "Display name for the source (e.g. Vault.sol)",
55
+ },
56
+ "explain": {
57
+ "type": "boolean",
58
+ "description": "Also ask the free keyless LLM to explain each "
59
+ "finding in plain language (optional, default false)",
60
+ },
61
+ },
62
+ "required": ["source"],
63
+ "additionalProperties": False,
64
+ },
65
+ },
66
+ {
67
+ "name": "get_checklist",
68
+ "description": "Return the 10-class audit checklist this tool checks.",
69
+ "parameters": {
70
+ "type": "object",
71
+ "properties": {},
72
+ "additionalProperties": False,
73
+ },
74
+ },
75
+ ],
76
+ }
77
+
78
+ # Free keyless LLM (APIsFreeLLM) — optional plain-language explanations only.
79
+ LLM_URL = "https://api.apisfreellm.com/v1/chat/completions"
80
+ LLM_MODEL = "free-ai"
81
+
82
+
83
+ def _explain_with_free_llm(findings, filename):
84
+ """Ask the free keyless LLM to explain findings. Never blocks the audit."""
85
+ try:
86
+ import urllib.request
87
+ except Exception:
88
+ return None, "urllib unavailable"
89
+ bullets = "\n".join(
90
+ f"- [{f['severity']}] {f['title']} ({f['location']})"
91
+ for f in findings[:15]
92
+ )
93
+ prompt = (
94
+ "You are a smart-contract security reviewer. Explain each finding below "
95
+ "in 1-2 plain sentences for a developer who is not a security expert: "
96
+ "what the bug is, and why it matters. Do not invent new findings.\n\n"
97
+ f"Contract: {filename}\n{bullets}"
98
+ )
99
+ body = json.dumps({
100
+ "model": LLM_MODEL,
101
+ "messages": [{"role": "user", "content": prompt}],
102
+ "max_tokens": 1200,
103
+ }).encode()
104
+ req = urllib.request.Request(
105
+ LLM_URL, data=body,
106
+ headers={"Content-Type": "application/json"},
107
+ )
108
+ try:
109
+ with urllib.request.urlopen(req, timeout=25) as resp:
110
+ data = json.loads(resp.read().decode())
111
+ text = data["choices"][0]["message"]["content"]
112
+ return text, None
113
+ except Exception as exc: # noqa: BLE001 - LLM is best-effort
114
+ return None, str(exc)
115
+
116
+
117
+ def invoke(tool: str, args: dict) -> dict:
118
+ if tool == "get_checklist":
119
+ return {"success": True, "data": {"checklist": CHECKLIST}}
120
+
121
+ if tool == "audit_contract":
122
+ source = (args.get("source") or "").strip()
123
+ if not source:
124
+ return {"success": False,
125
+ "error": "source is empty — paste Solidity code or upload a .sol file"}
126
+ if len(source) > 500_000:
127
+ return {"success": False,
128
+ "error": "source too large (max 500 KB)"}
129
+ filename = args.get("filename") or "Contract.sol"
130
+ report = audit_source(source, filename)
131
+ report["markdown"] = render_markdown(report)
132
+ if args.get("explain"):
133
+ text, err = _explain_with_free_llm(report["findings"], filename)
134
+ if text:
135
+ report["plain_language_explanation"] = text
136
+ else:
137
+ report["explain_error"] = (
138
+ "Free LLM unavailable (%s); findings above are unaffected."
139
+ % err
140
+ )
141
+ return {"success": True, "data": report}
142
+
143
+ raise ValueError(f"unknown tool: {tool}")
144
+
145
+
146
+ def handle(req: dict) -> dict:
147
+ method = req.get("method")
148
+ if method == "describe":
149
+ return {"result": MANIFEST}
150
+ if method == "invoke":
151
+ params = req.get("params") or {}
152
+ try:
153
+ return {"result": invoke(params.get("tool", ""),
154
+ params.get("arguments") or {})}
155
+ except ValueError as exc:
156
+ return {"error": {"code": -32601, "message": str(exc)}}
157
+ except Exception as exc: # noqa: BLE001
158
+ return {"error": {"code": -32603, "message": str(exc)}}
159
+ if method == "health":
160
+ return {"result": {"status": "ready"}}
161
+ return {"error": {"code": -32601, "message": f"unknown method: {method}"}}
162
+
163
+
164
+ def main() -> None:
165
+ for line in sys.stdin:
166
+ line = line.strip()
167
+ if not line:
168
+ continue
169
+ try:
170
+ req = json.loads(line)
171
+ except json.JSONDecodeError as exc:
172
+ payload = {"error": {"code": -32700, "message": str(exc)}}
173
+ req_id = None
174
+ else:
175
+ payload = handle(req)
176
+ req_id = req.get("id")
177
+ sys.stdout.write(json.dumps(
178
+ {"jsonrpc": "2.0", "id": req_id, **payload}) + "\n")
179
+ sys.stdout.flush()
180
+
181
+
182
+ if __name__ == "__main__":
183
+ main()
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: tool-dev-quick-audit
3
+ Version: 1.0.0
4
+ Summary: Executa for the Quick-Audit Anna App: static 10-class audit for Solidity contracts
5
+ Requires-Python: >=3.10
@@ -0,0 +1,8 @@
1
+ audit_engine.py
2
+ pyproject.toml
3
+ quick_audit_plugin.py
4
+ tool_dev_quick_audit.egg-info/PKG-INFO
5
+ tool_dev_quick_audit.egg-info/SOURCES.txt
6
+ tool_dev_quick_audit.egg-info/dependency_links.txt
7
+ tool_dev_quick_audit.egg-info/entry_points.txt
8
+ tool_dev_quick_audit.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tool-dev-quick-audit = quick_audit_plugin:main
@@ -0,0 +1,2 @@
1
+ audit_engine
2
+ quick_audit_plugin