BC8: Testing and securing smart contracts

Lesson 4 of 5 · reading 15–25 minutes; practice and project time is on the module page

Invariants, fuzzing and analysis tools

🎯You'll be able to

Write invariant tests, and explain what fuzzing, static analysis and formal verification add.

🏠The everyday picture

A shopkeeper who counts the till at the end of every day, not only after big sales: whatever happened, the cash should match the receipts.

📘What it really is

📝A worked example

Input: a learner's SakhiFund passes tests 1 to 8 but fails test 09.

Steps:

  1. The failure message says the ether and the records differ after action 23.
  2. Action 23 was a withdrawal of a member's whole balance.
  3. The code reduced balanceOf but forgot totalDeposits in one branch. Fixing it makes all 60 actions pass.

Expected output: a bug that example tests missed, found by an invariant.

🌍Where it's used

📝Case scenario

A token passed its unit tests, but a fuzzing run found that transferring to yourself doubled your balance in one edge case. The team fixed it before launch. Without the invariant "total supply equals the sum of balances", the bug would have shipped.

🖱️Try it

Write two invariants for SakhiVault. Success: for example "an executed transaction can't run again" and "the threshold is between 1 and the number of owners".

⚠️Common mistakes

🛠️For your project

Project 1's test 09 is an invariant test. Your security review's "Not verified" section should say if you didn't use fuzzing or static analysis.

✅Quick check

What is an invariant?

Show the answer

A fact that should hold after any sequence of actions.

Why doesn't 100% coverage prove a contract is safe?

Show the answer

Running every line once doesn't test every input or sequence.

← PreviousOther common attacks
ProLearners Assist