Repository navigation
Expand file tree
/
Copy pathGasOptimizationAnalyzer.ts
More file actions
607 lines (537 loc) · 18.1 KB
/
Copy pathGasOptimizationAnalyzer.ts
File metadata and controls
607 lines (537 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/**
* Gas Optimization Static Analysis Engine
*
* Analyzes Solidity code for gas optimization opportunities using pattern matching,
* AST analysis, and storage layout inspection.
*
* Features:
* - Storage packing analysis (detects wasted slots)
* - Arithmetic optimization detection (unchecked{} opportunities)
* - Loop optimization suggestions
* - Custom error vs require string analysis
* - Mapping vs array performance analysis
* - ERC721A sequential minting patterns
* - Calldata vs memory parameter optimization
*
* Based on best practices from:
* - Slither static analyzer
* - RareSkills gas optimization guide
* - Solidity compiler optimization techniques
*
* @version 1.0.0
* @author HoloScript Core Team
*/
export interface GasOptimization {
id: string;
severity: 'critical' | 'high' | 'medium' | 'low' | 'info';
category:
'storage' | 'arithmetic' | 'loops' | 'errors' | 'memory' | 'external-calls' | 'visibility';
location: CodeLocation;
issue: string;
suggestion: string;
potentialSavings: number; // Gas units
autoFixAvailable: boolean;
autoFix?: string;
}
export interface CodeLocation {
file: string;
line: number;
column: number;
length: number;
snippet?: string;
}
export interface GasAnalysisReport {
totalOptimizations: number;
totalPotentialSavings: number;
criticalCount: number;
highCount: number;
mediumCount: number;
lowCount: number;
optimizations: GasOptimization[];
summary: string[];
appliedFixes?: number;
}
export interface AnalyzerOptions {
enableAutoFix: boolean;
severityThreshold: 'critical' | 'high' | 'medium' | 'low' | 'info';
categories: string[];
ignorePatterns?: string[];
}
export class GasOptimizationAnalyzer {
private options: AnalyzerOptions;
private optimizations: GasOptimization[] = [];
constructor(options: Partial<AnalyzerOptions> = {}) {
this.options = {
enableAutoFix: options.enableAutoFix ?? false,
severityThreshold: options.severityThreshold || 'info',
categories: options.categories || [
'storage',
'arithmetic',
'loops',
'errors',
'memory',
'external-calls',
'visibility',
],
ignorePatterns: options.ignorePatterns || [],
};
}
/**
* Analyze Solidity code for gas optimizations
*/
analyze(code: string, filename: string = 'Contract.sol'): GasAnalysisReport {
this.optimizations = [];
// Run all analyzers
if (this.options.categories.includes('storage')) {
this.analyzeStorageLayout(code, filename);
}
if (this.options.categories.includes('arithmetic')) {
this.analyzeArithmetic(code, filename);
}
if (this.options.categories.includes('loops')) {
this.analyzeLoops(code, filename);
}
if (this.options.categories.includes('errors')) {
this.analyzeErrorHandling(code, filename);
}
if (this.options.categories.includes('memory')) {
this.analyzeMemoryUsage(code, filename);
}
if (this.options.categories.includes('external-calls')) {
this.analyzeExternalCalls(code, filename);
}
if (this.options.categories.includes('visibility')) {
this.analyzeVisibility(code, filename);
}
return this.generateReport();
}
/**
* Analyze storage layout for packing opportunities
*/
private analyzeStorageLayout(code: string, filename: string): void {
const lines = code.split('\n');
// Detect state variables
const stateVarPattern =
/^\s*(uint\d+|int\d+|bool|address|bytes\d+)\s+(?:public|private|internal)?\s+(\w+)/;
let currentSlot = 0;
let currentSlotSize = 0;
const variables: Array<{ type: string; name: string; size: number; line: number }> = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const match = line.match(stateVarPattern);
if (match) {
const type = match[1];
const name = match[2];
const size = this.getTypeSize(type);
variables.push({ type, name, size, line: i + 1 });
if (currentSlotSize + size > 32) {
const wasted = 32 - currentSlotSize;
if (wasted > 0) {
this.optimizations.push({
id: `STORAGE-PACK-${i}`,
severity: 'medium',
category: 'storage',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
snippet: line.trim(),
},
issue: `Wasted ${wasted} bytes in storage slot ${currentSlot}`,
suggestion: `Reorder state variables to pack efficiently. Consider grouping smaller types (uint128, uint64, bool) together.`,
potentialSavings: wasted * 20000, // ~20k gas per wasted slot
autoFixAvailable: false,
});
}
currentSlot++;
currentSlotSize = size;
} else {
currentSlotSize += size;
}
}
// Reset on mapping or array (they don't pack)
if (line.includes('mapping') || line.includes('[]')) {
currentSlot++;
currentSlotSize = 0;
}
}
// Check for inefficient uint256 usage where smaller types would suffice
for (const v of variables) {
if (v.type === 'uint256' && v.name.toLowerCase().includes('count')) {
this.optimizations.push({
id: `STORAGE-UINT256-${v.line}`,
severity: 'low',
category: 'storage',
location: {
file: filename,
line: v.line,
column: 0,
length: 0,
},
issue: `Using uint256 for counter "${v.name}" may be excessive`,
suggestion: `Consider uint96 or uint128 for counters (saves 12-20 bytes per slot)`,
potentialSavings: 5000,
autoFixAvailable: false,
});
}
}
}
/**
* Analyze arithmetic operations for unchecked{} opportunities
*/
private analyzeArithmetic(code: string, filename: string): void {
const lines = code.split('\n');
// Detect safe arithmetic that can be unchecked
const safePatterns = [
{ pattern: /\+\+i\b/, context: 'for loop increment', savings: 40 },
{ pattern: /i\+\+\b/, context: 'for loop increment', savings: 40 },
{ pattern: /--i\b/, context: 'for loop decrement', savings: 40 },
{ pattern: /i--\b/, context: 'for loop decrement', savings: 40 },
];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Check if already in unchecked block
if (line.includes('unchecked')) continue;
for (const { pattern, context, savings } of safePatterns) {
if (pattern.test(line)) {
this.optimizations.push({
id: `ARITH-UNCHECKED-${i}`,
severity: 'medium',
category: 'arithmetic',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
snippet: line.trim(),
},
issue: `Checked arithmetic on ${context}`,
suggestion: `Wrap in unchecked{} block if overflow is impossible`,
potentialSavings: savings,
autoFixAvailable: true,
autoFix: `unchecked { ${line.trim()} }`,
});
}
}
}
}
/**
* Analyze loops for optimization opportunities
*/
private analyzeLoops(code: string, filename: string): void {
const lines = code.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Detect array.length in loop condition
if (line.includes('for') && line.includes('.length')) {
this.optimizations.push({
id: `LOOP-LENGTH-${i}`,
severity: 'medium',
category: 'loops',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
snippet: line.trim(),
},
issue: 'Reading array.length on every iteration',
suggestion: 'Cache array.length in a local variable before the loop',
potentialSavings: 100, // ~100 gas per iteration saved
autoFixAvailable: true,
autoFix: 'uint256 length = array.length; for (uint256 i; i < length; ) { ... }',
});
}
// Detect storage reads in loop
if (line.includes('for') && (line.includes('storage') || !line.includes('memory'))) {
const nextLines = lines.slice(i + 1, i + 10).join('\n');
if (nextLines.includes('[i]') && !nextLines.includes('memory')) {
this.optimizations.push({
id: `LOOP-STORAGE-${i}`,
severity: 'high',
category: 'loops',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
},
issue: 'Multiple storage reads in loop',
suggestion: 'Load array element into memory variable before processing',
potentialSavings: 2000, // ~2k gas per storage read
autoFixAvailable: false,
});
}
}
}
}
/**
* Analyze error handling (require vs custom errors)
*/
private analyzeErrorHandling(code: string, filename: string): void {
const lines = code.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Detect require with string
const requireMatch = line.match(/require\s*\([^,]+,\s*"([^"]+)"\s*\)/);
if (requireMatch) {
const errorMsg = requireMatch[1];
this.optimizations.push({
id: `ERROR-REQUIRE-${i}`,
severity: 'medium',
category: 'errors',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
snippet: line.trim(),
},
issue: 'Using require with string error message',
suggestion: `Replace with custom error: error ${this.toCamelCase(errorMsg)}(); ... if (condition) revert ${this.toCamelCase(errorMsg)}();`,
potentialSavings: 50 + errorMsg.length * 2, // ~50 gas base + ~2 gas per character
autoFixAvailable: false,
});
}
}
}
/**
* Analyze memory vs calldata for function parameters
*/
private analyzeMemoryUsage(code: string, filename: string): void {
const lines = code.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Detect external/public functions with memory array parameters
if ((line.includes('external') || line.includes('public')) && line.includes('memory')) {
const memoryMatch = line.match(/(\w+)\[\]\s+memory\s+(\w+)/);
if (memoryMatch) {
const type = memoryMatch[1];
const paramName = memoryMatch[2];
// Check if parameter is only read (not modified)
const functionBody = this.extractFunctionBody(lines, i);
if (!functionBody.includes(`${paramName}[`) || !functionBody.includes(`${paramName} =`)) {
this.optimizations.push({
id: `MEMORY-CALLDATA-${i}`,
severity: 'medium',
category: 'memory',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
snippet: line.trim(),
},
issue: `Parameter "${paramName}" uses memory but is read-only`,
suggestion: `Change to calldata to save gas on array copying`,
potentialSavings: 200, // ~200 gas saved per array element
autoFixAvailable: true,
autoFix: line.replace('memory', 'calldata'),
});
}
}
}
}
}
/**
* Analyze external calls for optimization
*/
private analyzeExternalCalls(code: string, filename: string): void {
const lines = code.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Detect multiple calls to same external contract
const callMatch = line.match(/(\w+)\.(\w+)\(/);
if (callMatch) {
const contract = callMatch[1];
// Check next 5 lines for repeated calls
const nextLines = lines.slice(i + 1, i + 6);
const repeats = nextLines.filter((l) => l.includes(`${contract}.`)).length;
if (repeats > 1) {
this.optimizations.push({
id: `CALL-CACHE-${i}`,
severity: 'low',
category: 'external-calls',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
},
issue: `Multiple calls to ${contract} in sequence`,
suggestion: `Cache contract reference in local variable if calling multiple times`,
potentialSavings: 100,
autoFixAvailable: false,
});
}
}
}
}
/**
* Analyze function visibility modifiers
*/
private analyzeVisibility(code: string, filename: string): void {
const lines = code.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Detect public functions that could be external
if (line.includes('function') && line.includes('public') && !line.includes('view')) {
const funcName = line.match(/function\s+(\w+)/)?.[1];
// Check if function is only called externally (not from within contract)
const internalCall = code.includes(`this.${funcName}`) || code.includes(`${funcName}(`);
if (!internalCall) {
this.optimizations.push({
id: `VIS-PUBLIC-${i}`,
severity: 'low',
category: 'visibility',
location: {
file: filename,
line: i + 1,
column: 0,
length: line.length,
snippet: line.trim(),
},
issue: `Function "${funcName}" is public but only called externally`,
suggestion: `Change visibility to external to save gas on calldata decoding`,
potentialSavings: 50,
autoFixAvailable: true,
autoFix: line.replace('public', 'external'),
});
}
}
}
}
/**
* Generate comprehensive gas analysis report
*/
private generateReport(): GasAnalysisReport {
const criticalCount = this.optimizations.filter((o) => o.severity === 'critical').length;
const highCount = this.optimizations.filter((o) => o.severity === 'high').length;
const mediumCount = this.optimizations.filter((o) => o.severity === 'medium').length;
const lowCount = this.optimizations.filter((o) => o.severity === 'low').length;
const totalSavings = this.optimizations.reduce((sum, o) => sum + o.potentialSavings, 0);
const summary = [
`Found ${this.optimizations.length} gas optimization opportunities`,
`Potential savings: ~${totalSavings.toLocaleString()} gas units`,
`Critical: ${criticalCount}, High: ${highCount}, Medium: ${mediumCount}, Low: ${lowCount}`,
];
// Add category breakdown
const categories = new Map<string, number>();
for (const opt of this.optimizations) {
categories.set(opt.category, (categories.get(opt.category) || 0) + 1);
}
summary.push('');
summary.push('By category:');
for (const [cat, count] of categories) {
summary.push(` - ${cat}: ${count} issues`);
}
return {
totalOptimizations: this.optimizations.length,
totalPotentialSavings: totalSavings,
criticalCount,
highCount,
mediumCount,
lowCount,
optimizations: this.optimizations,
summary,
};
}
/**
* Apply automatic fixes
*/
applyAutoFixes(code: string): { code: string; appliedCount: number } {
let modifiedCode = code;
let appliedCount = 0;
for (const opt of this.optimizations) {
if (opt.autoFixAvailable && opt.autoFix) {
// Simple line-based replacement (real implementation would use AST)
const lines = modifiedCode.split('\n');
if (opt.location.line <= lines.length) {
lines[opt.location.line - 1] = opt.autoFix;
modifiedCode = lines.join('\n');
appliedCount++;
}
}
}
return { code: modifiedCode, appliedCount };
}
// Helper methods
private getTypeSize(type: string): number {
if (type === 'bool') return 1;
if (type === 'address') return 20;
if (type.startsWith('uint') || type.startsWith('int')) {
const bits = parseInt(type.replace(/\D/g, ''));
return bits / 8;
}
if (type.startsWith('bytes')) {
const size = parseInt(type.replace(/\D/g, ''));
return size || 32;
}
return 32; // Default
}
private extractFunctionBody(lines: string[], startLine: number): string {
let braceCount = 0;
let started = false;
const body: string[] = [];
for (let i = startLine; i < Math.min(startLine + 100, lines.length); i++) {
const line = lines[i];
for (const char of line) {
if (char === '{') {
braceCount++;
started = true;
} else if (char === '}') {
braceCount--;
}
}
if (started) {
body.push(line);
}
if (started && braceCount === 0) {
break;
}
}
return body.join('\n');
}
private toCamelCase(str: string): string {
return str
.replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase())
.replace(/^./, (chr) => chr.toUpperCase());
}
}
/**
* Preset analyzer configurations
*/
export const ANALYZER_PRESETS = {
production: {
enableAutoFix: false,
severityThreshold: 'medium' as const,
categories: ['storage', 'arithmetic', 'loops', 'errors', 'memory', 'external-calls'],
},
development: {
enableAutoFix: true,
severityThreshold: 'info' as const,
categories: [
'storage',
'arithmetic',
'loops',
'errors',
'memory',
'external-calls',
'visibility',
],
},
aggressive: {
enableAutoFix: true,
severityThreshold: 'low' as const,
categories: [
'storage',
'arithmetic',
'loops',
'errors',
'memory',
'external-calls',
'visibility',
],
},
};