Web3, DeFi & Blockchain Applications

Chapter 7
DeFi Foundations and Protocol Architecture

Advance Diploma in Blockchain
Web3, DeFi & Blockchain Applications   •   Advance Diploma

DeFi Foundations and Protocol Architecture

Introduction and Context

Decentralised finance (DeFi) is a set of blockchain-based financial services implemented primarily through smart contracts rather than conventional banks, brokerages, clearing houses, and custodians. DeFi applications can support exchange, lending, borrowing, derivatives, payments, asset management, and insurance. Their defining feature is not simply the use of cryptocurrency; it is the attempt to make financial rules transparent, programmable, and accessible through permissionless software.

DeFi does not eliminate financial risk. Instead, it redistributes and sometimes intensifies risks associated with code, collateral, market prices, governance, oracles, liquidity, and blockchain infrastructure. A professional understanding therefore requires both architectural knowledge and critical evaluation of incentives and failure modes.

Learning Objectives

By the end of this chapter, learners should be able to:

  • explain the principles and defining characteristics of DeFi;
  • describe money-lego composability and identify its benefits and risks;
  • calculate and interpret total value locked (TVL), collateralisation ratios, loan-to-value ratios, and simple annual percentage yield (APY);
  • map users, liquidity providers, validators, keepers, oracles, and governance across the DeFi stack;
  • distinguish protocol revenue from token incentives and gross transaction volume;
  • analyse the architecture and risks of a DeFi application;
  • evaluate governance, regulatory, ethical, and operational considerations.

1. What Makes Finance “Decentralised”?

Traditional finance usually depends on institutional intermediaries. A bank assesses borrowers, maintains accounts, controls settlement, and may use a central database. A decentralised protocol replaces some of these functions with smart contracts, blockchain consensus, cryptographic signatures, and publicly verifiable state.

The term “decentralised” is relative rather than absolute. A protocol may have decentralised transaction validation but highly concentrated governance, a single administrator key, or dependence on one oracle provider. DeFi should therefore be analysed across several dimensions:

DimensionTypical DeFi approachQuestion for analysis
AccessWallet-based, often permissionlessWho can use the service?
SettlementBlockchain transactionsWho confirms and finalises transactions?
CustodyUser-controlled or contract-controlled assetsWho can move funds?
RulesPublic smart-contract codeCan rules be changed, and by whom?
PricingMarkets and oracle systemsHow are asset values determined?
GovernanceToken voting, multisignature, or delegated systemsWho decides upgrades and parameters?

The practical objective is not to label a system simply decentralised or centralised, but to identify which functions are decentralised, which remain concentrated, and what risks follow.

2. Core DeFi Principles

Programmability

Smart contracts encode financial conditions. A lending contract can accept collateral, calculate a borrowing limit, accrue interest, and liquidate an unsafe position without a loan officer. Programmability permits complex products, but a coding error can become a financial error.

Permissionless participation

Many protocols allow anyone with a compatible wallet and sufficient transaction fees to interact. This improves access and composability, but it can also expose inexperienced users to sophisticated risks and make sanctions, consumer protection, and identity controls more difficult.

Transparency and verifiability

Contract code, transactions, balances, and many governance decisions are publicly observable. Transparency supports auditability, although public visibility does not guarantee that code is correct, that users understand it, or that off-chain dependencies are reliable.

Non-custodial design

In a non-custodial application, users generally retain control of their private keys, while smart contracts hold or manage assets according to programmed rules. Non-custody reduces reliance on a central custodian but transfers responsibility for key management and transaction authorization to users.

Economic incentives

DeFi protocols use fees, interest, liquidity rewards, collateral requirements, and governance tokens to encourage desired behaviour. Incentives must be analysed as economic mechanisms, not as guaranteed returns.

3. The DeFi Stack and Its Participants

A DeFi protocol is best understood as a layered socio-technical system.

Layered DeFi protocol architecture Users and wallets Applications and interfaces Protocols and smart contracts Oracles, keepers and governance Blockchain, validators and settlement
Layered DeFi protocol architecture
Figure: Layered DeFi protocol architecture

Figure: Functional layers of a DeFi protocol architecture.

Users and traders

Users supply assets, borrow, trade, stake, provide liquidity, vote, or combine several services. Their wallet signs transactions, but the wallet does not itself guarantee successful execution or asset safety.

Liquidity providers

A liquidity provider (LP) deposits assets into a pool so that other users can trade or borrow. In return, the LP may receive a share of fees and, in some systems, incentive tokens. LP exposure includes smart-contract risk, asset-price risk, impermanent loss, and pool imbalance.

Validators and sequencers

Validators order and confirm transactions on a blockchain. On some networks, sequencers temporarily order transactions for a layer-two system. Their behaviour affects finality, transaction costs, censorship resistance, and the possibility of transaction-ordering exploitation.

Keepers and liquidators

Keepers are automated actors that perform operational tasks, such as calling a rebalance or executing a liquidation when conditions are met. Liquidators repay or close unsafe debt in exchange for a liquidation incentive. Their competition can improve responsiveness, but congestion or insufficient incentives may delay intervention.

Oracles

Smart contracts cannot natively observe arbitrary off-chain prices. Oracles transmit external information, such as an exchange rate, into a blockchain. Oracle design may use multiple sources, time-weighted prices, medianisation, or decentralised reporting. Manipulated, stale, or illiquid price data can cause incorrect borrowing limits and liquidations.

Governance participants

Governance may set fees, collateral factors, supported assets, risk parameters, treasury allocations, and upgrade permissions. Voting power may be based on tokens, delegated representatives, or a multisignature council. Token voting is not automatically decentralised: concentrated holdings, low participation, delegation markets, and emergency administrators can substantially influence outcomes.

4. Money-Lego Composability

Composability means that one protocol can be used as a building block by another. A user might deposit a stablecoin in a lending market, receive an interest-bearing token, use that token as collateral elsewhere, and trade the resulting position on an automated market maker. These components resemble money legos because they can be assembled into new financial products.

Composability has three important forms:

  1. Syntactic composability: contracts can call other contracts through standard interfaces.
  2. Economic composability: assets produced by one protocol can represent claims that another protocol recognises.
  3. Atomic composability: several operations can occur in one transaction, with the transaction reverting if a required condition fails.

Composability can reduce development costs, increase liquidity, and support rapid innovation. It also creates dependency chains. If protocol A relies on B, B relies on C, and C relies on an oracle, a failure in C may propagate to A. This is often called composability or smart-contract systemic risk.

A robust design therefore specifies dependency boundaries, validates external inputs, limits privileges, and tests behaviour under congestion, price shocks, and partial failure.

5. Automated Market Makers and Liquidity

An automated market maker (AMM) allows trading against a pool rather than a conventional order book. A basic constant-product pool maintains:

x × y = k

Here, x and y are the reserves of two assets, while k is constant for an individual trade before fees. The formula applies to the idealised constant-product model and assumes that trades are executed against the pool without considering fees, external price updates, or liquidity changes during the transaction.

If a trader adds an amount ∆x of asset X, the ideal new reserve of asset Y is:

y' = k ÷ (x + ∆x)

The amount received is y − y'], before fees. As the trade becomes large relative to the pool, the execution price worsens; this is price impact. LPs earn fees but bear exposure to changing relative prices.

For a two-asset pool, the value of deposited assets can diverge from simply holding the assets. This difference is commonly called impermanent loss, although it becomes permanent if the LP withdraws while the price ratio remains changed. The exact outcome depends on pool design, fees, deposits, withdrawals, and price path.

6. Lending, Collateralisation, and Liquidation

DeFi lending is commonly overcollateralised because the protocol may not know a borrower’s identity, income, or legal recourse. A borrower deposits collateral and receives a smaller loan.

The collateralisation ratio is:

CR = VC ÷ VD × 100%

where VC is the market value of collateral and VD is the value of debt. The loan-to-value ratio is the inverse relationship:

LTV = VD ÷ VC × 100%

These formulas assume that collateral and debt values are measured in the same currency at the same valuation time. Interest, fees, volatile prices, oracle latency, and liquidation penalties must be included in a production risk calculation.

Suppose a borrower deposits collateral worth $10,000 and borrows $6,000. The initial LTV is:

LTV = 6,000 ÷ 10,000 × 100% = 60%.

If the protocol liquidates positions at 75% LTV, the collateral value at the threshold, ignoring debt growth, is:

VC = 6,000 ÷ 0.75 = $8,000.

Thus, a 20% fall from $10,000 to $8,000 reaches the stated threshold. In practice, liquidation may occur earlier or later because of interest accrual, oracle updates, transaction competition, and liquidation mechanics.

Liquidation protects lenders by selling collateral or otherwise reducing debt. It can also create cascading selling during market stress. Risk managers therefore consider debt ceilings, liquidation bonuses, asset liquidity, correlated collateral, oracle design, and emergency shutdown procedures.

7. TVL, APY, and Protocol Revenue

Total value locked

TVL is an estimate of the market value of assets deposited in a protocol or ecosystem. A simplified measure is:

TVL = ∑(qᵢ × pᵢ)

where qᵢ is the quantity of asset i locked and pᵢ is its selected market price in a common currency. TVL depends on the valuation timestamp, price source, asset inclusion rules, and treatment of borrowed or internally issued assets.

TVL is useful for observing scale and liquidity, but it is not equivalent to revenue, profit, security, or user welfare. TVL can rise because token prices rise, because incentives attract temporary deposits, or because the same economic value is counted across interconnected protocols.

Interest rates and APY

Annual percentage yield incorporates compounding, whereas annual percentage rate (APR) generally states a non-compounded annual rate. If a nominal periodic rate is r and compounding occurs n times per year, the effective annual yield is:

APY = (1 + r ÷ n)ⁿ − 1

This formula assumes a fixed rate, equal compounding periods, reinvestment of returns, and no fees, taxes, defaults, price changes, or interruption. For a nominal 12% rate compounded monthly, r = 0.12 and n = 12:

APY = (1 + 0.12 ÷ 12)12 − 1 ≈ 12.68%.

In DeFi, displayed APY may combine borrowing interest, trading fees, token emissions, and auto-compounding. A responsible analyst asks whether the yield is denominated in the deposited asset or a volatile reward token, whether it is sustainable, and what risks are excluded.

Protocol revenue

Protocol revenue is the value retained by the protocol or its treasury after distinguishing user-paid fees from amounts distributed to LPs, suppliers, or external service providers. A simplified identity is:

Gross fees = Volume × Fee rate

For example, $5,000,000 of eligible trading volume at a 0.30% fee produces $5,000,000 × 0.003 = $15,000 in gross fees. If 80% is paid to LPs and 20% is retained by the treasury, treasury revenue before operating costs is $3,000. This is not necessarily profit. Revenue analysis must also account for incentives, security costs, grants, bad debt, token emissions, and governance-directed spending.

8. Governance and Control Architecture

Governance determines who can change a protocol and under what conditions. Common mechanisms include:

  • token-holder voting;
  • delegated voting;
  • multisignature approval;
  • time-locked upgrades;
  • emergency councils; and
  • immutable contracts with no upgrade authority.

Each mechanism involves trade-offs. Immutable code reduces discretionary intervention but makes correction difficult. Upgradeable code permits security fixes but introduces administrator and governance risk. A timelock gives users an opportunity to exit before a change takes effect; it does not prevent a harmful decision.

A governance assessment should identify voting concentration, quorum rules, proposal thresholds, execution delay, emergency powers, conflicts of interest, disclosure practices, and the difference between formal voting power and effective control.

9. Illustrative Case: A Collateralised Stablecoin Protocol

Background. Consider an illustrative protocol, Atlas, that allows users to deposit ETH and mint a dollar-referenced stablecoin, AUSD. Atlas uses an external ETH/USD oracle and liquidates positions when LTV reaches 75%.

Problem. A user deposits ETH worth $20,000 and mints 10,000 AUSD. The initial LTV is 50%. A rapid ETH price decline reduces collateral value to $13,000 while debt remains $10,000 before interest. LTV becomes:

10,000 ÷ 13,000 × 100% ≈ 76.92%.

The position is now above the 75% threshold.

Approach. A keeper submits a liquidation transaction. A liquidator repays part of the AUSD debt and receives ETH at a discount specified by the protocol. The oracle must provide a sufficiently fresh price, and the blockchain must confirm the transaction before the collateral value falls further. Governance has previously selected the collateral factor, liquidation incentive, oracle configuration, and debt ceiling.

Outcome. The liquidation reduces lender exposure, but the borrower loses collateral and pays a penalty. If the oracle reports an inaccurate price, the position could be liquidated unfairly or remain unsafe. If ETH falls faster than liquidators can act, the protocol may incur bad debt.

Learning points. The case demonstrates that lending security is a system property. It depends on collateral valuation, contract logic, keeper incentives, transaction settlement, governance parameters, and market liquidity—not merely on the borrower’s initial collateral ratio.

10. Risks, Ethics, and Regulation

Technical risks

These include re-entrancy, arithmetic or logic errors, flawed access control, oracle manipulation, bridge vulnerabilities, upgrade-key compromise, denial of service, and transaction-ordering exploitation. Audits reduce but do not eliminate risk; formal verification is valuable for specified properties but cannot prove that the economic design is appropriate.

Market and liquidity risks

Tokens may lose value, pools may become imbalanced, and liquidations may occur during market-wide stress. Stablecoins can deviate from their reference value. Correlated collateral can make apparently diversified positions vulnerable to one common shock.

Governance and operational risks

Low voter participation, concentrated ownership, undisclosed conflicts, and rushed emergency decisions can undermine legitimacy. Dependence on a small development team or a single oracle operator creates operational concentration.

Ethical and regulatory considerations

Permissionless access can expand financial inclusion but may also expose users to unsuitable products, fraud, or irreversible loss. Designers should communicate risk clearly, avoid misleading yield claims, protect operational keys, and consider consumer protection, anti-money-laundering obligations, sanctions requirements, securities and derivatives rules, tax treatment, and data-protection law in relevant jurisdictions. Legal classification is fact-specific and changes over time; technical decentralisation does not automatically remove regulatory responsibility.

11. Best Practices for DeFi Analysis and Design

  1. Map every asset, contract, oracle, administrator, and external dependency.
  2. Separate TVL, volume, gross fees, retained revenue, incentives, and profit.
  3. State the source, timestamp, and methodology for all valuations.
  4. Use conservative collateral parameters and stress-test rapid price movements.
  5. Limit privileges, use hardware-secured keys, and apply upgrade timelocks.
  6. Test oracle staleness, liquidity gaps, transaction failure, and chain congestion.
  7. Publish assumptions, risks, liquidation rules, and governance procedures.
  8. Monitor concentration among LPs, borrowers, validators, keepers, and voters.
  9. Treat token emissions as a cost or subsidy rather than automatic revenue.
  10. Design for graceful degradation, including pauses and recovery procedures where justified.

Contemporary Developments

DeFi is increasingly deployed across multiple blockchain layers, creating trade-offs among cost, speed, liquidity fragmentation, and security assumptions. Liquid staking and restaking create composable claims on staked assets but may introduce correlated validator or slashing risk. Real-world asset protocols connect on-chain systems with custodians, legal contracts, and off-chain data, challenging the assumption that all claims are natively enforceable by code. Automated risk monitoring and machine-learning tools can improve anomaly detection, but AI outputs require validation and do not replace governance, audits, or accountable decision-making.

Chapter Summary

DeFi uses smart contracts, blockchain settlement, cryptographic wallets, incentives, and governance to provide programmable financial services. Its architecture includes users, applications, protocols, liquidity providers, validators, keepers, oracles, and governance actors. Composability enables protocols to function as money legos, producing innovation and efficiency while also creating dependency chains and systemic risk.

TVL measures the market value of selected deposited assets, but it is not a measure of profitability or safety. APY reflects compounding under explicit assumptions, while protocol revenue must be distinguished from gross fees, LP distributions, and token incentives. Overcollateralised lending relies on collateralisation and LTV thresholds, accurate oracles, motivated liquidators, and sufficient market liquidity. Effective DeFi analysis therefore combines technical, economic, governance, ethical, and regulatory perspectives.

Key Terms

DeFi: Blockchain-based financial services implemented through smart contracts and decentralised infrastructure.

Smart contract: Programmed logic executed by a blockchain or compatible execution environment.

Composability: The ability to combine protocols and contract functions as reusable components.

Money lego: A composable DeFi protocol used as a building block by another application.

Liquidity provider: Participant who deposits assets into a pool to facilitate trading or lending.

Automated market maker: Trading mechanism that prices assets through algorithmic pool rules.

Constant-product invariant: AMM relationship x × y = k for an idealised two-asset pool.

TVL: Estimated market value of assets locked in a protocol or ecosystem.

APY: Effective annual yield including specified compounding.

APR: Stated annualised rate that may exclude compounding.

Collateralisation ratio: Collateral value divided by debt value.

LTV: Debt value divided by collateral value.

Liquidation: Process of reducing unsafe debt by selling or transferring collateral.

Oracle: Mechanism that supplies external data to a blockchain contract.

Keeper: Automated actor that triggers an eligible protocol operation.

Validator: Network participant that helps order, confirm, or finalise blockchain transactions.

Governance: Process through which protocol parameters, upgrades, and resources are controlled.

Impermanent loss: Relative underperformance of an LP position compared with holding assets directly, under specified conditions.

Protocol revenue: Fees or other income retained by a protocol or its treasury after distributions.

Bad debt: Debt that cannot be fully recovered from available collateral and reserves.

Review Questions

Short Answer Questions

  1. What distinguishes a DeFi protocol from a conventional financial intermediary?
  2. Define composability and explain one benefit and one risk.
  3. What is the difference between TVL and protocol revenue?
  4. Why are many DeFi loans overcollateralised?
  5. What function does an oracle perform?

Long Answer Questions

  1. Explain the major layers and participants in a DeFi protocol architecture.
  2. Discuss how constant-product AMMs determine trading outcomes and expose LPs to risk.
  3. Explain APY, including the assumptions required for a compounding calculation.
  4. Analyse the role of governance in balancing upgradeability and immutability.
  5. Evaluate the technical, market, and ethical risks of permissionless lending.

Analytical / Application Questions

  1. A borrower deposits collateral worth $15,000 and borrows $9,000. Calculate the LTV and determine whether the position exceeds a 70% liquidation threshold, ignoring interest and fees.
  2. A protocol records $8 million in trading volume at a 0.25% fee. If 75% is distributed to LPs, calculate gross fees and the amount retained before operating costs.
  3. Design a risk map for a composable lending application that depends on an AMM, an oracle, a bridge, keepers, and token-based governance. Identify at least one failure mode and mitigation for each dependency.

Multiple Choice Questions with Answers

Question 1

Which participant most directly supplies external asset-price information to a DeFi smart contract?

A. Oracle

B. Validator

C. Liquidity provider

D. Governance voter

Correct Answer: A. Oracle

Question 2

A protocol has collateral worth $12,000 and debt worth $8,000. What is the LTV?

A. 50%

B. 66.67%

C. 75%

D. 150%

Correct Answer: B. 66.67%

Question 3

What is a principal benefit of atomic composability?

A. It guarantees that all protocols are secure

B. It permits related operations to succeed or revert as one transaction

C. It removes the need for blockchain validators

D. It prevents all price volatility

Correct Answer: B. It permits related operations to succeed or revert as one transaction

Question 4

Which statement about TVL is most accurate?

A. It is always equal to protocol profit

B. It measures only governance-token ownership

C. It estimates the market value of selected assets locked in a protocol

D. It guarantees that a protocol is secure

Correct Answer: C. It estimates the market value of selected assets locked in a protocol

Question 5

In a constant-product AMM, the idealised invariant is:

A. x + y = k

B. x − y = k

C. x ÷ y = k

D. x × y = k

Correct Answer: D. x × y = k

Question 6

A nominal annual rate of 12% compounded monthly has an APY closest to:

A. 10.00%

B. 12.00%

C. 12.68%

D. 24.00%

Correct Answer: C. 12.68%

Question 7

What is a keeper typically responsible for?

A. Issuing legal licences

B. Triggering eligible automated protocol operations

C. Holding every user’s private key

D. Setting the market price of every asset

Correct Answer: B. Triggering eligible automated protocol operations

Question 8

If gross trading fees are $20,000 and 80% is paid to liquidity providers, how much is retained before other costs?

A. $4,000

B. $8,000

C. $16,000

D. $20,800

Correct Answer: A. $4,000

Question 9

Why can composability create systemic risk?

A. Protocols cannot call one another

B. A failure in one dependency can propagate through dependent applications

C. It eliminates all external data

D. It prevents liquidity providers from earning fees

Correct Answer: B. A failure in one dependency can propagate through dependent applications

Question 10

If debt is $6,000 and liquidation occurs at 75% LTV, what collateral value is the threshold, ignoring debt growth?

A. $4,500

B. $6,000

C. $7,500

D. $8,000

Correct Answer: D. $8,000

Web3, DeFi & Blockchain Applications
Chapter 7 of 15