Crypto Training
A Practical Smart Contract Audit Workflow: From Threat Model to Finding
The order of work on one engagement: state what the protocol protects, map who can change it, mark the calls that cross trust boundaries, turn guarantees into tests, and write findings an engineer can fix. Each step is shown on Euler v1's eToken module, where the map alone points at the function behind the March 2023 loss.
An audit that consists of reading the code from top to bottom produces uneven results, with plenty of low-severity notes and no confidence about what was missed. The alternative is to treat the engagement as a sequence of constraints and experiments. You decide what "broken" means, find every place where it could be made true, and test those places in order of expected loss.
This post gives that sequence for a multi-contract system with external integrations, upgrades and MEV exposure. To keep it concrete, every step is applied to one real file: EToken.sol in Euler v1 as it stood at commit dfaa778, a month before the exploit of 13 March 2023. The working habits around the sequence (notes, environment, cadence, variant analysis) are in The Auditor Operating System.
Step 0: define what you are protecting#
Start from what is deployed and configured, since that is what holds value, and find the asset boundary before reading any logic. Four questions get you there.
| Question | What you look at first |
|---|---|
| Where can funds leave? | withdraw and transfer paths, settlement, rescue functions |
| Who can change the rules? | governance and admin roles, upgrade hooks |
| What can revert and freeze progress? | token calls, hooks, oracle reads |
| What is assumed honest? | keepers, relayers, off-chain signers |
Then write the guarantees as sentences and keep them at the top of your notes. For a lending market such as Euler they read roughly as follows.
- Depositors can withdraw their share of the pool whenever it has liquidity (liveness).
- No action an account takes on itself leaves its debt under-collateralised (safety).
- Only governance changes asset configuration (authorization).
- Moving a price far enough to matter costs more than it can earn (economic security).
When the specification does not state such guarantees, infer them from the tests, the documentation and the economics, and confirm them with the team. A disagreement at this point is often the most valuable result of the engagement, because the code may faithfully implement a rule the team never intended.
Step 1: map entry points and privilege#
List every externally callable function that changes state and sort the list by who can call it.
| Category | Why it matters | Common failure |
|---|---|---|
| permissionless | largest attack surface | missing checks, unbounded work |
| role-gated | a privilege mistake is total | misconfigured role, bypass through another path |
| admin-only | governance is code plus operations | unsafe upgrade, key risk |
| contract-only | "only this contract" guards are brittle | reachable through a wrapper or a delegatecall |
| upgrade paths | they replace every other guarantee | unprotected initializer, weak upgrade authorization |
| callback paths | they are entry points the ABI does not list | hooks and receivers entered while state is half-updated |
The map earns its keep when you add a column for the guarantee from Step 0. For Euler's eToken the safety sentence is enforced by checkLiquidity, so the column records whether each balance-changing function calls it.
| Function | Effect on the caller | Calls checkLiquidity? |
|---|---|---|
deposit | raises collateral | only if the account has debt |
withdraw | lowers collateral | yes |
mint | raises collateral and debt together | yes |
burn | lowers collateral and debt together | yes |
transferFrom | lowers the sender's collateral | yes, on the sender |
donateToReserves | lowers collateral | no |
One row is different, and it is the row the attacker used. donateToReserves had been in the code since July 2022, and the table that exposes it takes minutes to build with grep. If time allows nothing else, enumerate the state-changing entry points and check each against the guarantees, because a function that changes guarded state without running the guard is the failure we would look for first in any codebase.
Step 2: draw the external-call graph#
Before reading line by line, mark the edges where execution leaves code you trust: token calls, oracle and pool reads, callbacks and hooks, low-level calls and delegatecall. A useful note names the edge and its position relative to the accounting, for example "withdraw pushes tokens to the caller and then decreases the balance".
For each edge, write down what the party on the other side can do that the code does not expect.
| Edge | What the other side can do | Seen in |
|---|---|---|
| token call | return nothing or false, keep a fee, call back into you | ERC-777 hooks at Cream, August 2021 |
| oracle or pool read | answer truthfully about a state the caller has just set | Makina, January 2026 |
| callback or hook | reenter while your state is half-updated | read-only and cross-contract reentrancy |
| low-level call | revert, burn the forwarded gas, return a huge payload | gas griefing and untrusted reverts |
delegatecall | run code on your storage and see the outer call's msg.value in every sub-call | MISO's batch, reported in 2021 |
Most DeFi systems are glue between tokens, oracles, bridges, routers and staking modules, so each dependency deserves three lines in your notes: what it guarantees, what it can do unexpectedly, and what your code does when it fails. A dependency that can revert hands you a liveness risk, and one that can call back hands you a control-flow risk. In Euler's withdraw the tokens leave before the balance is decreased, which is safe only because the function is nonReentrant and ends with the liquidity check. That is a claim you can now verify instead of a line you skimmed past.
Step 3: derive invariants and make them testable#
An invariant is useful when you can describe the transaction that would falsify it. "The protocol is safe" fails that test, and the following pass it.
- Total shares stay consistent with total assets under the documented rounding rules.
- Debt decreases only through repayment or liquidation.
- A message id is consumed at most once.
- Every privileged action requires an explicit role.
When a guarantee resists precise wording, phrase it as the directions in which a variable may move and under what conditions: fee growth never decreases, an account's health can fall only through a price move or the account's own borrow, a nonce only increases. Each of these becomes a check after a random sequence of calls. Invariant-First Auditing shows how to turn them into a Foundry harness and reproduces the Euler pattern in a small model.
Step 4: isolate the highest-yield bug classes#
Audit time is limited, so spend it where historical losses concentrate. These are the places to read slowly, with the post that covers each class.
- external calls in the middle of accounting (reentrancy)
- upgradeability and initialization (initializers and UUPS)
- signature verification and replay boundaries (EIP-712 and permit)
- oracle reads and price assumptions (oracles and TWAPs)
- rounding direction in share and debt math (rounding in DeFi)
- loops over state that can grow, and calls whose return values are ignored (liveness)
Step 5: turn hypotheses into tests#
A suspicion becomes a finding or a dismissed idea only when it is executed. Writing the test forces the precondition, the call sequence and the expected loss to be stated exactly, and it leaves the project with a regression artifact.
| Risk | Test style | Why |
|---|---|---|
| rounding and accounting | property plus fuzz | the failing inputs sit in corners nobody types by hand |
| reentrancy | attacker contract plus trace | the trace makes the order of calls and writes explicit |
| unusual tokens | assertions on balance deltas | catches fee-on-transfer and missing return values |
| upgrades | upgrade simulation on a fork | catches storage layout drift and initializer mistakes |
| oracle manipulation | scenario on a fork with borrowed liquidity | puts a number on the cost of the attack |
The small suite that results encodes the threat model in executable form. Foundry for Security has working examples of the first three rows.
Step 6: rate severity by impact and exploitability#
Reports lose credibility when something alarming and unreachable is rated critical. A rubric with the evidence each level requires keeps the rating honest.
| Severity | Typical impact | Typical exploitability | Evidence to attach |
|---|---|---|---|
| Critical | direct loss of funds or permanent loss of control | feasible on mainnet by anyone | fork PoC that ends with the attacker holding the funds |
| High | large loss, protocol insolvency or permanent freeze | plausible under mild, stated assumptions | exploit path with every assumption named, test for the core step |
| Medium | bounded loss, temporary freeze, griefing | needs timing, particular state or a cost to the attacker | costed scenario |
| Low | hardening gap, unsafe default | unlikely or minor | code pointer and the missing check |
| Informational | clarity, documentation | none | suggestion |
The assumptions carry the rating. "Critical if the attacker can choose the token" and "critical if only a timelocked governance can list the token" are different findings. Public scales say the same thing in their own words: Code4rena reserves High for assets that can be stolen through a valid attack path and assigns Medium when assets are not at direct risk or the path depends on stated assumptions and external requirements, and Immunefi's scale is organised by impact and downgrades bugs that need elevated privileges.
Step 7: write findings that lead to fixes#
A finding is one engineer handing another a reproducible bug. Lead with what breaks, because a report that opens with "the code does X" invites an argument about whether X matters, while "a user can take Y under conditions Z" starts the discussion at the fix. The order that works is impact, root cause, preconditions, exploit sketch, recommendation and regression test.
Below, the Euler bug is written that way, after the fact and from public information, to show the form.
Impact: Any account can make itself insolvent on purpose and collect the liquidation discount from a second account, which lets it drain a market's deposits. The realised loss was about $197M.
Root cause: EToken.donateToReserves reduces the caller's eToken balance and never calls checkLiquidity, unlike withdraw, mint, burn and transferFrom in the same module.
Preconditions: None beyond capital, which a flash loan supplies.
Exploit sketch: Deposit, use mint to build a leveraged eToken and dToken position, donate eTokens until debt exceeds collateral, liquidate the position from a second account at a discount, withdraw the underlying.
Recommendation: Call checkLiquidity(account) at the end of donateToReserves, and add an invariant test asserting that no self-initiated action leaves an account unhealthy.
Regression: The invariant above, with a handler for every balance-changing function.
It is actionable because it names one guarantee, one function that escapes it and one line that restores it. For the structure of the report around the findings, D-Squared's notes on the ideal audit report are a good reference.
Step 8: verify the fix and lock regressions#
A fix counts when the failing test passes, the invariants hold again, and the test stays in the suite. Treat the patch as new code and repeat Steps 1 and 2 on the diff, since fixes add entry points too. Euler Labs' own account of the incident says donateToReserves was introduced while patching a different issue, and the commit that added it shipped tests for donations only from accounts with no debt.
Step 9: surface operational risk#
A share of incidents filed under smart contract bugs are operational: a compromised upgrade key, a timelock that a misconfigured role lets anyone bypass, an initializer run with the wrong value. The Nomad bridge was drained in August 2022 after an upgrade initialised the trusted root to zero, which made every unproven message acceptable. Operations are outside an auditor's control, and the report should still state where admin power exists, what a malicious admin can do and what a compromised one can do, so that readers can see when safety depends on flawless operations. The questions to ask are in the upgradeability section of the companion post.
Where tools fit#
Tools buy coverage and time, and the threat model still has to come from you. Use them to find functions and edges you might miss by eye, to check whether a hypothesis is reachable, and to capture traces and minimal reproductions as evidence.
| Tool | Good for | Weak at |
|---|---|---|
| Slither | detectors for known patterns, and printers such as entry-points, vars-and-auth and call-graph that draft the maps in Steps 1 and 2 | protocol-specific invariants, economics |
| Foundry | reproducing, fuzzing, fork tests | issues nobody hypothesised |
| Tenderly and trace viewers | following execution paths of real transactions | proving economic safety |
| Semgrep | project-specific pattern hunts across a codebase | reasoning across functions without carefully written rules |
| Echidna, Medusa, Halmos | long property campaigns and bounded symbolic checks | properties you have not written |
The failure mode is to run the tools and paste their alerts into the report. An alert is worth keeping when it changes the model, the map or a test. For choosing between fuzzing and symbolic or formal methods, see Halmos vs Lean.
Watch: audit techniques and tools (Secureum)#
This Secureum lecture is a good companion to the steps above. It covers how to think about attack surfaces and how to use tools as filters.
Sources#
- euler-contracts,
EToken.solat commitdfaa778, the file behind the Step 1 table, and commit85abe8d, which addeddonateToReservesin July 2022. - Euler Labs, "War and Peace: Behind the Scenes of Euler's $240M Exploit Recovery", for the loss figure, the missing health check and the origin of the function.
- Code4rena severity categorization and Immunefi Vulnerability Severity Classification System v2.3, the public scales compared in Step 6.
- Slither, whose printers are named in the tool table (checked at release 0.11.6).
- D-Squared, "The Ideal Audit Report", on report structure.
- Trail of Bits, Building Secure Contracts, for development and review guidelines that complement this sequence.