forge-guard 0.1.5

Pre-deployment smart contract auditing framework for Foundry
Documentation
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
//! `forge-guard simulate` โ€” run deployment simulations with MEV analysis.

use super::SimulateArgs;
use anyhow::{Context, Result};
use colored::*;
use std::time::Instant;

/// MEV-sensitive source-level patterns.
const SANDWICH_SENSITIVE_PATTERNS: &[&str] = &[
    "amm",
    "swap",
    "pool",
    "liquidity",
    "reserve",
    "price",
    "twap",
    "oracle",
    "slippage",
    "minAmount",
    "amountOutMin",
    "sqrtPrice",
];

/// Run deployment simulations to detect issues before deploying.
pub fn run(args: &SimulateArgs) -> Result<()> {
    let start = Instant::now();

    eprintln!("{}\n", "๐Ÿงช Forge Guard โ€” Deployment Simulation".bold());
    println!("  Blocks:    {}", args.blocks);
    println!(
        "  MEV:       {}",
        if args.mev {
            "enabled".green()
        } else {
            "disabled".dimmed()
        }
    );
    println!("  Contract:  {}", args.contract.as_deref().unwrap_or("all"));
    println!(
        "  Deployer:  {}",
        args.deployer.as_deref().unwrap_or("default")
    );
    println!();

    // Phase 1: Compile and analyze for MEV patterns (even without --mev flag)
    eprintln!("๐Ÿ“‹ Phase 1: Analyzing contract bytecode for MEV vectors...\n");
    let mev_signals = analyze_mev_patterns(args);

    if !mev_signals.is_empty() {
        println!("  โš ๏ธ  Potential MEV patterns found:\n");
        for signal in &mev_signals {
            println!(
                "     โ€ข {} โ€” {}",
                signal.pattern.yellow(),
                signal.description
            );
        }
        println!();
    } else {
        println!("  โœ… No obvious MEV patterns detected.\n");
    }

    // Phase 2: Build and simulate via forge script
    eprintln!("๐Ÿ“‹ Phase 2: Running deployment simulation...\n");

    let mut cmd = std::process::Command::new("forge");
    cmd.arg("script");

    if let Some(contract) = &args.contract {
        cmd.arg(contract);
    }

    if let Some(deployer) = &args.deployer {
        cmd.arg("--sender").arg(deployer);
    }

    cmd.arg("--slow");

    eprintln!(
        "     Running: forge script {}\n",
        args.contract.as_deref().unwrap_or("<default>")
    );

    let output = match cmd.output().context("Failed to run forge script") {
        Ok(o) => o,
        Err(e) => {
            eprintln!("  โš ๏ธ  Simulation failed: {e}");
            eprintln!("     This is non-fatal โ€” forge may not be installed or configured.");
            eprintln!("     Security audit findings are still available.");
            return Ok(());
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("  โš ๏ธ  Simulation stderr:\n{}", stderr);
        eprintln!("     Simulation had warnings โ€” these are non-fatal.");
    } else {
        extract_simulation_results(&String::from_utf8_lossy(&output.stdout));
    }

    // Phase 3: MEV analysis (if enabled)
    if args.mev {
        eprintln!("\n๐Ÿ“‹ Phase 3: MEV analysis...\n");
        run_mev_analysis(args.blocks);
    }

    let elapsed = start.elapsed();
    println!(
        "\n{}",
        "โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•".bright_blue()
    );
    println!(
        "  {} SIMULATION COMPLETE in {:.2}s",
        "โœ…".green(),
        elapsed.as_secs_f64()
    );
    println!(
        "{}",
        "โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•".bright_blue()
    );

    Ok(())
}

/// Detected MEV pattern.
struct MevSignal {
    pattern: &'static str,
    description: String,
}

/// Analyze source code for potential MEV-sensitive patterns.
fn analyze_mev_patterns(args: &SimulateArgs) -> Vec<MevSignal> {
    let mut signals = Vec::new();

    // Scan source files for MEV-sensitive patterns
    let src_dir = args.shared.project.join("src");
    if !src_dir.exists() {
        return signals;
    }

    let mut source_files = Vec::new();
    for entry in walkdir::WalkDir::new(&src_dir)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.extension().is_some_and(|ext| ext == "sol") {
            source_files.push(path.to_path_buf());
        }
    }

    for file in &source_files {
        let content = match std::fs::read_to_string(file) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lower = content.to_lowercase();

        // Check for sandwich-sensitive patterns
        for pattern in SANDWICH_SENSITIVE_PATTERNS {
            if lower.contains(pattern) {
                signals.push(MevSignal {
                    pattern: "Sandwich / Slippage",
                    description: format!(
                        "Contract uses '{}' patterns that may be vulnerable to sandwich attacks. Ensure proper slippage protection.",
                        pattern
                    ),
                });
                break;
            }
        }

        // Check for flash loan patterns
        if lower.contains("flashloan")
            || lower.contains("flash_loan")
            || lower.contains("onflashloan")
        {
            signals.push(MevSignal {
                pattern: "Flash Loan",
                description:
                    "Contract supports flash loans โ€” verify price oracle manipulation resistance."
                        .into(),
            });
        }

        // Check for oracle dependency
        if lower.contains("chainlink") || lower.contains("oracle") || lower.contains("twap") {
            signals.push(MevSignal {
                pattern: "Oracle Dependency",
                description:
                    "Contract depends on price oracles โ€” ensure freshness and manipulation resistance."
                        .into(),
            });
        }

        // Check for unchecked external calls (MEV extraction vector)
        if lower.contains(".call{value")
            || lower.contains(".delegatecall(")
            || lower.contains("selfdestruct")
        {
            signals.push(MevSignal {
                pattern: "Value Extraction",
                description:
                    "Contract has value-moving operations that could be MEV extraction targets."
                        .into(),
            });
        }
    }

    // Deduplicate by pattern
    signals.dedup_by_key(|s| s.pattern);

    signals
}

/// Extract and display key results from forge script simulation output.
fn extract_simulation_results(stdout: &str) {
    let mut gas_used: Vec<u64> = Vec::new();
    let mut txn_count = 0u32;

    for line in stdout.lines() {
        let trimmed = line.trim();

        // Extract gas from forge traces
        if trimmed.contains("gas used") || trimmed.contains("Gas used") {
            if let Some(gas_str) = trimmed
                .split_whitespace()
                .find(|w| w.chars().all(|c| c.is_ascii_digit()))
            {
                if let Ok(gas) = gas_str.parse::<u64>() {
                    gas_used.push(gas);
                }
            }
        }

        // Count transactions
        if trimmed.contains("Transaction") || trimmed.starts_with("==LOG==") {
            txn_count += 1;
        }
    }

    // Deployment cost estimate
    if let Some(&total) = gas_used.last() {
        let estimated_eth_cost = total as f64 * 20_000_000_000.0 / 1_000_000_000_000_000_000.0; // ~20 gwei
        println!("  โ›ฝ Estimated gas:  {}", total.to_string().bold());
        println!(
            "  ๐Ÿ’ฐ Estimated cost: {:.6} ETH at 20 gwei",
            estimated_eth_cost
        );
    }

    if txn_count > 0 {
        println!("  ๐Ÿ“ Transactions:   {}", txn_count);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_analyze_mev_patterns_no_source_dir() {
        // With non-existent src dir, should return empty
        let args = SimulateArgs {
            shared: super::super::SharedFlags {
                chain: "ethereum".into(),
                project: std::path::PathBuf::from("/nonexistent"),
                json: false,
                markdown: false,
                strict: false,
                offline: true,
                production: false,
                report: false,
                parallelism: 4,
            },
            blocks: 100,
            deployer: None,
            mev: false,
            contract: None,
        };
        let signals = analyze_mev_patterns(&args);
        assert!(signals.is_empty(), "No src dir should yield no signals");
    }

    #[test]
    fn test_analyze_mev_patterns_with_src_dir_no_sol_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        // Create a non-.sol file
        std::fs::write(dir.path().join("src").join("readme.md"), "# nothing").unwrap();

        let args = SimulateArgs {
            shared: super::super::SharedFlags {
                chain: "ethereum".into(),
                project: dir.path().to_path_buf(),
                json: false,
                markdown: false,
                strict: false,
                offline: true,
                production: false,
                report: false,
                parallelism: 4,
            },
            blocks: 100,
            deployer: None,
            mev: false,
            contract: None,
        };
        let signals = analyze_mev_patterns(&args);
        assert!(signals.is_empty());
    }

    #[test]
    fn test_extract_simulation_results_empty() {
        // Should not panic with empty input
        extract_simulation_results("");
    }

    #[test]
    fn test_extract_simulation_results_with_gas() {
        let stdout = "some output\nGas used: 50000\nmore output\nTransaction #1\n";
        // Should not panic
        extract_simulation_results(stdout);
    }

    #[test]
    fn test_run_mev_analysis_basic() {
        // Should not panic
        run_mev_analysis(100);
    }

    #[test]
    fn test_run_mev_analysis_zero_blocks() {
        run_mev_analysis(0);
    }

    #[test]
    fn test_mev_signal_dedup() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        // Write a contract that triggers multiple patterns
        std::fs::write(
            src.join("Pool.sol"),
            "contract Pool { function swap() { uint price = oracle.getPrice(); } }",
        )
        .unwrap();

        let args = SimulateArgs {
            shared: super::super::SharedFlags {
                chain: "ethereum".into(),
                project: dir.path().to_path_buf(),
                json: false,
                markdown: false,
                strict: false,
                offline: true,
                production: false,
                report: false,
                parallelism: 4,
            },
            blocks: 100,
            deployer: None,
            mev: false,
            contract: None,
        };
        let signals = analyze_mev_patterns(&args);
        // Should have found patterns, but each pattern should appear at most once
        assert!(
            !signals.is_empty(),
            "Should find MEV patterns in Pool contract"
        );
        assert_eq!(
            signals.len(),
            signals
                .iter()
                .map(|s| s.pattern)
                .collect::<std::collections::HashSet<_>>()
                .len(),
            "Patterns should be deduplicated"
        );
    }
}

/// Run detailed MEV analysis (placeholder for future enhancement).
fn run_mev_analysis(blocks: u32) {
    println!("  Analyzing {blocks} blocks for MEV opportunities...\n");

    // Analysis categories
    let analyses = [
        (
            "Frontrunning",
            "Check if transactions can be displaced by priority gas auctions",
        ),
        (
            "Sandwiching",
            "Detect AMM swap patterns vulnerable to sandwich attacks",
        ),
        (
            "Backrunning",
            "Identify post-transaction value extraction opportunities",
        ),
        (
            "Liquidation",
            "Scan for liquidation opportunities and competition",
        ),
        ("Arbitrage", "Detect cross-pool/CEX-DEX arbitrage patterns"),
    ];

    for (category, description) in &analyses {
        println!("  โ€ข {}: {}", category.bold(), description.dimmed());
    }

    println!(
        "\n  {} MEV analysis requires a full archival node and historical data for accuracy.",
        "๐Ÿ’ก".dimmed()
    );
    println!(
        "    For production use, consider dedicated MEV tools: searcher, libmev, or Flashbots.",
    );
}