soumyagoel11 commited on
Commit
3ae089d
·
1 Parent(s): e3518f4

Update grader and inference

Browse files
__pycache__/environment.cpython-311.pyc ADDED
Binary file (5.43 kB). View file
 
__pycache__/graders.cpython-311.pyc ADDED
Binary file (6.28 kB). View file
 
graders.py CHANGED
@@ -20,10 +20,57 @@ def _normalize_issue(issue: Dict[str, Any]) -> Issue:
20
 
21
 
22
  def _match_issue(pred: Issue, expected: Issue) -> bool:
23
- if pred.issue_type.lower() != expected.issue_type.lower():
24
- return False
25
- if pred.severity.lower() != expected.severity.lower():
26
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  return True
28
 
29
 
@@ -75,4 +122,4 @@ def grade_action(action: List[Dict[str, Any]], expected: List[Dict[str, Any]]) -
75
  "line_bonus": round(min(line_bonus_total, 0.2), 3),
76
  "score": round(score, 4),
77
  }
78
- return score, details
 
20
 
21
 
22
  def _match_issue(pred: Issue, expected: Issue) -> bool:
23
+ pred_type = pred.issue_type.lower()
24
+ exp_type = expected.issue_type.lower()
25
+
26
+ type_variations = {
27
+ "missing_spdx": ["spdx", "license", "licensing"],
28
+ "old_compiler_version": ["compiler", "pragma", "version"],
29
+ "missing_natspec": ["natspec", "documentation", "doc comment"],
30
+ "deprecated_constructor": ["constructor", "deprecated"],
31
+ "unbounded_loop": ["loop", "unbounded", "dynamic array"],
32
+ "redundant_storage_read": ["storage read", "redundant", "cache", "sload", "repeated storage"],
33
+ "custom_error_missing": ["custom error", "require string"],
34
+ "reentrancy": ["reentrancy", "re-entrancy", "re-entry"],
35
+ "missing_access_control": ["access control", "authorization", "owner only"],
36
+ "tx_origin_auth": ["tx.origin", "tx origin"],
37
+ }
38
+
39
+ matched_type = True
40
+ if pred_type != exp_type:
41
+ matched_type = False
42
+ if exp_type in type_variations:
43
+ for variation in type_variations[exp_type]:
44
+ if variation in pred_type or pred_type in variation:
45
+ matched_type = True
46
+ break
47
+ if not matched_type:
48
+ for key, variations in type_variations.items():
49
+ for v in variations:
50
+ if v in pred_type and v in exp_type:
51
+ matched_type = True
52
+ break
53
+ if matched_type:
54
+ break
55
+ if not matched_type:
56
+ return False
57
+
58
+ pred_sev = pred.severity.lower()
59
+ exp_sev = expected.severity.lower()
60
+
61
+ severity_map = {
62
+ "critical": ["critical", "high", "severe", "danger", "major", "important"],
63
+ "medium": ["medium", "moderate", "warning", "medium-high", "average"],
64
+ "low": ["low", "minor", "informational", "info", "minor issue", "cosmetic"],
65
+ "info": ["info", "information", "low", "informational", "note"],
66
+ }
67
+
68
+ if pred_sev != exp_sev:
69
+ if exp_sev in severity_map:
70
+ matched_sev = any(s in pred_sev for s in severity_map[exp_sev])
71
+ if not matched_sev:
72
+ return False
73
+
74
  return True
75
 
76
 
 
122
  "line_bonus": round(min(line_bonus_total, 0.2), 3),
123
  "score": round(score, 4),
124
  }
125
+ return score, details
inference.py CHANGED
@@ -9,7 +9,7 @@ from environment import SolidityGuardEnv
9
 
10
 
11
  def _log(tag: str, payload: Dict[str, Any]) -> None:
12
- print(f"[{tag}] {json.dumps(payload, ensure_ascii=True)}")
13
 
14
 
15
  def _load_env_var(name: str) -> str:
@@ -26,18 +26,30 @@ def _call_model(prompt: str) -> List[Dict[str, Any]]:
26
  model_name = _load_env_var("MODEL_NAME")
27
  hf_token = _load_env_var("HF_TOKEN")
28
 
29
- client = OpenAI(base_url=api_base_url, api_key=hf_token)
30
- response = client.chat.completions.create(
31
- model=model_name,
32
- messages=[
33
- {"role": "system", "content": "You are a Solidity security reviewer."},
34
- {"role": "user", "content": prompt},
35
- ],
36
- temperature=0.0,
37
- max_tokens=800,
38
- )
 
39
 
40
- content = response.choices[0].message.content or "[]"
 
 
 
 
 
 
 
 
 
 
 
41
  try:
42
  parsed = json.loads(content)
43
  except json.JSONDecodeError:
@@ -48,10 +60,15 @@ def _call_model(prompt: str) -> List[Dict[str, Any]]:
48
 
49
 
50
  def _build_prompt(source_code: str, task_id: str) -> str:
 
 
 
 
 
51
  return (
52
  "Review the Solidity contract and return a JSON array of findings. "
53
- "Each finding must include: issue_type, line_number, description, severity. "
54
- f"Task: {task_id}.\n\n"
55
  f"Contract:\n{source_code}"
56
  )
57
 
@@ -97,4 +114,4 @@ if __name__ == "__main__":
97
  sys.exit(run())
98
  except Exception as exc:
99
  _log("END", {"final_score": 0.0, "error": str(exc)})
100
- sys.exit(1)
 
9
 
10
 
11
  def _log(tag: str, payload: Dict[str, Any]) -> None:
12
+ print(f"[{tag}] {json.dumps(payload, ensure_ascii=False)}")
13
 
14
 
15
  def _load_env_var(name: str) -> str:
 
26
  model_name = _load_env_var("MODEL_NAME")
27
  hf_token = _load_env_var("HF_TOKEN")
28
 
29
+ try:
30
+ client = OpenAI(base_url=api_base_url, api_key=hf_token)
31
+ response = client.chat.completions.create(
32
+ model=model_name,
33
+ messages=[
34
+ {"role": "system", "content": "You are a Solidity security reviewer. Always respond with valid JSON array only, no explanations."},
35
+ {"role": "user", "content": prompt},
36
+ ],
37
+ temperature=0.1,
38
+ max_tokens=1024,
39
+ )
40
 
41
+ content = response.choices[0].message.content or "[]"
42
+ except Exception:
43
+ content = "[]"
44
+
45
+ if content.startswith("```"):
46
+ parts = content.split("```")
47
+ if len(parts) >= 3:
48
+ content = parts[1]
49
+ if content.startswith("json"):
50
+ content = content[4:]
51
+ content = content.strip()
52
+
53
  try:
54
  parsed = json.loads(content)
55
  except json.JSONDecodeError:
 
60
 
61
 
62
  def _build_prompt(source_code: str, task_id: str) -> str:
63
+ task_info = {
64
+ "task_1_best_practices": "Find syntax and best-practice issues: missing SPDX license, old compiler version (<0.8.x), missing NatSpec comments, deprecated constructor syntax.",
65
+ "task_2_gas_optimization": "Find gas optimization opportunities: unbounded loops, redundant storage reads, missing custom errors (use custom errors instead of require strings).",
66
+ "task_3_security": "Find security vulnerabilities: reentrancy bugs, missing access control, tx.origin usage for authorization, integer overflow/underflow.",
67
+ }
68
  return (
69
  "Review the Solidity contract and return a JSON array of findings. "
70
+ "Each finding must include: issue_type, line_number, description, severity (Critical/Medium/Low/Info). "
71
+ f"Focus on: {task_info.get(task_id, task_id)}\n\n"
72
  f"Contract:\n{source_code}"
73
  )
74
 
 
114
  sys.exit(run())
115
  except Exception as exc:
116
  _log("END", {"final_score": 0.0, "error": str(exc)})
117
+ sys.exit(1)