Smart Contract Testing: Unit, Fuzz and Invariant Tests in Solidity

Smart contract testing is the practice of checking, before deployment, that a contract does what it should and nothing else. For Solidity contracts on Ethereum and other EVM chains it comes in layers: unit tests check single functions, fuzz tests throw random inputs at them, invariant tests run random sequences of calls against rules that must always hold, static analyzers such as Slither read the code without running it, and formal verification tools such as Certora and Halmos prove properties for every possible input.

No layer is enough alone, and this article shows why with one experiment. At Etherwave Labs we wrote a 45-line Solidity vault with three bugs in it, then tested it the way most projects do. The unit tests pass with 100% coverage. Slither, one fuzz test, and one invariant test then each find a different bug, in under 20 seconds in total. Every command and output below comes from a real run (Foundry 1.5.1, Slither 0.11.3, Halmos 0.3.3, Solidity 0.8.29, November 2026). The last part covers what AI security tools such as OpenAI Daybreak add, and what they do not.

The short version:

  • 100% test coverage proved nothing. Four unit tests cover every line and branch of the vault, and all three bugs survive them.
  • Each bug needed a different layer. Slither found an unchecked ERC20 transfer, a fuzz test found a fee that rounds to zero on its second run, and an invariant test found a self-transfer that creates balance, shrunk to a two-call reproduction.
  • Formal tools turn a search into a proof. Halmos produced the self-transfer counterexample in 0.92 seconds, then proved the fixed function correct for every input.
  • AI agents are a reviewer, not a gate. On OpenAI and Paradigm's EVMbench, the best agent exploited 71.0% of known vulnerabilities; on real post-release incidents an independent study recorded zero successful exploits in 110 attempts.

What is smart contract testing?

The Ethereum Foundation's developer docs give the baseline definition: "Smart contract testing is the process of verifying that the code of a smart contract works as expected." The reason it carries more weight than in ordinary software is on the same page: public blockchains are immutable, "making it difficult to change a smart contracts code after deployment", and testing before mainnet is described as "a minimum requirement for security". The Smart Contract Security Field Guide, which Consensys Diligence's retired best-practices repository now points to, puts it in one line: "Smart contracts are immutable, and so are their bugs."

The methods fall into six layers. They differ in what they check, how much they cost to write, and what they can and cannot promise:

LayerWhat it checksMain toolsGuarantee
Unit testsOne function, with inputs you choseFoundry, HardhatOnly the cases you thought of
Static analysisCode patterns, without executingSlither, forge lint, SolhintKnown bug patterns, some false positives
Fuzz tests (stateless)One function, with thousands of random inputsFoundry, Echidna, MedusaProbabilistic, per function
Invariant tests (stateful fuzzing)Rules that hold after random sequences of callsFoundry, Echidna, MedusaProbabilistic, across call sequences
Formal verificationA property, for every possible inputCertora Prover, Halmos, SMTCheckerA proof, limited by what you specified
Human and AI reviewDesign, economics, the unknown unknownsAudits, bug bounties, AI agentsJudgement, no proof
Six layers of smart contract testing stacked from unit tests at the base to audits and AI review at the top, with the vault bug each layer caught in this article
The six layers of smart contract testing, and the bug each one caught in this article's vault.

The contract under test

The example is a token vault: users deposit an ERC20 token, can move their balance to another user inside the vault, and pay a 0.30% fee when they withdraw. It compiles, reads cleanly, and has three bugs.

src/Vault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

/// A token vault with a 0.30% withdrawal fee and internal transfers.
contract Vault {
    uint256 public constant FEE_BPS = 30;

    IERC20 public immutable asset;

    mapping(address => uint256) public balanceOf;
    uint256 public totalDeposits;
    uint256 public accruedFees;

    constructor(IERC20 asset_) {
        asset = asset_;
    }

    function deposit(uint256 amount) external {
        balanceOf[msg.sender] += amount;
        totalDeposits += amount;
        asset.transferFrom(msg.sender, address(this), amount);
    }

    function withdraw(uint256 amount) external {
        uint256 fee = amount * FEE_BPS / 10_000;
        balanceOf[msg.sender] -= amount;
        totalDeposits -= amount;
        accruedFees += fee;
        asset.transfer(msg.sender, amount - fee);
    }

    function transfer(address to, uint256 amount) external {
        uint256 fromBalance = balanceOf[msg.sender];
        uint256 toBalance = balanceOf[to];
        require(fromBalance >= amount, "insufficient balance");
        balanceOf[msg.sender] = fromBalance - amount;
        balanceOf[to] = toBalance + amount;
    }
}

If you have already spotted all three, you are doing the job of an auditor. The point of the next sections is that tools find them without you having to.

What is unit testing in Solidity?

A unit test calls one function with inputs you chose and asserts the result. In Foundry, tests are Solidity contracts that inherit from Test; in Hardhat they are TypeScript or JavaScript files that drive the contract through a library. OpenZeppelin's guide to writing automated smart contract tests sums up the consensus: "practice has shown that contract unit testing is exceptionally worthwhile", and the tests should be "multiple small, focused tests, which each check a small part of your contract for correctness".

Here are four of them for the vault, covering every function and the one revert path:

test/Vault.t.sol
contract VaultTest is Test {
    MockERC20 token;
    Vault vault;
    address alice = makeAddr("alice");
    address bob = makeAddr("bob");

    function setUp() public {
        token = new MockERC20();
        vault = new Vault(IERC20(address(token)));
        token.mint(alice, 1_000 ether);
        vm.prank(alice);
        token.approve(address(vault), type(uint256).max);
    }

    function test_DepositCreditsBalance() public {
        vm.prank(alice);
        vault.deposit(100 ether);

        assertEq(vault.balanceOf(alice), 100 ether);
        assertEq(vault.totalDeposits(), 100 ether);
        assertEq(token.balanceOf(address(vault)), 100 ether);
    }

    function test_WithdrawChargesFee() public {
        vm.startPrank(alice);
        vault.deposit(100 ether);
        vault.withdraw(100 ether);
        vm.stopPrank();

        assertEq(vault.accruedFees(), 0.3 ether);
        assertEq(token.balanceOf(alice), 999.7 ether);
    }

    function test_TransferMovesBalance() public {
        vm.startPrank(alice);
        vault.deposit(100 ether);
        vault.transfer(bob, 40 ether);
        vm.stopPrank();

        assertEq(vault.balanceOf(alice), 60 ether);
        assertEq(vault.balanceOf(bob), 40 ether);
    }

    function test_RevertWhen_TransferExceedsBalance() public {
        vm.prank(alice);
        vm.expectRevert("insufficient balance");
        vault.transfer(bob, 1);
    }
}

forge test reports four passes, and forge coverage reports the number every team wants to see:

$ forge coverage --match-contract VaultTest | File | % Lines | % Statements | % Branches | % Funcs | | src/Vault.sol | 100.00% (18/18) | 100.00% (16/16) | 100.00% (2/2) | 100.00% (4/4) |

Every line, statement, branch and function of Vault.sol is executed by a passing test, and the contract still has three bugs. Coverage measures which code ran. It says nothing about which inputs ran through it, or in which order. ethereum.org warns about the opposite failure, low coverage giving false confidence; this is the same trap from the other side.

Unit tests still earn their place. They document intended behaviour, they fail fast when a refactor breaks something, and they are the regression net for every bug the other layers find. They are the floor of a test suite, and they should not be mistaken for the ceiling.

What is static analysis, and what does Slither find?

Static analysis reads the code without executing it and matches it against known bug patterns. It is the cheapest layer: no tests to write, results in seconds. Slither, from Trail of Bits, is the standard tool for Solidity and Vyper. Its README claims an "average execution time of less than 1 second per contract" and that it "detects vulnerable Solidity code with low false positives".

On the vault, from the project root:

$ slither . --filter-paths "lib|test" INFO:Detectors: Vault.deposit(uint256) (src/Vault.sol#24-28) ignores return value by asset.transferFrom(msg.sender,address(this),amount) (src/Vault.sol#27) Vault.withdraw(uint256) (src/Vault.sol#30-36) ignores return value by asset.transfer(msg.sender,amount - fee) (src/Vault.sol#35) Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-transfer INFO:Detectors: Vault (src/Vault.sol#11-45) has incorrect ERC20 function interface:Vault.transfer(address,uint256) (src/Vault.sol#38-44) Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc20-interface INFO:Slither:. analyzed (2 contracts with 100 detectors), 3 result(s) found

Bug 1: unchecked token transfers. Some ERC20 tokens return false on failure instead of reverting. With such a token, deposit credits the user's balance even though no tokens arrived. The unit tests could never see this, because the mock token they use always returns true: the test double hid the bug. The fix is to check the return value, or in production to use OpenZeppelin's SafeERC20, which also handles tokens that return nothing at all.

The third finding is a different kind of result. Slither sees a function named transfer(address,uint256) that does not return a bool and suspects a broken ERC20. The vault is not an ERC20, so this one is a judgement call: rename the function, or mark the finding as reviewed. Static analysis always needs this triage step, which is why its output is a list to read and not a verdict.

Two notes on tooling in late 2026. Foundry now ships its own linter: forge lint flagged the same two unchecked transfers during a normal build, with no extra tool installed. And Aderyn, Cyfrin's Rust-based analyzer that many guides still recommend next to Slither, is gone: its repository was archived on November 17, 2026, and the README now states that "Aderyn is retired and no longer maintained".

Slither found one bug of three. The other two are not patterns, they are logic, and logic needs execution.

What is fuzz testing? Random inputs for one function

Fuzz testing runs a test many times with randomly generated inputs to find the ones that break it. A fuzz test is a unit test with parameters: instead of choosing the inputs, you state a property that should hold for any input, and the fuzzer generates the inputs. In Foundry any test function that takes arguments is a fuzz test, and Forge runs it 256 times by default with different values.

The unit test checked that withdrawing 100 tokens pays a 0.3 token fee. The property behind it is more general: every withdrawal pays a fee.

test/Vault.fuzz.t.sol
function testFuzz_WithdrawAlwaysChargesFee(uint256 amount) public {
    amount = bound(amount, 1, 1e30);
    token.mint(alice, amount);

    vm.startPrank(alice);
    token.approve(address(vault), amount);
    vault.deposit(amount);
    vault.withdraw(amount);
    vm.stopPrank();

    assertGt(vault.accruedFees(), 0, "withdrawal paid no fee");
}
$ forge test --match-contract VaultFuzzTest [FAIL: withdrawal paid no fee: 0 <= 0; counterexample: calldata=0x1e80ce65...0035 args=[53]] testFuzz_WithdrawAlwaysChargesFee(uint256) (runs: 2, μ: 142343, ~: 142343)

Bug 2: the fee rounds down to zero. On its second run the fuzzer tried amount = 53, and 53 * 30 / 10_000 is 0 in integer math. Any withdrawal below 334 base units is free, so a user can split a withdrawal into small pieces and never pay. With an 18-decimal token that amount is dust, which is exactly why nobody writes this unit test. But rounding against the protocol is the bug class behind much larger losses once it meets share-price math, and it is why ERC-4626 specifies a rounding direction for every vault function. The fix is to round the fee up.

Two practical rules for fuzz tests:

  • Prefer bound to vm.assume. bound(amount, 1, 1e30) maps any generated value into the range, so no run is wasted. vm.assume throws runs away when the condition is false, and a narrow condition discards most of them.
  • State a property and avoid restating the code. assertEq(fee, amount * 30 / 10_000) would pass forever, because it repeats the bug. Good properties come from the specification: a fee is always charged, a deposit followed by a withdrawal never returns more than was put in, a function either reverts or leaves balances consistent.

This kind of fuzzing is called stateless: every run starts from a fresh setUp, so it explores inputs, not history. Cyfrin's fuzzing explainer draws the same line between stateless fuzzing, where each run is independent, and stateful fuzzing, where the state left by one call is the starting point of the next. The third bug needs the second kind.

What is invariant testing? Random sequences of calls

An invariant is a statement about the contract that must be true in every reachable state, whatever anyone calls and in whatever order. The Foundry docs define the method as follows: "Invariant testing verifies properties that should always hold true, regardless of the sequence of actions taken." Trail of Bits describes the same idea for Echidna: where a classic fuzzer looks for crashes, a property-based fuzzer "aims to break user-defined invariants".

The vault has two obvious ones:

  1. The sum of all user balances equals totalDeposits.
  2. The tokens the vault holds equal totalDeposits plus accruedFees: it can always pay what it owes.

In Foundry, an invariant test is a function prefixed with invariant_. The fuzzer calls random functions on the target contracts and re-checks every invariant after each call. Pointed straight at the vault, most of those calls would revert (random callers with no tokens and no allowance), so the standard pattern is a handler: a wrapper contract that turns random numbers into valid actions by a small set of actors.

test/Vault.invariant.t.sol
contract Handler is Test {
    Vault public vault;
    MockERC20 public token;
    address[] public actors;

    constructor(Vault vault_, MockERC20 token_) {
        vault = vault_;
        token = token_;
        actors.push(makeAddr("alice"));
        actors.push(makeAddr("bob"));
        actors.push(makeAddr("carol"));
    }

    function deposit(uint256 actorSeed, uint256 amount) external {
        address actor = actors[actorSeed % actors.length];
        amount = bound(amount, 1, 1e24);
        token.mint(actor, amount);

        vm.startPrank(actor);
        token.approve(address(vault), amount);
        vault.deposit(amount);
        vm.stopPrank();
    }

    function withdraw(uint256 actorSeed, uint256 amount) external {
        address actor = actors[actorSeed % actors.length];
        amount = bound(amount, 0, vault.balanceOf(actor));

        vm.prank(actor);
        vault.withdraw(amount);
    }

    function transfer(uint256 fromSeed, uint256 toSeed, uint256 amount) external {
        address from = actors[fromSeed % actors.length];
        address to = actors[toSeed % actors.length];
        amount = bound(amount, 0, vault.balanceOf(from));

        vm.prank(from);
        vault.transfer(to, amount);
    }

    function sumOfBalances() external view returns (uint256 sum) {
        for (uint256 i = 0; i < actors.length; i++) {
            sum += vault.balanceOf(actors[i]);
        }
    }
}

contract VaultInvariantTest is Test {
    MockERC20 token;
    Vault vault;
    Handler handler;

    function setUp() public {
        token = new MockERC20();
        vault = new Vault(IERC20(address(token)));
        handler = new Handler(vault, token);
        targetContract(address(handler));
    }

    /// Every unit the vault owes is accounted for.
    function invariant_BalancesSumToTotalDeposits() public view {
        assertEq(handler.sumOfBalances(), vault.totalDeposits());
    }

    /// The vault always holds what it owes, plus the fees it kept.
    function invariant_VaultIsSolvent() public view {
        assertEq(token.balanceOf(address(vault)), vault.totalDeposits() + vault.accruedFees());
    }
}
$ forge test --match-contract VaultInvariantTest [FAIL: assertion failed: 980527 != 980526] [Sequence] (original: 5, shrunk: 2) sender=0x...1C12 addr=[Handler] calldata=deposit(uint256,uint256) args=[1.157e77, 980526] sender=0x...0E2a addr=[Handler] calldata=transfer(uint256,uint256,uint256) args=[1e24, 8650, 1] invariant_BalancesSumToTotalDeposits() (runs: 0, calls: 0, reverts: 0) [PASS] invariant_VaultIsSolvent() (runs: 256, calls: 128000, reverts: 6931)

Bug 3: a self-transfer creates balance out of nothing. The fuzzer found a failing sequence of five calls and shrank it to two: a deposit, then a transfer of 1 unit where fromSeed and toSeed both map to the same actor. Read transfer again with to == msg.sender: both balances are cached, the sender's is decreased, and then the recipient's is overwritten with the stale cached value plus amount. The user's balance grows by amount for free. Repeat it and the account's balance doubles each time, until it withdraws tokens that belong to everyone else.

Three things in that output are worth reading closely:

  • Shrinking. The raw failure was five calls with huge random numbers. Foundry reduced it to the two calls that matter, which is the difference between a bug report and a debugging session.
  • The invariant that passed. invariant_VaultIsSolvent held for 128,000 calls (256 runs of 500 calls, Foundry's defaults) because the bug inflates the ledger and leaves the token balance alone. An invariant suite needs several angles on the same state.
  • The reverts. 6,931 withdrawals reverted in that passing run. After the fix the same campaign shows reverts: 0. Those reverts were inflated balances failing to withdraw more than totalDeposits, so the number was a symptom. A revert count you cannot explain deserves a look.

How do you find invariants?

Writing the handler is mechanical. Finding the invariants is the real work, and most protocols share a few families:

  • Conservation: the sum of the parts equals the total (balances and supply, shares and assets, debt and collateral).
  • Solvency: the contract holds at least what it owes.
  • Monotonicity: some values only move one way (a nonce, cumulative fees, a share price that should never fall outside a loss event).
  • Access: no sequence of calls by a non-owner changes privileged state.
  • Round trips: deposit then withdraw never returns more than was put in.

For standard tokens you do not have to start from zero: Trail of Bits publishes crytic/properties, a set of pre-built invariants for ERC20, ERC721 and ERC4626 that run under Echidna or Medusa. Both are dedicated fuzzers from the same team: Echidna is the original Haskell tool, and Medusa is a newer Go fuzzer "inspired by Echidna" that adds parallel fuzzing. Consensys Diligence runs a hosted equivalent, Diligence Fuzzing, built on its Harvey fuzzer and Scribble annotations. For most projects, Foundry's built-in invariant runner is the place to start because the tests live next to the unit tests.

What is formal verification? Halmos, Certora and the SMTChecker

Formal verification proves that a contract satisfies a property for every possible input, where fuzzing only samples the input space. ethereum.org defines it as "evaluating the correctness of a system with respect to a formal specification", and states the difference with testing plainly: testing "cannot conclusively prove the absence of bugs", while formal verification can prove a property "for an infinite range of executions".

Halmos: symbolic tests in the Foundry syntax

Halmos, from a16z, is "a symbolic testing tool for EVM smart contracts" that reuses Foundry test syntax. A function prefixed with check_ has its arguments treated as symbols standing for all values at once, and a solver looks for any assignment that breaks an assertion.

test/Vault.symbolic.t.sol
/// For every sender, recipient, deposit and amount: a transfer creates no balance.
function check_TransferCreatesNoBalance(address from, address to, uint256 deposited, uint256 amount) public {
    vm.assume(from != address(0) && from != address(vault));
    token.mint(from, deposited);

    vm.startPrank(from);
    token.approve(address(vault), deposited);
    vault.deposit(deposited);

    uint256 fromBefore = vault.balanceOf(from);
    uint256 toBefore = vault.balanceOf(to);
    vault.transfer(to, amount);
    vm.stopPrank();

    uint256 sumBefore = from == to ? fromBefore : fromBefore + toBefore;
    uint256 sumAfter = from == to ? vault.balanceOf(from) : vault.balanceOf(from) + vault.balanceOf(to);
    assertEq(sumAfter, sumBefore);
}
$ halmos --contract VaultSymbolicTest Counterexample: p_amount_uint256 = 0x4000...0000 p_deposited_uint256 = 0x8000...0000 p_from_address = 0x8000000000000000000000000000000000000000 p_to_address = 0x8000000000000000000000000000000000000000 [FAIL] check_TransferCreatesNoBalance(address,address,uint256,uint256) (paths: 12, time: 0.92s)

The solver went straight to from == to in under a second. On the fixed contract the same test returns [PASS] after exploring 14 paths in 0.70 seconds, and that pass means something a fuzz pass does not: no sender, recipient, deposit or amount exists that breaks the property, within the scenario the test describes.

Certora Prover: specifications in CVL

The Certora Prover is the tool behind the formal verification of protocols such as Aave, Uniswap and Lido. It became open source on February 24, 2025, and Certora says it "has secured a total of over $100 Billion in TVL". It works on compiled EVM bytecode, and properties are written in a separate language, CVL. The docs distinguish two building blocks: a rule "defines a sequence of commands that should be simulated during verification", and invariants "describe a property of the state of a contract that is always expected to hold".

The vault's first invariant, as a CVL specification:

certora/Vault.spec
methods {
    function balanceOf(address) external returns (uint256) envfree;
    function totalDeposits() external returns (uint256) envfree;
}

// A ghost variable that mirrors the sum of every entry of the balanceOf mapping.
ghost mathint sumOfBalances {
    init_state axiom sumOfBalances == 0;
}

// Keep the ghost in sync on every storage write to balanceOf.
hook Sstore balanceOf[KEY address user] uint256 newBalance (uint256 oldBalance) {
    sumOfBalances = sumOfBalances + newBalance - oldBalance;
}

invariant balancesSumToTotalDeposits()
    sumOfBalances == to_mathint(totalDeposits());

Compare this with the Foundry handler. The Foundry invariant summed three known actors and checked the result after random call sequences. The CVL invariant covers every address through a storage hook, and the Prover checks that the constructor establishes it and that every public function preserves it, for all inputs. When it cannot, it "will output a specific counterexample that causes the assertions to fail". We show the specification as an illustration of the approach: unlike the Foundry, Slither and Halmos runs above, it was not executed for this article.

OpenZeppelin Contracts is a good picture of how these tools combine in a mature codebase. Its engineering guidelines require that coverage "be kept as close to 100% as possible", and add that where unit tests are insufficient the team uses "property-based tests (aka. fuzzing) for math-heavy code" and "formal verification for state machines". The repository's CI runs Slither on every pull request and has separate workflows for Certora and Halmos.

What formal verification does not give you

A proof is only as good as the property. ethereum.org lists the limits: it "requires considerable manual labor", it "can only check if the execution of the smart contract matches the formal specification", and some properties run into state explosion or cannot be decided at all. Our Halmos proof covers a single deposit followed by a single transfer. It says nothing about the fee, and it would have passed on a vault whose withdraw sent tokens to the wrong address. Solidity's built-in SMTChecker has the same shape: it tries to prove that assert statements, arithmetic and array accesses are safe, and reports a counterexample when it can find one.

Which layer caught which bug?

BugUnit tests (100% coverage)SlitherFuzz testInvariant testHalmos
Unchecked ERC20 transferMissed (mock always returns true)FoundMissedMissedNot targeted
Fee rounds down to zeroMissedMissedFound, run 2Missed by our two invariantsNot targeted
Self-transfer inflates balanceMissedMissedNot targetedFound, shrunk to 2 callsCounterexample in 0.92 s

Each bug was caught by the cheapest layer able to see it, and by none of the layers below. After the three fixes (checked transfers, a fee rounded up, and transfer updating storage directly with -= and +=), the whole suite passes: 4 unit tests, 256 fuzz runs, two invariants over 128,000 calls each, and the symbolic test.

"Missed" also hides a second lesson. The solvency invariant missed the self-transfer bug, and neither invariant noticed the rounding bug. A green invariant suite proves only that the invariants you wrote hold, so the list of invariants deserves the same review as the code.

Smart contract testing tools compared

The tools used or named in this article, with their status as of November 2026:

ToolMaintainerLayerTests or specs written inStatus
FoundryFoundry teamUnit, fuzz, invariant, coverage, lintSolidityActive, open source
HardhatNomic FoundationUnit and integration testsTypeScript, JavaScriptActive, open source
SlitherTrail of BitsStatic analysis, 100 detectors in 0.11.3None needed (Python API for custom checks)Active, AGPL-3.0
EchidnaTrail of BitsProperty-based fuzzingSolidityOpen source, AGPL-3.0
MedusaTrail of BitsParallel fuzzingSolidityOpen source, AGPL-3.0
Halmosa16zSymbolic testingSolidity (Foundry syntax)Open source, AGPL-3.0
Certora ProverCertoraFormal verificationCVLOpen source since February 2025
SMTCheckerSolidity teamFormal verificationSolidity assertBuilt into the compiler
Diligence FuzzingConsensys DiligenceHosted fuzzingScribble annotationsHosted service
AderynCyfrinStatic analysisNone neededRetired, archived November 17, 2026

If you can only adopt two, take Foundry and Slither: together they cover the first four layers, both run in CI in seconds to minutes, and both are free.

Where does AI fit? OpenAI Daybreak, EVMbench and auditing agents

The newest layer is AI agents that read code, hypothesize vulnerabilities and try to prove them. Two pieces of evidence are worth separating: a general-purpose security product, and a smart-contract-specific benchmark.

OpenAI Daybreak

Daybreak is OpenAI's cybersecurity program. In its own words it "brings together AI capabilities, security solutions, partners, and support to help defenders protect the systems we all rely on". Access is by application, with two tiers: Daybreak Blue "for defensive work including vulnerability discovery, validation, remediation, threat modeling, and security investigation", and Daybreak Red for authorized red teaming and exploit validation. OpenAI verifies applicants and reviews how they plan to use the models before approving access.

For a development team, the relevant part is the tooling around it. Daybreak Defense Factory, in research preview, connects to a GitHub repository and scans it once or on every commit; likely issues are, per OpenAI's developer blog, "validated in an isolated environment", and you review suggested patches before a pull request is opened. The related Codex Security workflow ties back to this article's subject: "When feasible, the workflow adds a regression test that fails before the fix and passes afterward." In its June 22, 2026 announcement, OpenAI reported that Codex Security had "scanned over 30 million commits across more than 30,000 codebases". Its open-source arm, Patch the Planet, is run with Trail of Bits, the team behind Slither and Echidna.

One caveat matters for this article: none of the Daybreak pages we read mention smart contracts, Solidity or the EVM. Daybreak is a general application-security program. It can review the backend, the indexer, the deployment scripts and the frontend around a protocol, which is where a large share of real incidents start, and it is not marketed as a Solidity auditor.

EVMbench: how good are AI agents at smart contract security?

The smart-contract-specific data comes from EVMbench, a benchmark OpenAI and Paradigm released on February 18, 2026. It "draws on 117 curated vulnerabilities from 40 audits" and scores agents in three modes: detect (find the vulnerabilities human auditors found), patch (remove the bug while keeping the tests passing), and exploit (drain funds on a sandboxed chain).

  • In exploit mode, GPT-5.3-Codex scored 71.0%, against 33.3% for GPT-5.
  • Detect and patch are weaker: OpenAI says both "remain below full coverage", and that the benchmark "does not represent the full difficulty of real-world smart contract security".
  • An independent re-evaluation by researchers from BlockSec and Zhejiang University, on 22 real incidents that happened after the models were released, found that "no agent succeeds at end-to-end exploitation across all 110 agent-incident pairs despite detecting up to 65% of vulnerabilities".

Read together: agents are already useful at spotting candidate bugs and are improving fast, they are much better when the bug is in their training data, and a detected bug is still far from a verified one.

What this changes in a test suite

AI review belongs in the pipeline as one more reviewer, and its output should be converted into the layers above:

  • A finding becomes a test. Whether a bug is reported by an agent, an auditor or a bounty hunter, the fix ships with a unit test or an invariant that fails without it.
  • Agents are good at the boring parts. Handlers, mocks, and first drafts of invariants are mechanical to write and easy to review. The invariant list itself still needs a human who understands what the protocol promises.
  • Deterministic tools stay the gate. A model's review can differ between two runs; forge test cannot. CI should block merges on tests, invariants and Slither, and treat AI findings as input to triage.
  • Attackers have the same tools. A 71% exploit rate on known bug classes means cheap, automated scanning of every deployed contract. Bug classes that a fuzzer finds in ten seconds will not survive long on mainnet.

A testing pipeline you can copy

Fuzzing depth is a time budget, so use two profiles: fast defaults locally, a deeper campaign in CI.

foundry.toml
[profile.default.fuzz]
runs = 256

[profile.default.invariant]
runs = 256
depth = 500
fail_on_revert = false

[profile.ci.fuzz]
runs = 10000

[profile.ci.invariant]
runs = 1000
depth = 500
.github/workflows/contracts.yml
name: contracts
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    env:
      FOUNDRY_PROFILE: ci
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive
      - uses: foundry-rs/foundry-toolchain@v1
      - run: forge test
      - uses: crytic/slither-action@v0.4.2
        with:
          fail-on: medium

The order of work that has held up for us on client projects:

  1. Write unit tests with the code, including every revert path. Aim for full coverage and do not trust it.
  2. Run Slither and forge lint from the first commit. Triage every finding once; fix it or record why it is accepted.
  3. Turn each unit test's assumption into a fuzz test wherever a number, an address or a length is involved.
  4. Write the invariants before the audit, starting with conservation and solvency. Read the revert counts.
  5. Add fork tests (forge test --fork-url) for anything that touches a live protocol: real tokens behave differently from mocks, as bug 1 showed.
  6. Use formal verification where a bug is unaffordable: accounting cores, share math, state machines, upgrade and access logic.
  7. Then bring in people: an independent audit, and a bug bounty once live. ethereum.org lists both next to testing, and the scripted layers above make the auditors' time go to design flaws and away from rounding errors.

Frequently asked questions

Is 100% test coverage enough for a smart contract?

No. Coverage counts the lines that tests executed. It does not count the inputs or the call sequences that were tried. The vault in this article reaches 100% line, statement, branch and function coverage with four passing unit tests, and still contains three bugs, including one that lets a user mint balance for free.

What is the difference between fuzz testing and invariant testing?

A fuzz test calls one function with random inputs from a fresh state and checks a property of that single call. An invariant test, also called stateful fuzzing, runs random sequences of calls and checks after each one that global rules still hold. Fuzzing finds bad inputs. Invariant testing finds bad sequences.

Foundry or Hardhat for testing Solidity?

Both work, and many teams use both. Foundry writes tests in Solidity and has fuzzing, invariant testing, coverage and a linter built in, which makes it the usual choice for contract logic. Hardhat tests are TypeScript, which suits integration tests that share code with a frontend or backend. OpenZeppelin Contracts ships with both a hardhat.config and a foundry.toml.

Do I still need an audit if I use Slither, fuzzing and formal verification?

Yes. Automated layers check the properties you wrote and the patterns the tools know. An audit questions the design itself: the economic assumptions, the trust in oracles and admins, the properties nobody thought to write. Strong tests make an audit cheaper and deeper. They are not a substitute for it.

Can AI tools like OpenAI Daybreak audit a Solidity contract?

AI agents can find real smart contract bugs: on EVMbench, GPT-5.3-Codex exploited 71.0% of a curated set of known vulnerabilities. On real incidents after the models' release, an independent study found zero end-to-end exploits in 110 attempts. Daybreak itself is a general cybersecurity program and does not mention Solidity. Treat AI review as an extra reviewer whose findings become tests.

How long does smart contract testing take?

For a well-scoped contract, plan roughly as much time for tests as for the code. Unit tests are written with the code. A first invariant suite with a handler usually takes one to three days for a small protocol. Formal verification of a core component takes days to weeks, mostly spent on the specification.

Tested, audit-ready contracts

The vault above took an hour to write and three tools to break. Real protocols have more functions, more actors and more money, and the gap between "the tests pass" and "the contract is correct" grows with each of them. The useful habit is the one this article followed: for every assumption in the code, ask which layer would notice if it were false.

That is how we work at Etherwave Labs. Our smart contract development ships Solidity with unit, fuzz and invariant suites in Foundry, static analysis in CI, and a test report an auditor can start from; we built the vault contracts behind YieldBase and the ERC721 and ERC1155 contracts of The Smurfs Society. If you have a codebase that was written quickly, with AI or without, our code audit grades it on eight dimensions including tests. To budget a build, the Web3 development cost calculator gives an itemized estimate, or talk to us about your contracts.

More articles

Ready to take your project to the next level?

Contact us today to discuss how we can help you achieve your goals in the blockchain space.