Hardhat
Security Testing
Smart Contract Audit

Hardhat Security Testing: The Complete Guide

Your Hardhat test suite proves your contract does what you intended. It doesn't prove what happens when someone does what you didn't intend. That gap is where $197M disappears — Euler Finance found out the hard way in March 2023. This guide closes it.

Duron Epps, Founder
12 min read
Share:X / TwitterLinkedIn

What Your Hardhat Tests Actually Cover (And What They Don't)

Hardhat is the right tool for contract development. Hot reloading, flexible plugin support, TypeScript-native, a debugging console that actually works — it's genuinely good. But your test suite is only as dangerous as your imagination. You write tests for the behavior you designed. Attackers probe the behavior you didn't.

The Euler Finance exploit ($197M, March 2023) passed every internal test the team ran. The vulnerability was in the interaction between donation logic and liquidation math — a relationship no unit test caught because no one thought to test it that way. That's not a Hardhat failure. That's the fundamental limit of test-driven security.

What you need is a layered approach: Hardhat for behavioral testing, static analysis and AI auditing for vulnerability classes you haven't thought of yet. Here's how to build that workflow from scratch.

Setting Up Your Hardhat Security Baseline

Step 1: Project Structure That Supports Security Testing

Before you write a single security-focused test, your project structure needs to support it. If you're starting fresh or refactoring:

my-protocol/
├── contracts/
│   ├── core/
│   └── interfaces/
├── test/
│   ├── unit/
│   ├── integration/
│   └── security/      ← add this
├── scripts/
├── hardhat.config.ts
└── package.json

The security/ directory is where adversarial tests live. These are different from unit tests. You're not checking that transfer() moves tokens correctly — you're checking that an attacker can't drain the pool by calling transfer() in a reentrancy loop.

Step 2: Install the Security-Relevant Plugins

npm install --save-dev \
  @nomicfoundation/hardhat-toolbox \
  @nomicfoundation/hardhat-chai-matchers \
  hardhat-gas-reporter \
  solidity-coverage \
  @openzeppelin/contracts

Your hardhat.config.ts should include at minimum:

import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import "solidity-coverage";
import "hardhat-gas-reporter";

const config: HardhatUserConfig = {
  solidity: {
    version: "0.8.24",
    settings: {
      optimizer: { enabled: true, runs: 200 },
      viaIR: true
    }
  },
  gasReporter: {
    enabled: true,
    currency: "USD"
  }
};

export default config;

Pin your Solidity version. Mixing 0.8.x minor versions across contracts in the same project creates subtle behavioral differences — especially around unchecked blocks and ABI encoding.

Writing Adversarial Security Tests in Hardhat

Reentrancy Tests

Reentrancy via call() is the oldest trick in the book and still catches protocols off guard. Write an attacker contract directly in your test environment:

// contracts/test/ReentrancyAttacker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IVault {
    function withdraw(uint256 amount) external;
    function deposit() external payable;
}

contract ReentrancyAttacker {
    IVault public vault;
    uint256 public attackCount;

    constructor(address _vault) {
        vault = IVault(_vault);
    }

    function attack() external payable {
        vault.deposit{value: msg.value}();
        vault.withdraw(msg.value);
    }

    receive() external payable {
        if (attackCount < 5 && address(vault).balance >= msg.value) {
            attackCount++;
            vault.withdraw(msg.value);
        }
    }
}

Then your Hardhat test asserts the attack fails:

it("should not be vulnerable to reentrancy", async function () {
  const [owner, attacker] = await ethers.getSigners();
  
  // Seed vault with 10 ETH
  await vault.connect(owner).deposit({ value: ethers.parseEther("10") });
  
  const attackerContract = await ethers.deployContract(
    "ReentrancyAttacker",
    [await vault.getAddress()]
  );

  await expect(
    attackerContract.attack({ value: ethers.parseEther("1") })
  ).to.be.reverted;

  // Vault should still have its 10 ETH
  expect(await ethers.provider.getBalance(vault.getAddress()))
    .to.equal(ethers.parseEther("10"));
});

Access Control Tests

Never assume your onlyOwner modifier is wired correctly just because the happy path works. Test that every privileged function reverts for non-owners:

describe("Access Control", function () {
  it("should revert when non-owner calls admin functions", async function () {
    const [, attacker] = await ethers.getSigners();
    
    await expect(
      vault.connect(attacker).setWithdrawLimit(ethers.parseEther("1000"))
    ).to.be.revertedWithCustomError(vault, "OwnableUnauthorizedAccount");
  });

  it("should not use tx.origin for authentication", async function () {
    // tx.origin auth means any contract called by owner can act as owner
    // Test this by simulating an intermediary contract call
    const [owner] = await ethers.getSigners();
    const proxyAttacker = await ethers.deployContract("TxOriginAttacker", [
      await vault.getAddress()
    ]);
    
    // Even if owner triggers this, tx.origin auth is exploitable
    await expect(
      proxyAttacker.connect(owner).exploit()
    ).to.be.reverted;
  });
});

tx.origin authentication is a category of bug that looks correct in unit tests — because in unit tests, msg.sender and tx.origin are often the same address. Real-world it's not. This is exactly the kind of thing static analysis catches and test suites miss.

Integer Overflow Edge Cases

Solidity 0.8.x added built-in overflow protection, but unchecked blocks turn it off. Any unchecked block in your codebase needs explicit overflow testing:

it("should not overflow in unchecked accumulation", async function () {
  const maxUint256 = ethers.MaxUint256;
  
  // If your contract has unchecked addition anywhere near user inputs,
  // test the boundary explicitly
  await expect(
    token.mint(attacker.address, maxUint256)
  ).to.be.reverted;
});

Adding Slither Static Analysis to Your Hardhat Workflow

Slither 0.10.x runs as a separate pass over your compiled artifacts. Wire it into your CI pipeline, not just as a manual step you remember sometimes:

# Install
pip3 install slither-analyzer

# Run against your Hardhat project
slither . --hardhat-artifacts-directory artifacts

# Or output JSON for CI parsing
slither . --json slither-report.json

Add this to your package.json:

"scripts": {
  "test": "hardhat test",
  "coverage": "hardhat coverage",
  "security:slither": "slither . --hardhat-artifacts-directory artifacts",
  "security:full": "npm run coverage && npm run security:slither"
}

Slither catches a predictable set of issues well: reentrancy patterns, integer issues, uninitialized storage, dangerous delegatecall usage. What it doesn't catch is logic-layer vulnerabilities specific to your protocol's design. That's where AI auditing fills the gap.

Integrating AI Auditing Into Your Hardhat Workflow

Here's the workflow I'd actually use before any deployment:

  1. Run your Hardhat test suite — confirm intended behavior passes
  2. Run hardhat coverage — if you're below 85% line coverage, you have blind spots
  3. Run Slither — catch the static analysis obvious stuff
  4. Run an AI audit — catch protocol-specific logic flaws, interaction risks, and the vulnerability classes that static analysis misses
  5. Fix findings, repeat steps 3–4 before pushing to mainnet

AI auditing isn't a replacement for step 1 or step 2 — it's the step that makes you dangerous instead of just thorough. It will flag things like: flash loan price manipulation vectors, governance attack surfaces, storage collision risks in upgradeable contracts using delegatecall, and oracle dependency assumptions baked into your math.

SmartContractAuditor.ai detects reentrancy, access control flaws, integer overflow in unchecked blocks, tx.origin authentication, unsafe delegatecall patterns, and flash loan attack surfaces in under 60 seconds — free to start at https://contractgenius.vercel.app.

Coverage Isn't Security — But Low Coverage Is a Red Flag

Run npx hardhat coverage and look at the output honestly. 100% line coverage means every line executed at least once during tests. It says nothing about whether an attacker's input sequence was ever tried. 60% coverage means there are entire branches of your contract that have never been executed by any test — that's not a security posture, that's wishful thinking.

The target: 90%+ line coverage, 80%+ branch coverage. Gaps should be documented and justified, not ignored.

The Pre-Deployment Security Checklist

  • ✅ Solidity version pinned to 0.8.24 or latest stable 0.8.x
  • ✅ OpenZeppelin 5.x contracts used for standard patterns (don't roll your own Ownable)
  • ✅ Reentrancy tests written with attacker contracts, not just happy path
  • ✅ Every unchecked block has a corresponding overflow test
  • ✅ Every admin function tested for unauthorized access
  • ✅ No tx.origin used for authentication anywhere
  • ✅ Slither passes with no high-severity findings
  • ✅ AI audit run on final contract code, not a draft
  • ✅ Coverage above 85% line, 75% branch
  • ✅ All findings from static analysis and AI audit addressed or explicitly accepted with documentation

When to Get a Manual Audit on Top of This

If your protocol is managing less than $500k TVL at launch and you've run this full workflow, you're in reasonable shape. If you're launching something that could hold $5M+ on day one, add a manual audit from Halborn ($20k–$80k) or Sigma Prime ($20k–$60k) on top of automated tooling. The Ronin Bridge lost $625M in March 2022 — an audit that cost $50k would have been the best money Axie Infinity ever spent.

The math is simple: audit cost vs. potential loss. At any meaningful TVL, the audit wins.

For most contracts — a staking contract, a token with vesting, a simple NFT sale mechanism — the workflow above catches what gets protocols exploited. Start with your Hardhat tests, add Slither, add AI auditing. You'll know more about your contract's security posture than 80% of teams deploying to mainnet today.

Related Articles

Continue exploring smart contract security with these related insights

CertiK
Smart Contract Audit

CertiK Audit vs AI Audit: What Founders Need to Know

I've been through the CertiK process. The invoice was real, the wait was real, and some of what they flagged was stuff an AI tool caught in under a minute. Here's what I'd do differently — and when CertiK is still the right call.

51 views
Read Article
Published on
June 19, 2026