|
| 1 | +# GasGuard Finding Metadata System |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +The Finding Metadata System provides structured, standardized information about every optimization finding in GasGuard. It ensures consistent representation of severity, impact estimates, and educational resources across all CLI and API outputs. |
| 6 | + |
| 7 | +## Architecture |
| 8 | + |
| 9 | +### Core Components |
| 10 | + |
| 11 | +#### 1. **FindingMetadata Interface** (`finding-metadata.interface.ts`) |
| 12 | + |
| 13 | +The central data structure containing: |
| 14 | + |
| 15 | +- **Severity & Confidence**: Assessment of the issue |
| 16 | +- **Impact Estimates**: Quantified gas/storage savings |
| 17 | +- **Educational Links**: Learning resources |
| 18 | +- **Mitigation Steps**: How to fix the issue |
| 19 | +- **Related Information**: Tags, affected aspects, related rules |
| 20 | + |
| 21 | +```typescript |
| 22 | +interface FindingMetadata { |
| 23 | + severity: SeverityLevel; // critical, high, medium, low, info |
| 24 | + confidence: ConfidenceLevel; // critical, high, medium, low, uncertain |
| 25 | + confidenceScore: number; // 0-100 |
| 26 | + impacts: ImpactEstimate[]; // Array of quantified impacts |
| 27 | + educationalLinks: EducationalLink[]; // Learning resources |
| 28 | + affectedAspects: string[]; // System areas affected |
| 29 | + mitigation?: string; // Fix instructions |
| 30 | + relatedRules?: string[]; // Connected rules |
| 31 | + tags?: string[]; // Custom categorization |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +#### 2. **FindingMetadataBuilder** (`finding-metadata.interface.ts`) |
| 36 | + |
| 37 | +Fluent API for safely constructing metadata objects: |
| 38 | + |
| 39 | +```typescript |
| 40 | +const metadata = new FindingMetadataBuilder() |
| 41 | + .setSeverity(SeverityLevel.HIGH) |
| 42 | + .setConfidence(ConfidenceLevel.HIGH, 92) |
| 43 | + .addImpact({ |
| 44 | + type: ImpactType.GAS, |
| 45 | + amount: 5000, |
| 46 | + unit: 'gas', |
| 47 | + description: 'Gas cost reduction from optimized storage access' |
| 48 | + }) |
| 49 | + .addEducationalLink({ |
| 50 | + title: 'Solidity Docs', |
| 51 | + url: 'https://docs.soliditylang.org/...', |
| 52 | + source: 'documentation' |
| 53 | + }) |
| 54 | + .setAffectedAspects(['storage-layout', 'gas-usage']) |
| 55 | + .setMitigation('Reorder state variables for better packing') |
| 56 | + .build(); |
| 57 | +``` |
| 58 | + |
| 59 | +#### 3. **FindingMetadataFactory** (`finding-metadata.factory.ts`) |
| 60 | + |
| 61 | +Factory for consistent metadata creation with a built-in rule catalog: |
| 62 | + |
| 63 | +```typescript |
| 64 | +// Create metadata for a known rule |
| 65 | +const metadata = FindingMetadataFactory.createForRule('unused-state-variables'); |
| 66 | + |
| 67 | +// List all available rules |
| 68 | +const rules = FindingMetadataFactory.getAvailableRules(); |
| 69 | + |
| 70 | +// Validate metadata |
| 71 | +const validation = FindingMetadataFactory.validate(metadata); |
| 72 | +``` |
| 73 | + |
| 74 | +**Built-in Rule Configurations:** |
| 75 | +- `unused-state-variables` |
| 76 | +- `redundant-external` |
| 77 | +- `storage-layout-optimization` |
| 78 | +- `function-complexity` |
| 79 | + |
| 80 | +#### 4. **CLI Formatters** |
| 81 | + |
| 82 | +##### MetadataCliFormatter (`metadata-cli.formatter.ts`) |
| 83 | + |
| 84 | +Rich terminal output with formatting: |
| 85 | + |
| 86 | +```typescript |
| 87 | +// Detailed finding with all metadata |
| 88 | +const output = MetadataCliFormatter.formatFindingWithMetadata(violation); |
| 89 | + |
| 90 | +// Summary with severity breakdown |
| 91 | +const summary = MetadataCliFormatter.formatSummaryWithMetadata(violations); |
| 92 | + |
| 93 | +// JSON for programmatic access |
| 94 | +const json = MetadataCliFormatter.toJSON(violation); |
| 95 | +``` |
| 96 | + |
| 97 | +##### MetadataTableFormatter |
| 98 | + |
| 99 | +Compact table view of findings: |
| 100 | + |
| 101 | +```typescript |
| 102 | +const table = MetadataTableFormatter.formatAsTable(violations); |
| 103 | +``` |
| 104 | + |
| 105 | +#### 5. **Analysis Result Handler** (`analysis-result-handler.ts`) |
| 106 | + |
| 107 | +High-level CLI command handler: |
| 108 | + |
| 109 | +```typescript |
| 110 | +// Display results in various formats |
| 111 | +const output = AnalysisResultCliHandler.displayResults(violations, { |
| 112 | + format: 'detailed', // 'detailed', 'table', 'json' |
| 113 | + includeEducational: true, |
| 114 | + verbose: false |
| 115 | +}); |
| 116 | + |
| 117 | +// Get recommendations based on metadata |
| 118 | +const recommendations = AnalysisResultCliHandler.getRecommendations(violations); |
| 119 | + |
| 120 | +// Export to JSON with full metadata |
| 121 | +const json = AnalysisResultCliHandler.exportToJson(violations); |
| 122 | +``` |
| 123 | + |
| 124 | +## Integration Points |
| 125 | + |
| 126 | +### API Layer |
| 127 | + |
| 128 | +**AnalyzerService** automatically attaches metadata to violations: |
| 129 | + |
| 130 | +```typescript |
| 131 | +async analyzeCode(code: string, source: string): Promise<AnalysisReport> { |
| 132 | + // ... |
| 133 | + const formattedViolations = this.formatViolations(scanResult.violations); |
| 134 | + // Metadata is automatically added in formatViolations() |
| 135 | + // ... |
| 136 | +} |
| 137 | +``` |
| 138 | + |
| 139 | +Response includes: |
| 140 | + |
| 141 | +```json |
| 142 | +{ |
| 143 | + "violations": [ |
| 144 | + { |
| 145 | + "ruleName": "unused-state-variables", |
| 146 | + "severity": "medium", |
| 147 | + "metadata": { |
| 148 | + "severity": "medium", |
| 149 | + "confidence": "critical", |
| 150 | + "confidenceScore": 98, |
| 151 | + "impacts": [ |
| 152 | + { |
| 153 | + "type": "storage", |
| 154 | + "amount": 2500, |
| 155 | + "unit": "bytes", |
| 156 | + "description": "..." |
| 157 | + } |
| 158 | + ], |
| 159 | + "educationalLinks": [...], |
| 160 | + "affectedAspects": [...], |
| 161 | + "mitigation": "...", |
| 162 | + "tags": [...] |
| 163 | + } |
| 164 | + } |
| 165 | + ] |
| 166 | +} |
| 167 | +``` |
| 168 | + |
| 169 | +### CLI Layer |
| 170 | + |
| 171 | +Use `AnalysisResultCliHandler` in CLI commands: |
| 172 | + |
| 173 | +```typescript |
| 174 | +async analyzeCommand(filePath: string, options: CliOptions) { |
| 175 | + const report = await this.analyzer.analyzeCode(code, filePath); |
| 176 | + |
| 177 | + const output = AnalysisResultCliHandler.displayResults( |
| 178 | + report.violations, |
| 179 | + { |
| 180 | + format: options.format, |
| 181 | + includeEducational: options.includeEducational |
| 182 | + } |
| 183 | + ); |
| 184 | + |
| 185 | + console.log(output); |
| 186 | +} |
| 187 | +``` |
| 188 | + |
| 189 | +## Severity & Confidence Levels |
| 190 | + |
| 191 | +### Severity (Issue Importance) |
| 192 | +- **CRITICAL**: Must fix immediately; security/correctness issue |
| 193 | +- **HIGH**: Significant impact; strong recommendation to fix |
| 194 | +- **MEDIUM**: Noticeable impact; recommended to fix |
| 195 | +- **LOW**: Minor impact; optional optimization |
| 196 | +- **INFO**: Informational; no action required |
| 197 | + |
| 198 | +### Confidence (Detection Reliability) |
| 199 | +- **CRITICAL**: 95-100% confidence in detection |
| 200 | +- **HIGH**: 80-95% confidence |
| 201 | +- **MEDIUM**: 60-80% confidence |
| 202 | +- **LOW**: 40-60% confidence |
| 203 | +- **UNCERTAIN**: <40% confidence |
| 204 | + |
| 205 | +## Impact Types |
| 206 | + |
| 207 | +- **GAS**: Estimated gas savings (in gas units) |
| 208 | +- **STORAGE**: Storage bytes saved |
| 209 | +- **SECURITY**: Security improvements |
| 210 | +- **MAINTAINABILITY**: Code quality improvements |
| 211 | +- **PERFORMANCE**: Performance benefits |
| 212 | + |
| 213 | +## Educational Resources |
| 214 | + |
| 215 | +Each finding includes educational links to help developers understand the issue: |
| 216 | + |
| 217 | +```typescript |
| 218 | +interface EducationalLink { |
| 219 | + title: string; // Link title |
| 220 | + url: string; // Full URL |
| 221 | + source?: 'documentation' | 'blog' | 'standard' | 'best-practice' | 'security'; |
| 222 | + description?: string; // Brief description of content |
| 223 | +} |
| 224 | +``` |
| 225 | + |
| 226 | +## Example: Complete Finding Output |
| 227 | + |
| 228 | +``` |
| 229 | +════════════════════════════════════════════════════════════════════════════════ |
| 230 | +⚠️ [UNUSED-STATE-VARIABLES] |
| 231 | +Description: Found unused state variable that consumes storage |
| 232 | +
|
| 233 | +Severity: 🟡 MEDIUM | Confidence: ✓✓✓ CRITICAL (98%) |
| 234 | +
|
| 235 | +📊 Impact Estimates: |
| 236 | + • STORAGE: 2500 bytes |
| 237 | + └─ Unused state variables consume storage slots that cannot be reclaimed |
| 238 | + • GAS: 20000 (5000-50000) gas |
| 239 | + └─ Gas cost to read/write unused variables in initialization |
| 240 | +
|
| 241 | +🎯 Affected Aspects: state-storage, deployment-cost, runtime-gas |
| 242 | +
|
| 243 | +🔧 How to Fix: |
| 244 | + Remove the unused state variable declaration from the contract |
| 245 | +
|
| 246 | +📚 Learn More: |
| 247 | + • Solidity Storage Optimization [documentation] |
| 248 | + https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html |
| 249 | + └─ Official Solidity documentation on storage layout |
| 250 | + • Gas Optimization Best Practices [best-practice] |
| 251 | + https://blog.openzeppelin.com/smart-contract-gas-optimization-tips/ |
| 252 | + └─ OpenZeppelin guide to smart contract gas optimization |
| 253 | +
|
| 254 | +🔗 Related Rules: uninitialized-state-variables, private-visibility |
| 255 | +
|
| 256 | +🏷️ Tags: storage-optimization, code-quality, removal |
| 257 | +
|
| 258 | +════════════════════════════════════════════════════════════════════════════════ |
| 259 | +``` |
| 260 | + |
| 261 | +## Adding New Rules |
| 262 | + |
| 263 | +### Step 1: Define Metadata Configuration |
| 264 | + |
| 265 | +Add to `RULE_METADATA_CATALOG` in `finding-metadata.factory.ts`: |
| 266 | + |
| 267 | +```typescript |
| 268 | +export const RULE_METADATA_CATALOG: Record<string, RuleMetadataConfig> = { |
| 269 | + 'my-new-rule': { |
| 270 | + ruleName: 'my-new-rule', |
| 271 | + severity: SeverityLevel.MEDIUM, |
| 272 | + confidence: ConfidenceLevel.HIGH, |
| 273 | + confidenceScore: 85, |
| 274 | + impacts: [ |
| 275 | + { |
| 276 | + type: ImpactType.GAS, |
| 277 | + amount: 1000, |
| 278 | + unit: 'gas', |
| 279 | + range: { min: 500, max: 2000 }, |
| 280 | + description: 'Description of impact' |
| 281 | + } |
| 282 | + ], |
| 283 | + educationalLinks: [ |
| 284 | + { |
| 285 | + title: 'Reference Title', |
| 286 | + url: 'https://example.com', |
| 287 | + source: 'documentation', |
| 288 | + description: 'What this resource teaches' |
| 289 | + } |
| 290 | + ], |
| 291 | + affectedAspects: ['aspect1', 'aspect2'], |
| 292 | + mitigation: 'How to fix this issue', |
| 293 | + relatedRules: ['other-rule'], |
| 294 | + tags: ['tag1', 'tag2'] |
| 295 | + } |
| 296 | +}; |
| 297 | +``` |
| 298 | + |
| 299 | +### Step 2: Use in Analysis |
| 300 | + |
| 301 | +```typescript |
| 302 | +const metadata = FindingMetadataFactory.createForRule('my-new-rule'); |
| 303 | +``` |
| 304 | + |
| 305 | +## Validation & Error Handling |
| 306 | + |
| 307 | +The factory includes validation: |
| 308 | + |
| 309 | +```typescript |
| 310 | +const metadata = FindingMetadataFactory.createForRule('some-rule'); |
| 311 | +const validation = FindingMetadataFactory.validate(metadata); |
| 312 | + |
| 313 | +if (!validation.valid) { |
| 314 | + console.error('Invalid metadata:', validation.errors); |
| 315 | +} |
| 316 | +``` |
| 317 | + |
| 318 | +## CLI Output Formats |
| 319 | + |
| 320 | +### Detailed Format (Default) |
| 321 | +Rich, educational output with full metadata and learning resources. |
| 322 | + |
| 323 | +### Table Format |
| 324 | +Compact overview of all findings in a table: |
| 325 | +``` |
| 326 | +Rule │ Severity │ Confidence │ Line │ Gas Impact │ Storage Impact |
| 327 | +───────────────────────────┼──────────┼────────────┼──────┼────────────┼────────────── |
| 328 | +unused-state-variables │ 🟡 │ 98% │ 42 │ 20000gas │ 2500bytes |
| 329 | +redundant-external │ 🟢 │ 85% │ 15 │ 200gas │ - |
| 330 | +``` |
| 331 | + |
| 332 | +### JSON Format |
| 333 | +Machine-readable format for programmatic processing: |
| 334 | +```json |
| 335 | +{ |
| 336 | + "timestamp": "2024-01-23T...", |
| 337 | + "summary": { |
| 338 | + "total": 2, |
| 339 | + "critical": 0, |
| 340 | + "high": 0, |
| 341 | + "medium": 1, |
| 342 | + "low": 1, |
| 343 | + "info": 0 |
| 344 | + }, |
| 345 | + "findings": [...] |
| 346 | +} |
| 347 | +``` |
| 348 | + |
| 349 | +## Best Practices |
| 350 | + |
| 351 | +1. **Always Set Confidence Score**: Helps users understand reliability |
| 352 | +2. **Include Multiple Impacts**: Show gas, storage, and other benefits |
| 353 | +3. **Add Educational Links**: Help users learn, not just fix |
| 354 | +4. **Be Specific in Mitigation**: Actionable steps are most helpful |
| 355 | +5. **Tag Appropriately**: Use consistent tags for filtering |
| 356 | +6. **Validate Before Use**: Use `FindingMetadataFactory.validate()` |
| 357 | + |
| 358 | +## Files Created |
| 359 | + |
| 360 | +``` |
| 361 | +apps/api-service/src/ |
| 362 | +├── common/ |
| 363 | +│ ├── interfaces/ |
| 364 | +│ │ └── finding-metadata.interface.ts # Core metadata definitions |
| 365 | +│ ├── factories/ |
| 366 | +│ │ └── finding-metadata.factory.ts # Metadata creation factory |
| 367 | +│ ├── formatters/ |
| 368 | +│ │ └── metadata-cli.formatter.ts # CLI output formatting |
| 369 | +│ └── cli/ |
| 370 | +│ └── analysis-result-handler.ts # High-level CLI handler |
| 371 | +├── analyzer/ |
| 372 | +│ ├── analyzer.service.ts # Updated to attach metadata |
| 373 | +│ └── interfaces/ |
| 374 | +│ └── analyzer.interface.ts # Updated with metadata field |
| 375 | +└── scanner/ |
| 376 | + └── interfaces/ |
| 377 | + └── scanner.interface.ts # Updated RuleViolation interface |
| 378 | +``` |
| 379 | + |
| 380 | +## Version |
| 381 | + |
| 382 | +Current Metadata Schema Version: **1.0** |
| 383 | + |
| 384 | +## Future Enhancements |
| 385 | + |
| 386 | +- [ ] Metadata versioning for backward compatibility |
| 387 | +- [ ] Custom metadata source plugins |
| 388 | +- [ ] Metadata caching/optimization |
| 389 | +- [ ] Multi-language educational resources |
| 390 | +- [ ] User-defined impact estimates |
| 391 | +- [ ] Metadata telemetry and analytics |
0 commit comments