Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 47 ยท Security

Audits, Tools and Best Practices

Learn how contracts are reviewed and kept safe: static analysis such as Slither, fuzzing, formal checks, audits, multisigs, timelocks and deployment checklists.

You have now seen the common bugs, the reentrancy family, gas and testing. The last piece of the security chapter is the process around the code: the tools that look for problems automatically, the humans who review a contract before launch, and the safeguards that limit the damage when something still slips through.

Nothing in this lesson can run on the site: Slither, Echidna, a multisig wallet and a block explorer all need real software or a real network. The commands are shown read-only, and the JavaScript stand-ins model two of the ideas, a pattern-based checker that scans toy source and a timelock that delays a risky action, so that you can see how they behave.

Layers of defence

Static analysis Tools read the code for known patterns.
Fuzz and invariants Tools hammer it with random calls.
Formal checks Prove a rule holds for all inputs.
Human audit Experts read it line by line.
1 / 2

Static analysis

A static analyzer reads your source (or its compiled form) without running it and reports patterns that are known to cause bugs: tx.origin used for authorization, a low-level call whose result is ignored, state written after an external call, and so on. Slither, from Trail of Bits, is the best-known tool for Solidity:

Terminal
pip install slither-analyzer
slither .                                   # analyze the whole project
slither . --detect reentrancy-eth,tx-origin # run only chosen detectors

Each finding has a name, a location and a severity. Static analyzers are fast and cheap enough to run on every commit, so put them in your continuous-integration pipeline. They also produce false positives: a flagged line is a question for you to answer, not a verdict. And they can only find what they have a pattern for, so a clean report is not a certificate of safety.

Fuzzing, symbolic execution and formal checks

Beyond pattern matching, three families of tools go deeper:

  • Fuzzers and invariant testers such as Foundry's built-in fuzzer and Echidna run huge numbers of random calls against rules you wrote (Testing Contracts). They find bugs that need an unlikely sequence.
  • Symbolic execution (for example Mythril or Halmos) treats inputs as unknowns and explores paths with a solver, which can show that some input breaks a property, or that none does within the explored paths.
  • Formal verification (for example the Certora Prover) states a rule precisely and attempts to prove it for every possible input and state. It is the strongest guarantee and the most expensive: it takes expert time, and it proves only the rules you wrote down.

For most projects the practical stack is: careful design, a thorough test suite with fuzzing and invariants, a static analyzer in CI, and an external audit before launch.

Audits

An audit is a paid, time-boxed review of your code by security specialists. A typical audit has a scope (which files and which commit), a manual line-by-line review, tool runs, a report of findings graded by severity (critical, high, medium, low, informational), a fix period, and a re-review of the fixes. Some teams also run audit contests, where many independent reviewers compete to find issues in a fixed time window.

What an audit is not: a guarantee. It reviews one version of the code. Any change afterwards, however small, is outside the audit. Reviewers can miss things, and the best-audited contracts have still been exploited. To get value from one:

  1. Finish the code and freeze it first. Auditors should not review a moving target.
  2. Write documentation and tests, so the reviewers spend time on the hard issues instead of guessing what the code is for.
  3. Explain the intended behavior and the trust assumptions: who is the owner, what can they do, which external contracts are trusted.
  4. Fix every finding and have the fixes reviewed, rather than arguing about severity.
  5. Publish the report. Users and other developers learn from it.

A checklist to review your own code

Before you pay anyone, run through this list yourself:

  • Access control: every state-changing function has a deliberate permission. Look especially for initialize, mint, setX, withdraw, upgrade and selfdestruct.
  • External calls: state is updated before each call (checks, effects, interactions); results of low-level calls are checked; tokens go through SafeERC20 (Using OpenZeppelin).
  • Math: rounding direction favors the protocol; decimals match; unchecked has a written proof.
  • Loops and storage: no unbounded loops over user-controlled data; no push payments that one party can block.
  • Randomness and time: no secrets or randomness from on-chain data; block.timestamp is used only where a few seconds' error is harmless.
  • Signatures: nonce, chain id and contract address are part of every signed message.
  • Upgrades: storage layout is preserved; initializers can run only once (Proxies and Upgradeable Contracts).
  • Events: every important state change emits one, so monitoring tools can watch.
  • Dependencies: libraries are pinned to known versions and audited, and you understand every external contract you call.

A pattern-based checker

The stand-in below is a miniature of what a static analyzer does. It scans a toy contract, held as a string, with a few simple rules and prints findings with line numbers. It is far cruder than Slither: it matches text, not the program's structure, so it will miss things and flag harmless code. That is the same trade-off in miniature.

JS A tiny static analyzer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that kill is not flagged as unprotected (it has onlyOwner), while setOwner is. Notice also what the checker cannot see: sendAll sends the whole balance to msg.sender, an authorization flaw no pattern in this list describes. A human reviewer finds that kind of issue.

Deployment safety

A secure contract can still be deployed insecurely:

  • Rehearse on a testnet with the exact script and settings you will use on mainnet (Deploying to Testnet and Mainnet).
  • Verify the source on a block explorer so anyone can compare the code with the deployed bytecode.
  • Never keep admin power in a single key. Move ownership to a multisig wallet, an account that needs several of its owners (for example 3 of 5) to approve a transaction. Safe is a widely used one; you can also build one yourself (Project: A Multisig Wallet).
  • Put sensitive changes behind a timelock. A timelock stores an approved action and refuses to run it until a delay has passed (a day or two is common). Users get time to read the pending change and leave if they disagree. OpenZeppelin ships a TimelockController.
  • Start small. Cap deposits at first, raise the caps as confidence grows.
  • Monitor. Watch events and balances with alerting, and keep a written incident plan: who can pause, who talks to users, how funds are recovered.
  • Offer a bug bounty, so that a researcher who finds a flaw has a better offer than exploiting it.
  • Revoke deployer powers you no longer need: renounce roles and transfer ownership instead of leaving a hot wallet in charge.

The timelock idea is easy to model. In the stand-in below, a multisig approves an action, the action is queued with a delay, and execution works only inside a window. Time is a plain number of seconds here, not a blockchain clock.

JS A multisig that queues behind a timelock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the tools, the audit process and the safeguards described above (names and commands may evolve, so check each tool's documentation). Stand-in: the checker matches text with regular expressions and the timelock uses made-up time, with no signatures or chain.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A static analyzer reports no findings on your contract. What does that tell you?

    Static analysis detects known patterns. It can miss logic and design flaws, so it supplements tests and human review.
  2. 2. Why is an audit not a guarantee of safety?

    An audit reduces risk, but it covers a specific commit and is limited by time and human attention.
  3. 3. What is the purpose of putting an admin action behind a timelock?

    The delay makes privileged changes visible and gives users a chance to exit if they disagree.
  4. 4. Which is the best home for a contract's owner role after deployment?

    A multisig avoids a single point of failure, and a timelock adds a visible delay for risky changes.

Summary

  • Layer your defences: careful design, tests with fuzzing and invariants, static analysis in CI, formal checks where they pay off, and an external audit.
  • Static analyzers such as Slither find known patterns quickly but give false positives and miss design flaws.
  • Prepare for an audit by freezing the code, documenting intent and trust assumptions, and fixing every finding.
  • Deploy safely: rehearse on a testnet, verify source, hold admin power in a multisig, add a timelock, start with caps and monitor events.
  • A bug bounty and an incident plan are part of security, not extras.

Next: Talking to Contracts with JavaScript.