CCamoCrypt
Guide

DeFi mechanics and risk: the complete guide

A sober, source-based walkthrough of how decentralised finance actually works — AMMs, liquidity, lending, impermanent-loss arithmetic, audits and bridge risk — written as documentation, not investment guidance.

Last reviewed: September 2026 — security guidance re-reviewed on a six-month cycle.

Quick answer

DeFi replaces trusted intermediaries with smart contracts that pool assets and run public rules. This guide explains the mechanics: constant-product AMMs and price impact, concentrated liquidity, impermanent-loss arithmetic, overcollateralised lending and liquidation, oracle and flash-loan risk, what audits can and cannot prove, and why bridges are the most attacked component. It covers risk only — no prices, returns, or advice.

Key points

  • Constant-product AMMs price assets as a ratio of reserves (x·y=k); large trades cause price impact, and arbitrage keeps pool prices aligned at liquidity providers' expense.
  • Impermanent (divergence) loss is deterministic math from the pool curve: a 2x relative price move implies about -5.7% versus holding, a 4x move about -20%.
  • On-chain lending relies on overcollateralisation and a health factor; when it falls to 1 the position is liquidated automatically at a discount.
  • Oracle manipulation and flash loans, not broken lending math, drive a large share of exploits; composability spreads risk across every protocol a position touches.
  • Audits reduce known-bug risk but never prove safety; admin keys, upgradeability and unreviewed upgrades are often the biggest risk facts about a protocol.
  • Bridges use lock-and-mint with trusted validators and are the ecosystem's most attacked component; a wrapped asset carries bridge risk on top of the underlying.

What DeFi is, and what it is not

Decentralised finance (DeFi) is a label for financial applications built as smart contracts on public blockchains. Instead of a bank, broker, or exchange holding your assets and executing instructions on your behalf, code deployed to a network such as Ethereum holds pooled assets and executes deterministic rules that anyone can read, call, or build on top of. The promise is not that risk disappears; it is that custody and settlement move from a company you must trust to a program whose logic is public. This guide describes the mechanics and the risks. It does not describe returns, does not recommend any protocol or asset, and treats every design choice as a trade-off rather than a feature.

Three properties distinguish DeFi from the systems it imitates. First, it is non-custodial by default: assets sit in contracts governed by rules, not in an account a firm can freeze or reassign, although many front-ends and bridges reintroduce custodians in practice. Second, it is composable: one protocol can call another in the same transaction, so a lending market, an exchange, and a stablecoin can be chained together atomically. Third, it is permissionless at the contract layer: the code does not check who you are before it runs. Each property is simultaneously the source of DeFi’s flexibility and the source of most of its failure modes.

It helps to separate three layers when reasoning about any DeFi position. The protocol layer is the smart-contract logic itself. The economic layer is the incentive design that is supposed to keep the protocol solvent and its prices honest. The operational layer is everything around the edges: the web front-end, the wallet, the bridge, the oracle, and the governance keys. A protocol can be mathematically sound and still lose user funds because of a compromised front-end or a mispriced oracle. Most of the remainder of this guide is organised around those layers.

Automated market makers: the constant-product model

Traditional exchanges match buyers and sellers through an order book. Most on-chain exchanges instead use an automated market maker (AMM): a contract that holds reserves of two or more tokens and quotes a price algorithmically from those reserves. The canonical design is the constant-product AMM introduced by Uniswap v2, which maintains the invariant that the product of the two reserves stays constant across every trade.

Write the reserves of the two tokens as x and y. The pool enforces:

x * y = k

where k is the invariant that must not decrease. When a trader sells token A into the pool, x rises; to keep the product at k, the contract releases only enough of token B to bring y down to k / x_new. The spot price offered by the pool is simply the ratio of reserves, y / x. There is no counterparty quoting a price; the curve is the counterparty.

Two consequences follow directly from the arithmetic. The first is price impact: because the price is a ratio of reserves, a trade that is large relative to the pool moves the ratio significantly, so the average execution price is worse than the price at the start of the trade. Small trades execute close to spot; large trades slide along the curve. The second is that the curve never runs out of liquidity in a nominal sense — the hyperbola x·y=k asymptotes to the axes — but the price to drain the pool of one asset rises without bound, which is the intended defence against emptying a pool.

Uniswap v2 applies a fee on the input amount of each swap, historically 0.30%, which is retained in the reserves and therefore accrues to liquidity providers in proportion to their share of the pool. The fee is what compensates providers for supplying capital and for the risk described below; it is not a yield promise and its realised value depends entirely on trading volume that no one can guarantee.

Why arbitrage keeps AMM prices honest

An AMM has no idea what an asset is worth anywhere else; it only knows its own reserves. Its prices are kept aligned with the wider market by arbitrageurs. If the pool price drifts below the price on another venue, a trader buys from the pool until the ratio corrects, pocketing the difference. This is elegant but it has a cost that is borne by liquidity providers, discussed under impermanent loss. It also means an AMM price is only as reliable as the arbitrage around it: a thinly traded pool can be pushed a long way from fair value, which is precisely why using a raw AMM spot price as an oracle is dangerous.

Concentrated liquidity and specialised curves

The constant-product curve spreads a provider’s capital across every possible price from zero to infinity, even though almost all trading happens in a narrow band. That is capital-inefficient. Two families of design address it.

Concentrated liquidity

Uniswap v3 lets a provider allocate liquidity to a chosen price range rather than the whole curve. The price space is divided into discrete ticks, where each tick represents a fixed 0.01% step in price. A provider deposits between a lower and upper tick; their capital only earns fees while the market price sits inside that band, and it is fully converted into the less valuable of the two assets if price exits the band. Uniswap’s own documentation illustrates the efficiency gain with a stablecoin pair: under the older full-range model, only a small fraction of capital — on the order of half a percent — was actually doing work in the tight band around the peg where most volume occurs. Concentration lets providers put far more depth where trading happens, but it converts a passive position into an active one: a range that the price leaves stops earning and must be managed.

Stable-asset curves

Curve’s StableSwap design targets assets that are meant to trade near parity, such as different dollar stablecoins. It blends a constant-sum curve (which gives zero slippage but no defence against depletion) with a constant-product curve (which resists depletion but adds slippage) and governs the blend with an amplification coefficient A. A high A makes the curve very flat near the peg, delivering low slippage for like-for-like swaps; as the pool becomes imbalanced the curve gracefully degrades toward constant-product behaviour so it still resists being drained. The lesson generalises: an AMM curve encodes an assumption about how the assets are expected to move relative to each other, and that assumption is a risk if it turns out to be wrong — a stable pair curve behaves badly precisely when a “stable” asset loses its peg.

Providing liquidity and the arithmetic of impermanent loss

When you deposit into a pool you receive LP tokens representing your pro-rata claim on the reserves plus accrued fees. Redeeming them returns your share of whatever the reserves then contain — which is not the same as what you put in, because the pool rebalances continuously as arbitrageurs trade against it.

Impermanent loss (better called divergence loss) is the gap between holding the two assets in a pool and simply holding them in a wallet, caused purely by relative price movement. It is not a fee, a hack, or a bug; it is a direct mathematical consequence of the constant-product curve. For a two-asset constant-product pool, if the price of one asset relative to the other changes by a factor p from the moment you deposited, the value of your pool position relative to simply holding is:

IL(p) = 2 * sqrt(p) / (1 + p) - 1

The result is always zero or negative, and it is symmetric: the pool underperforms holding whether the price rises or falls, because rebalancing always sells the appreciating asset and buys the depreciating one. Because the formula is deterministic, the figures can be computed exactly rather than estimated:

Price ratio change (p) Divergence loss vs. holding
1.25x -0.6%
1.5x -2.0%
2x -5.7%
3x -13.4%
4x -20.0%
5x -25.5%

The word “impermanent” is misleading: the loss only reverses if relative prices return to where they were when you deposited. If you withdraw after a permanent divergence, it is realised. Trading fees accrue against this loss, and whether fees exceed divergence loss over a given period is unknowable in advance because it depends on volume and volatility that no one controls. This guide makes no claim that they do or do not; the point is purely that the loss is structural and must be modelled, not assumed away.

Concentrated-liquidity positions experience the same effect in a sharper form: within a tight range the divergence loss for a given price move is larger, which is the flip side of the higher fee density. A provider is, in effect, being paid more per unit of capital for taking a more concentrated version of the same risk.

Lending and borrowing protocols

On-chain lending markets such as Aave and Compound let suppliers deposit assets into a shared pool and borrowers draw from it against collateral. There is no credit check and no repayment schedule in the traditional sense; the entire system is held together by overcollateralisation and automated liquidation.

Overcollateralisation, LTV and the health factor

Because a borrower is pseudonymous and cannot be pursued, they must post collateral worth more than they borrow. Each collateral asset is assigned a loan-to-value ratio (how much can be borrowed against it) and a liquidation threshold (the point at which the position is unsafe). Aave summarises position safety in a single health factor, defined in its documentation as:

Health Factor = (collateral value * weighted-average liquidation threshold) / total borrow value

A health factor above 1 is safe; when it falls to 1 or below, the position becomes eligible for liquidation. It falls when collateral loses value, when borrowed assets gain value, or simply as interest accrues on the debt. This is the central risk of borrowing in DeFi: your position can be closed automatically and at a discount, without warning and without any human deciding to be lenient.

Liquidation

When a position crosses the threshold, third-party liquidators repay part of the debt and receive collateral at a discount, called the liquidation bonus. This is what keeps the pool solvent — bad debt is cleared by paying someone to clear it — but it means a borrower pays a penalty precisely at the worst moment, and during sharp market moves liquidations can cluster, congesting the network and pushing prices further, a feedback loop discussed below.

Interest-rate models and utilisation

Borrowing and supply rates are set algorithmically from utilisation: the fraction of the pool that is currently borrowed. As utilisation rises, rates rise, which is meant to attract suppliers and discourage borrowing so that some liquidity remains available for withdrawal. A practical consequence is that suppliers are not guaranteed to be able to withdraw on demand: if utilisation is at or near 100%, there is simply nothing in the pool to return until borrowers repay or new supply arrives. Rates are variable and reflexive, not contractual.

Composability and its systemic risks

Because protocols can call each other atomically, DeFi positions are frequently stacked: collateral in one market is borrowed against, the borrowed asset is supplied to a second market, LP tokens are themselves used as collateral, and so on. This “money-lego” composability is DeFi’s most distinctive feature and its most underappreciated risk. Three failure modes recur.

Oracle risk

Lending markets and derivatives need to know the price of collateral, and they get it from an oracle. If the oracle can be manipulated — for instance by pushing a thin AMM pool that the oracle reads — an attacker can make worthless collateral appear valuable, borrow against it, and walk away, or trigger liquidations that should not happen. A large share of DeFi exploits are oracle-manipulation attacks rather than breaks of the core lending math. Robust protocols use time-weighted averages or independent price feeds precisely to make this expensive, but no oracle is unmanipulable in principle.

Flash loans as an amplifier

A flash loan lets anyone borrow an arbitrary amount within a single transaction provided it is repaid before the transaction ends. It is a legitimate tool, but it removes the capital barrier to manipulation: an attacker no longer needs to own a large position to move a thin market, because they can borrow one for the length of one block. Flash loans do not create vulnerabilities; they make existing ones — especially oracle and accounting bugs — cheap to exploit at scale.

Cascading liquidations and contagion

When positions are chained across protocols, the failure of one can propagate. A sharp price move triggers liquidations, liquidations sell collateral into the market and push prices further, which triggers more liquidations, and any protocol holding the affected assets as collateral inherits the stress. Composability means the boundary of your risk is not the protocol you chose but every protocol it touches, directly or through shared collateral and oracles.

Smart-contract risk: what audits do and do not cover

Every DeFi interaction is a call to code that, once deployed, generally executes exactly as written — including its bugs. The dominant categories of smart-contract vulnerability have been stable for years: access-control mistakes (a privileged function anyone can call), input-validation failures, and reentrancy, where a contract calls out to another that calls back in before the first has updated its state. Understanding what mitigations exist, and their limits, is essential.

Audits

A security audit is a manual and tool-assisted review by a specialist firm — Trail of Bits and OpenZeppelin are among the best known — that looks for known vulnerability classes and design flaws. Audits are valuable and reduce the probability that a known class of bug is exploitable. They are not proofs of safety. As auditors themselves state, manual review based on pattern recognition catches common cases but degrades where syntactically similar code differs in security-critical ways, and novel attack vectors, economic attacks, oracle manipulation, and integration risk are difficult to capture in any single review. A protocol being “audited” tells you a review happened; it does not tell you the review was comprehensive, that the deployed code matches what was audited, or that later upgrades were reviewed.

Automated analysis and formal verification

Static analysers (such as Slither), fuzzers (such as Echidna), and symbolic-execution tools extend human review by exploring many code paths automatically. Formal verification goes further, mathematically proving that code satisfies a specification. It is powerful but expensive — auditors note it can multiply developer effort several-fold — and, crucially, it only proves the properties you thought to specify. A contract can be formally verified against its spec and still lose funds if the specification itself failed to anticipate an economic attack.

Immutability, upgradeability and admin keys

An immutable contract cannot be changed, which means a bug cannot be patched but also that no one can insert a malicious change. Many protocols instead use upgradeable proxies and admin keys so they can fix bugs and adjust parameters. This reintroduces a trusted party: whoever controls the keys can, in principle, change the rules or drain the contract, whether maliciously or through a compromised key. Bug-bounty programmes and timelocks (which delay privileged actions so users can react) are partial mitigations. The honest summary is that “decentralised” is a spectrum, and the location of the admin keys is often the most important risk fact about a protocol.

Bridges and cross-chain risk

Assets are native to one chain, so moving value between chains requires a bridge. The most common design is lock-and-mint: you lock the native asset in a contract on the source chain, and a wrapped representation is minted on the destination chain, redeemable one-for-one later. The wrapped token is only as good as the guarantee that the locked collateral is safe and that redemption will be honoured.

The hard problem, as Chainlink’s own risk documentation sets out, is the trust assumption: something must verify that the lock on chain A really happened before authorising the mint on chain B. Many bridges delegate this to an off-chain set of validators or a multisignature — which concentrates trust in those key-holders. If an attacker compromises enough validator keys, through phishing or a server breach, they can authorise mints that are not backed by any lock and drain the bridge. Bridges have consequently been among the most heavily attacked components in the entire ecosystem, with cumulative losses reported in the billions of dollars. Newer designs attempt to replace trusted validators with cryptographic proofs so the destination chain can verify source-chain events directly, but these are harder to build and are not yet universal.

The practical takeaways are concrete. A wrapped asset carries the bridge’s risk in addition to the underlying asset’s risk. Holding value on a chain you reached through a bridge means your ability to leave depends on that bridge remaining solvent and operational. And “the asset bridged fine last week” is not evidence of safety, because bridge failures are typically sudden, total, and driven by a key compromise rather than gradual degradation.

A framework for reasoning about a protocol

Rather than a checklist of what to buy, the useful output of understanding DeFi mechanics is a set of questions that expose where a position’s risk actually lives. Where is custody — is the contract genuinely non-custodial, or does a bridge or front-end reintroduce a trusted party? Where are the admin keys, and can they change the rules or move funds, and behind what delay? What does the protocol assume about prices, and where does it get them — can that oracle be pushed? What is the collateral, and is any of it wrapped or itself a claim on another protocol? What has been audited, by whom, when, and does the deployed and current code match that review? And finally, what happens under stress — does a sharp price move trigger liquidations that feed back on themselves, and how much of the system shares the same collateral, oracle, or bridge?

None of these questions concern price or return, and that is deliberate. The mechanics above determine how and why a DeFi position can lose value for reasons that have nothing to do with the market going the wrong way. A position can be correct about the market and still be zeroed by a bridge exploit, an oracle manipulation, an admin-key compromise, or a divergence loss the provider never modelled. The discipline of DeFi is separating those risks so each can be examined on its own terms.

Sources

Frequently asked questions

Is impermanent loss a bug or a fee?
Neither. It is a direct mathematical consequence of the constant-product curve rebalancing your position as relative prices move. It is only realised if you withdraw while prices have diverged from where you deposited; if they return to the original ratio, it disappears.
Does an audit mean a protocol is safe?
No. An audit means a specialist review looked for known vulnerability classes at a point in time. It cannot prove the absence of bugs, cannot anticipate every economic or oracle attack, and does not guarantee the deployed or later-upgraded code matches what was reviewed.
Why are bridges considered so risky?
Most bridges lock assets on one chain and mint a wrapped version on another, relying on a set of validators or a multisignature to attest that the lock happened. Compromising those keys lets an attacker mint unbacked tokens, which is why bridges have suffered some of the largest exploits.
What is a flash loan and why does it matter for security?
A flash loan lets anyone borrow a large amount within a single transaction as long as it is repaid before that transaction ends. It does not create vulnerabilities, but it removes the capital barrier to exploiting oracle and accounting bugs, making attacks cheap to attempt at scale.
Can I always withdraw assets I supplied to a lending pool?
Not necessarily on demand. Withdrawals come from the un-borrowed portion of the pool. If utilisation is near 100%, there may be nothing available to return until borrowers repay or new supply arrives, though rising rates are designed to correct this over time.
What is the single most useful risk question to ask about a DeFi protocol?
Where are the admin keys and what can they do. Upgradeable contracts with privileged keys reintroduce a trusted party who could change the rules or move funds, so the location and controls around those keys are often the most important risk fact, alongside how the protocol sources its prices.

Note: CamoCrypt is security & education only — no prices, no predictions, no investment advice. Verify every address and contract yourself; we cannot recover lost funds and neither can anyone who contacts you claiming they can.