Skip to content
Tech Interview Prep home
Technical interview guide

DeFi Primitives (AMMs, Lending, Liquidity Pools)

The core building blocks of decentralized finance — automated market makers, lending protocols, and the liquidity pools they're built on.

Read
48 min
Practice MCQs
25
Interview QA
25
Edition
v3
Editorial status
Reviewed

Scope: Uniswap v2 and v3 specifications; Aave borrowing and liquidation documentation reviewed 2026-09-04 (version-specific parameters must be checked at integration); Chainlink Data Feeds; ERC-4626; ERC-3156; OWASP SCSVS.

Overview

Curated: · Written: · Reviewed:

DeFi is adversarial accounting composed across public state

Decentralized finance implements exchange, lending, borrowing, vaults and stable-value mechanisms as smart contracts. The code can make settlement rules transparent and composable, but it does not remove financial risk or intermediaries; it changes them into liquidity providers, validators, oracle operators, governance, administrators, bridge operators and contract dependencies. Every position is exposed to public ordering, atomic composition, volatile collateral and immutable accounting mistakes.

An automated market maker holds reserves and quotes trades from a curve instead of matching a central order book. In a constant-product pool, reserve product x·y is maintained subject to fees and rounding. Buying one asset removes it from the pool and adds the other, moving the marginal price against the trader. The execution price depends on trade size relative to liquidity; a displayed spot price is not a promise that a large trade can execute there.

Arbitrage aligns a pool with external markets by trading when prices diverge. This makes AMM pricing responsive but means the pool deliberately transfers value to arbitrageurs during adjustment. Liquidity providers earn fees while bearing inventory exposure, contract risk and loss relative to simply holding the assets when relative prices move—often called impermanent loss. The loss becomes economically realized when liquidity is withdrawn and may or may not be offset by fees.

Liquidity shares must preserve proportional ownership under deposits, withdrawals, fees and donations. Initial deposits and small rounding domains are dangerous: an attacker may manipulate assets-per-share before a victim deposit. Tokenized vaults need explicit preview, limit and rounding behavior, minimum liquidity or virtual offsets where appropriate, and balance-delta accounting for fee or rebasing tokens. A share token is a claim under contract rules, not guaranteed redemption at a fixed price.

Concentrated-liquidity AMMs let providers allocate capital within price ranges. This improves capital efficiency while the market stays in range, but positions become one-sided outside it and stop earning swap fees. Positions are nonfungible because ranges and fee-growth histories differ. Integrators must reason in ticks, liquidity and fee accounting rather than applying a simple v2 pool-share model.

Slippage limits and deadlines express user authorization. Public transactions can be sandwiched: an adversary trades before a victim to worsen the victim's execution, then reverses afterward. A minimum output or maximum input bounds direct loss; a deadline bounds stale execution. Private relays, batch auctions and intents introduce different trust and availability assumptions rather than eliminating ordering risk.

AMM spot prices are manipulable within one transaction, particularly in shallow pools. A time-weighted average raises the cost by requiring distortion across time, but security depends on observation window, liquidity, asset behavior, update mechanism and value at risk. External feeds require equally careful identity, decimals, freshness, range and failure checks. Multiple feeds are not independent if they share markets or operators.

Lending protocols pool supplier liquidity and issue overcollateralized debt. Utilization links available liquidity to borrow rates: higher utilization commonly raises rates to attract supply and encourage repayment. Interest accrues through indexes or share conversions, so rounding, update order and stale snapshots can create accounting divergence. Supplied assets are exposed to borrower default, oracle error, smart-contract failure and withdrawal illiquidity.

Loan-to-value controls new borrowing while the liquidation threshold defines when an existing position becomes eligible for liquidation. A health factor combines collateral value, configured thresholds and debt value; it moves with prices, interest and governance parameters. “Above one” is not a universal safety margin because volatility, liquidity, oracle cadence, congestion and correlated assets determine how quickly a position can cross the boundary.

Liquidators repay eligible debt and receive collateral plus an incentive. The bonus must cover gas, price movement and execution risk without over-penalizing borrowers. Close-factor and target-health rules determine liquidation size; dust rules prevent uneconomic remnants. If oracle prices lag, collateral gaps faster than keepers can act, liquidity disappears or transactions cannot land, the protocol can accumulate bad debt despite formally correct eligibility rules.

Flash loans lend assets and require principal plus fee before the transaction completes. Atomicity makes the lender whole or reverts, but temporary capital can amplify an oracle, governance, share-pricing or accounting weakness elsewhere. The flash loan is a financing tool, not usually the root cause. Security analysis should assume adversaries can access large temporary balances and compose every public protocol action in one transaction.

Stablecoins maintain a target through different mechanisms: redeemable reserves, overcollateralized debt, market incentives, protocol-owned assets or hybrids. A price near one does not prove reserves, redemption capacity or risk-free stability. Evaluate backing, custody, liquidation, oracle, liquidity, governance, censorship, maturity mismatch and stress recovery. Reflexive collateral and confidence-dependent incentives can fail together.

Governance sets parameters that are part of the financial engine: collateral factors, caps, rates, fees, oracle addresses, pause rules and upgrades. Changes can make existing positions unsafe or alter withdrawals. High-impact proposals need simulation, independent review, delayed execution, bounded authority and clear user exit. Governance tokens can be concentrated, delegated, borrowed or controlled through custodians, so vote count is not the entire trust model.

Composability creates both reuse and correlated failure. A vault may deposit into a lending market whose collateral price comes from an AMM and whose governance token is bridged. One pause, depeg, callback, upgrade or accounting change propagates through the stack. Inventory direct and transitive dependencies, cap exposure, handle emergency states and test integrated systems on realistic forked state.

Operate DeFi from invariants: assets cover claims, debt and collateral reconcile, fees cannot be created twice, no actor exceeds authorized withdrawal, and rounding loss is bounded. Test donations, first deposits, flash liquidity, oracle jumps and staleness, liquidation cascades, utilization extremes, fee tokens, rebases, callbacks, pauses, governance changes and reorgs. Monitor reserves, share price, utilization, health-factor distribution, bad debt, oracle divergence, liquidation latency, slippage, privileged events and dependency status. Production safety is the maintained ability to detect insolvency early and recover without silently rewriting claims.