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.

Crypto Training•2026-02-09•12 min read

Audit workflow illustration

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.

QuestionWhat 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.

CategoryWhy it mattersCommon failure
permissionlesslargest attack surfacemissing checks, unbounded work
role-gateda privilege mistake is totalmisconfigured role, bypass through another path
admin-onlygovernance is code plus operationsunsafe upgrade, key risk
contract-only"only this contract" guards are brittlereachable through a wrapper or a delegatecall
upgrade pathsthey replace every other guaranteeunprotected initializer, weak upgrade authorization
callback pathsthey are entry points the ABI does not listhooks 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.

FunctionEffect on the callerCalls checkLiquidity?
depositraises collateralonly if the account has debt
withdrawlowers collateralyes
mintraises collateral and debt togetheryes
burnlowers collateral and debt togetheryes
transferFromlowers the sender's collateralyes, on the sender
donateToReserveslowers collateralno

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.

EdgeWhat the other side can doSeen in
token callreturn nothing or false, keep a fee, call back into youERC-777 hooks at Cream, August 2021
oracle or pool readanswer truthfully about a state the caller has just setMakina, January 2026
callback or hookreenter while your state is half-updatedread-only and cross-contract reentrancy
low-level callrevert, burn the forwarded gas, return a huge payloadgas griefing and untrusted reverts
delegatecallrun code on your storage and see the outer call's msg.value in every sub-callMISO'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.

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.

RiskTest styleWhy
rounding and accountingproperty plus fuzzthe failing inputs sit in corners nobody types by hand
reentrancyattacker contract plus tracethe trace makes the order of calls and writes explicit
unusual tokensassertions on balance deltascatches fee-on-transfer and missing return values
upgradesupgrade simulation on a forkcatches storage layout drift and initializer mistakes
oracle manipulationscenario on a fork with borrowed liquidityputs 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.

SeverityTypical impactTypical exploitabilityEvidence to attach
Criticaldirect loss of funds or permanent loss of controlfeasible on mainnet by anyonefork PoC that ends with the attacker holding the funds
Highlarge loss, protocol insolvency or permanent freezeplausible under mild, stated assumptionsexploit path with every assumption named, test for the core step
Mediumbounded loss, temporary freeze, griefingneeds timing, particular state or a cost to the attackercosted scenario
Lowhardening gap, unsafe defaultunlikely or minorcode pointer and the missing check
Informationalclarity, documentationnonesuggestion

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.

ToolGood forWeak at
Slitherdetectors for known patterns, and printers such as entry-points, vars-and-auth and call-graph that draft the maps in Steps 1 and 2protocol-specific invariants, economics
Foundryreproducing, fuzzing, fork testsissues nobody hypothesised
Tenderly and trace viewersfollowing execution paths of real transactionsproving economic safety
Semgrepproject-specific pattern hunts across a codebasereasoning across functions without carefully written rules
Echidna, Medusa, Halmoslong property campaigns and bounded symbolic checksproperties 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#