DEV Community

ohmygod
ohmygod

Posted on

Building a Zero-Cost DeFi Audit Pipeline: Slither + Foundry + AI in Under 30 Minutes

Professional smart contract audits cost $50K–$500K and take weeks. But 73% of exploited DeFi protocols in 2025-2026 had vulnerabilities that automated tools could have caught before deployment. Here's how to build a continuous audit pipeline that costs nothing, runs in your CI/CD, and catches the bugs that keep draining protocols.

The Pipeline Architecture

Source Code
    │
    ▼
┌─────────────┐     ┌──────────────┐     ┌────────────────┐
│   Slither    │────▶│   Foundry    │────▶│   AI Review    │
│ Static Scan  │     │   Fuzzing    │     │  (Final Pass)  │
└─────────────┘     └──────────────┘     └────────────────┘
    │                     │                      │
    ▼                     ▼                      ▼
  Known Vuln          State-Space           Logic & Economic
  Patterns            Exploration           Attack Vectors
Enter fullscreen mode Exit fullscreen mode

Each layer catches what the others miss. Slither finds known patterns in seconds. Foundry fuzzing explores state space for hours. AI review catches the economic logic flaws that neither tool understands.

Layer 1: Slither Static Analysis (5 Minutes to Set Up)

Slither's 92+ detectors catch reentrancy, unchecked transfers, and access control issues instantly. But most teams run it wrong.

The Wrong Way

slither . --detect all
Enter fullscreen mode Exit fullscreen mode

This dumps hundreds of findings, most of them false positives. Teams get alert fatigue and start ignoring results.

The Right Way

Create a slither.config.json that filters noise and focuses on what kills protocols:

{
  "detectors_to_run": [
    "reentrancy-eth",
    "reentrancy-no-eth", 
    "arbitrary-send-erc20",
    "arbitrary-send-eth",
    "controlled-delegatecall",
    "suicidal",
    "unprotected-upgrade",
    "msg-value-loop",
    "delegatecall-loop",
    "unchecked-transfer",
    "unchecked-lowlevel",
    "tx-origin",
    "locked-ether"
  ],
  "exclude_informational": true,
  "exclude_low": true
}
Enter fullscreen mode Exit fullscreen mode

These 13 detectors cover the patterns behind 80% of DeFi exploits. Run them first, fix everything they find, then expand.

Slither Printers for Economic Analysis

Most teams skip Slither's printers. Don't.

# Who can call what? Find unprotected admin functions
slither . --print modifiers

# Token flow analysis — where can funds move?
slither . --print erc20

# Call graph — find unexpected external interactions
slither . --print call-graph
Enter fullscreen mode Exit fullscreen mode

The call-graph printer is gold for catching flash loan attack surfaces. If an external call happens before a state update, you've got a potential reentrancy or oracle manipulation window.

Layer 2: Foundry Fuzzing (15 Minutes to Write Invariants)

Static analysis finds code patterns. Fuzzing finds broken assumptions. The Resolv exploit ($25M, March 2026) violated a simple invariant: total minted tokens should never exceed total deposited collateral value. A fuzzer testing that invariant would have caught it.

Writing Invariants That Actually Matter

Forget testing individual functions. Test protocol-level properties:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "forge-std/Test.sol";
import "../src/LendingPool.sol";

contract LendingInvariantTest is Test {
    LendingPool pool;

    function setUp() public {
        pool = new LendingPool();
        deal(address(pool.asset()), address(pool), 1_000_000e18);
    }

    // INVARIANT 1: Pool solvency
    function invariant_poolSolvency() public view {
        uint256 totalAssets = pool.totalAssets();
        uint256 totalShares = pool.totalSupply();
        if (totalShares > 0) {
            assertGe(totalAssets, totalShares / 1e18);
        }
    }

    // INVARIANT 2: No free minting
    function invariant_noShareDilution() public view {
        uint256 totalAssets = pool.totalAssets();
        uint256 totalShares = pool.totalSupply();
        if (totalShares > 0) {
            uint256 sharePrice = (totalAssets * 1e18) / totalShares;
            assertGe(sharePrice, 1e18);
        }
    }

    // INVARIANT 3: Withdrawal sanity
    function invariant_noExcessWithdrawal() public view {
        assertGe(
            pool.asset().balanceOf(address(pool)),
            0,
            "Pool drained below zero"
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

The Five Invariants Every DeFi Protocol Needs

  1. Solvency: Total liabilities ≤ total assets (catches donation attacks, oracle manipulation)
  2. Share price monotonicity: Share price never decreases except through legitimate fees (catches first-depositor attacks, inflation attacks)
  3. Conservation of value: Total value in = total value out + fees (catches minting bugs, rounding errors)
  4. Access control: Protected functions revert for unauthorized callers (catches privilege escalation)
  5. Reentrancy safety: State is consistent at every external call boundary (catches cross-function reentrancy)

Running the Fuzzer Effectively

# Quick smoke test (CI — 2 minutes)
forge test --match-contract Invariant --fuzz-runs 1000

# Deep exploration (nightly — 30 minutes)  
forge test --match-contract Invariant --fuzz-runs 50000

# Weekend deep dive (weekly — hours)
forge test --match-contract Invariant --fuzz-runs 500000 \
  --fuzz-seed 42  # Reproducible for debugging
Enter fullscreen mode Exit fullscreen mode

Foundry Fuzzing Pro Tips

Use deal() and vm.prank() to simulate whale behavior:

function testFuzz_whaleDeposit(uint256 amount) public {
    amount = bound(amount, 1e18, 100_000_000e18);
    deal(address(token), address(this), amount);

    uint256 sharesBefore = pool.totalSupply();
    pool.deposit(amount, address(this));
    uint256 sharesAfter = pool.totalSupply();

    assertGt(sharesAfter, sharesBefore);
}
Enter fullscreen mode Exit fullscreen mode

Test across multiple blocks to catch time-dependent bugs:

function testFuzz_timeDependentYield(uint256 blocks) public {
    blocks = bound(blocks, 1, 100_000);
    vm.roll(block.number + blocks);
    vm.warp(block.timestamp + blocks * 12);

    uint256 yield = pool.pendingYield(address(this));
    assertLe(yield, pool.totalAssets());
}
Enter fullscreen mode Exit fullscreen mode

Layer 3: AI-Assisted Review (The Logic Layer)

Static analysis and fuzzing catch code-level bugs. They don't catch economic design flaws — the kind that caused the Makina Finance oracle manipulation ($4M) and the Curve reentrancy ($70M).

What to Ask AI to Review

Feed your contract to an AI model with these specific prompts:

Economic attack surface analysis:

Review this DeFi protocol for economic attack vectors:
1. Can flash loans manipulate any price oracle or liquidity calculation?
2. Can a sequence of transactions extract more value than deposited?
3. Are there sandwich attack opportunities in any swap or liquidation path?
4. Can governance actions be front-run for profit?
Enter fullscreen mode Exit fullscreen mode

Cross-contract interaction risks:

Analyze the external call pattern in this contract:
1. Which external contracts are trusted? Can they be upgraded?
2. What happens if an external call returns unexpected values?
3. Is there a callback pattern that could enable reentrancy?
4. Can the order of operations across multiple contracts be manipulated?
Enter fullscreen mode Exit fullscreen mode

Privilege escalation review:

Review the access control model:
1. Who can upgrade this contract? Is there a timelock?
2. Which admin functions can drain user funds?
3. Can the owner rug-pull? What's the maximum extractable value?
4. Are there any functions that should be restricted but aren't?
Enter fullscreen mode Exit fullscreen mode

Building the CI/CD Pipeline

Create a GitHub Action that runs the full pipeline on every PR:

name: Security Pipeline
on: [pull_request]

jobs:
  slither:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: crytic/slither-action@v0.4.0
        with:
          slither-config: slither.config.json
          fail-on: high

  foundry-fuzz:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: foundry-rs/foundry-toolchain@v1
      - run: forge test --match-contract Invariant --fuzz-runs 10000
Enter fullscreen mode Exit fullscreen mode

The Reality Check: What This Pipeline Won't Catch

Be honest about limitations:

  • Classic reentrancy: ✅ Slither + Foundry + AI all catch it
  • Oracle manipulation: Needs oracle mocks in fuzzing; AI catches the pattern
  • Governance attacks: AI review only
  • MEV extraction: Partially caught by AI
  • Social engineering / Key compromise: No code tool catches this
  • Cross-chain bridge bugs: Partially caught by AI

The Step Finance hack ($27M, January 2026) was a compromised private key. No amount of code analysis prevents that. The pipeline catches code bugs, not operational security failures.

What This Actually Costs vs Professional Audits

  • This pipeline: $0 (OSS tools), 30 min setup, runs continuously
  • Single professional audit: $50K-$500K, 2-8 weeks, one snapshot
  • Bug bounty program: $10K-$1M+ in rewards, ongoing, community-driven

The right answer: all three. This pipeline is your first line of defense. Professional audits catch what automation misses. Bug bounties catch what everyone missed.

Getting Started Today

# 1. Install tools
curl -L https://foundry.paradigm.xyz | bash
pip3 install slither-analyzer

# 2. Run Slither on your project
cd your-defi-project
slither . --config-file slither.config.json

# 3. Write your first invariant test
# (copy the template above into test/invariants/)

# 4. Run the fuzzer
forge test --match-contract Invariant --fuzz-runs 10000

# 5. Set up GitHub Action
# (copy the YAML above into .github/workflows/security.yml)
Enter fullscreen mode Exit fullscreen mode

Total time: 30 minutes. Total cost: $0. Potential savings: millions.

The protocols getting exploited in 2026 aren't failing because they can't afford security tools. They're failing because they don't use the free ones that already exist.


This article is part of the DeFi Security Research series. Follow for weekly deep-dives into smart contract vulnerabilities, audit methodologies, and defense patterns.

Top comments (0)