Sub topic 10
Smart contract and protocol risk in DeFi
This chapter assumes you know what a blockchain and a wallet are, and that you have bought and sold crypto on an exchange. It also assumes you can read short Python snippets. This is educational material and not financial advice.
What smart contract risk is
A smart contract is a program stored on a blockchain that runs exactly as written. Decentralized finance (DeFi) is a set of lending, trading and yield services built from these programs. Nobody operates a desk, and no company can reverse a transaction for you.
Smart contract risk is the chance that you lose funds because the code, or the system around it, does not behave as its users expect. The price of the asset can stay flat and you can still lose everything you deposited.
This differs from market risk, which comes from price moves. It also differs from counterparty risk on an exchange, where a company holds your funds. In DeFi the "counterparty" is code plus the people who can change it.
Three properties make this risk hard to manage:
- Deployed code is public, so attackers can study it for as long as they like.
- Transactions are final. A drained contract rarely gives money back.
- Funds in a contract are often a single pool. One flaw can expose every depositor at once.
Where losses come from
Protocol risk has several distinct sources. Auditing the code addresses only some of them.
| Source | What goes wrong | Typical example |
|---|---|---|
| Code bug | Logic does not match intent | Missing check lets anyone withdraw |
| Reentrancy | A contract is called again before it updates its state | Repeated withdrawals from one balance |
| Oracle manipulation | The price feed a protocol trusts is distorted | Attacker moves a thin pool's price, then borrows against it |
| Admin key risk | A privileged account can change or drain the system | Stolen upgrade key replaces the contract |
| Economic design flaw | Code works, incentives fail | Collateral falls faster than liquidations can run |
| Dependency risk | A protocol relies on another that fails | A lending market accepts a broken token as collateral |
| Bridge risk | Assets locked on one chain back a copy on another | Locked funds are stolen, so the copy is unbacked |
Code bugs and reentrancy
Reentrancy is a classic bug. A contract sends funds to a caller before it records that the balance has been spent. The caller's code runs on receipt and calls withdraw again. The balance still looks unspent, so the contract pays again.
The sequence looks like this.
The standard fix is the checks-effects-interactions pattern. The contract checks conditions, updates its own state, and only then sends funds to outside code.
Oracle manipulation
An oracle is a service that feeds off-chain or cross-market data, usually prices, to a contract. If a lending protocol reads its price from one small trading pool, an attacker can push that pool's price with a large trade. The attacker then borrows more than the collateral is really worth. This is why protocols that use thin pools as price sources are risky, and it links directly to the liquidity risk chapter.
Admin keys and upgradeability
Many protocols can be upgraded, or have an "owner" who can pause them, change parameters or mint tokens. That helps fix bugs. It also means you trust whoever holds that key. A protocol described as decentralized may still have a single wallet that can change the rules.
Questions to ask:
- Who can upgrade the contract, and is it one key or a multi-signature wallet?
- Is there a timelock, a delay between announcing a change and applying it, so users can exit first?
- Can the owner move user funds, or only change settings?
Composability and dependency risk
DeFi protocols plug into each other. A yield vault may deposit into a lending market, which accepts a stablecoin as collateral, which relies on an oracle. A failure at any layer can pass upward. Your risk is the combined risk of the whole stack, not that of the app you see.
Audits do not remove risk
An audit is a review of code by outside specialists. It lowers the chance of known classes of bugs. It does not guarantee safety, for these reasons:
- It covers one version of the code at one time. Later upgrades may be unreviewed.
- It rarely covers economic design, oracle choices or admin key handling in depth.
- Auditors can miss bugs, and different firms vary in quality.
- Audited contracts have still been exploited.
Treat an audit as one input. Check what was in scope, whether findings were fixed, and whether the deployed code matches the audited code.
Signals of lower and higher risk
No checklist predicts failure. These signals help you rank protocols, not clear them.
| Signal | Lower risk | Higher risk |
|---|---|---|
| Time live with large deposits | Years, many market stresses survived | Weeks or months |
| Audits | Several, recent, issues resolved | None, or one old report |
| Admin control | Multi-signature wallet with a timelock | Single key, instant upgrades |
| Code | Verified source, widely forked and reviewed | Unverified or closed |
| Yield | Explainable from fees or interest | Far above market with no clear source |
| Dependencies | Few and well understood | Many layers and obscure collateral |
Unusually high yield deserves suspicion. If you cannot say where the return comes from, you may be the source of it.
Thinking about the odds in numbers
You cannot measure smart contract risk the way you measure volatility, because failures are rare and not normally distributed. You can still reason about it with a rough expected-loss estimate. Every input is a guess, so use it to compare options, not to predict outcomes.
def expected_loss(deposit, annual_failure_prob, loss_given_failure):
"""Expected yearly loss from a protocol failure."""
return deposit * annual_failure_prob * loss_given_failure
def net_yield(deposit, annual_yield, annual_failure_prob, loss_given_failure):
"""Yield after subtracting expected failure losses."""
gross = deposit * annual_yield
return gross - expected_loss(deposit, annual_failure_prob, loss_given_failure)
deposit = 5_000
options = {
"Mature lending protocol": (0.04, 0.02, 0.80),
"New high-yield vault": (0.30, 0.15, 0.90),
}
for name, (yield_rate, prob, severity) in options.items():
result = net_yield(deposit, yield_rate, prob, severity)
print(f"{name}: gross {deposit * yield_rate:.0f}, net after risk {result:.0f}")With these assumed inputs, the vault's 30% yield becomes a much smaller expected return once a 15% failure chance is counted. Change the probabilities and see how fast the ranking moves. The point is that a high yield is partly payment for a risk you are taking.
The same position-sizing logic from earlier chapters applies. If a protocol could plausibly lose 100% of a deposit, size the deposit so a total loss stays within what you can tolerate.
Practical habits
- Limit the amount in any single protocol. Assume a total loss is possible.
- Prefer protocols with long track records and fewer dependencies.
- Read what an approval does. When you sign a token approval, you may give a contract permission to spend your tokens. Grant only the amount needed, and revoke approvals you no longer use.
- Use a separate wallet for experiments, holding only what you can lose.
- Check how a protocol can be upgraded and who holds the keys.
- Watch for official incident announcements. If a protocol reports an exploit, withdrawing quickly may help, but be sure the message comes from a verified channel.
- Understand how you exit. Know whether withdrawals have delays or limits.
Note that insurance-like products exist in DeFi, but their cover is limited, depends on claims decisions, and is itself smart contract risk.
Common mistakes
- Judging safety by the number of users or the size of deposits alone. Large pools attract attackers too.
- Chasing yield without identifying its source.
- Ignoring the admin key because the app says "decentralized."
- Leaving unlimited token approvals active for contracts you no longer use.
- Forgetting layered risk: bridged tokens, wrapped assets and vault tokens each add a dependency.
Exercise
A new vault offers 25% a year. You estimate a 12% chance per year that it fails, with an 80% loss of deposits if it does. A mature lending protocol offers 4% with a 2% failure chance and the same 80% loss. For a 10,000 deposit, which has the higher yield after subtracting expected failure losses, and what does that tell you about how to treat the vault's headline rate?
Show answer
Vault: gross 2,500; expected loss 10,000 × 0.12 × 0.80 = 960; net 1,540. Mature protocol: gross 400; expected loss 10,000 × 0.02 × 0.80 = 160; net 240. The vault still comes out ahead in expectation, but only because the numbers are guesses. Its headline rate is partly compensation for a much larger chance of losing most of the deposit. A cautious holder would cap the position so an 80% loss stays within their tolerable loss, and would test how the result changes if the failure chance is 30%.
Exercise
Name three questions you should ask about a protocol's admin controls before depositing.
Show answer
Who can upgrade or change the contract, and is it one key or a multi-signature wallet? Is there a timelock that gives users time to exit before changes apply? Can the admin move user funds directly, or only adjust settings?