Ethereum & Solidity

Chapter 12
DeFi, DAOs and Protocol Engineering

Diploma in Blockchain
Ethereum & Solidity   •   Diploma

DeFi, DAOs and Protocol Engineering

Introduction

Decentralised finance (DeFi) is a collection of blockchain-based financial protocols that provide exchange, lending, borrowing, payments, asset issuance, derivatives and savings without relying on a conventional central intermediary. Ethereum is especially important because Solidity smart contracts can encode financial rules that execute automatically and can be composed with other contracts.

DeFi changes the engineering problem from building a single application to designing an open, adversarial and composable economic system. A protocol must therefore address both software correctness and incentive compatibility. A mathematically correct contract may still fail if its oracle is manipulable, its governance can be captured, or its incentives encourage excessive leverage.

A decentralised autonomous organisation (DAO) extends this model by allowing token holders or other authorised participants to propose and approve changes, allocate treasury assets and manage protocol parameters. DAOs do not eliminate governance; they make governance an explicit technical and economic process.

Learning Objectives

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

  • explain automated market makers, liquidity pools and constant-product pricing;
  • compare lending, stablecoin, staking and flash-loan protocols;
  • analyse composability, leverage and systemic risk;
  • describe DAO proposals, voting mechanisms and treasury management;
  • evaluate governance attacks, oracle risks and protocol incentives;
  • apply a structured framework for designing safer and more sustainable protocols.

1. DeFi as Protocol Engineering

A DeFi protocol normally contains five interacting layers:

  1. Assets: native tokens, ERC-20 tokens, stablecoins, wrapped assets and liquid staking tokens.
  2. State and accounting: balances, collateral, debt, shares, reserves and accrued interest.
  3. Execution logic: Solidity functions that enforce transfers, swaps, liquidation or governance decisions.
  4. Information inputs: prices and other data obtained from on-chain or off-chain oracles.
  5. Governance and incentives: rules determining upgrades, fees, rewards and emergency intervention.

The protocol’s state is public, but public visibility does not guarantee safety. Attackers can inspect pending transactions, simulate state transitions and borrow capital temporarily. Consequently, engineers must assume that users are strategic, transactions may be reordered, and liquidity may disappear during stress.

A useful design principle is minimise trusted assumptions. If a protocol depends on an administrator, multisignature wallet, price oracle, bridge or upgrade proxy, that dependency should be documented, monitored and governed.

2. Automated Market Makers

2.1 From order books to liquidity curves

A traditional exchange matches buyers and sellers through an order book. An automated market maker (AMM) instead holds reserves in a smart-contract pool and calculates a price from a mathematical invariant. Liquidity providers deposit assets and receive a claim on pool assets plus a share of trading fees.

For a two-token constant-product pool, let x be the reserve of token X and y the reserve of token Y. The invariant is:

x × y = k

Here, k is the product of reserves. Ignoring fees, a trade that changes reserves from (x, y) to (x + Δx, y − Δy) must satisfy:

(x + Δx)(y − Δy) = xy

Solving for the output amount gives:

Δy = y − (xy)/(x + Δx) = (y × Δx)/(x + Δx)

The formula assumes a two-asset pool, no fee, no rounding error and no concurrent state change. Token units must be handled consistently; decimals do not change the economic relationship but do affect Solidity arithmetic and scaling.

The marginal price of X measured in Y is approximately:

PX = y/x

This is a local price, not the average price of a large trade. As Δx becomes large relative to x, the trader receives progressively less output per unit. This effect is called price impact or slippage.

If a fee f is charged on the input, where 0 ≤ f < 1, the effective input is Δx(1 − f). A common implementation therefore calculates:

Δy = [y × Δx(1 − f)]/[x + Δx(1 − f)]

The precise formula depends on the protocol’s fee accounting and rounding rules.

2.2 Worked AMM example

Suppose a pool contains 1,000 X and 2,000 Y. A trader supplies 100 X and the fee is ignored for simplicity. The output is:

Δy = (2,000 × 100)/(1,000 + 100) = 181.818 Y

The trader receives approximately 181.818 Y. The post-trade reserves are 1,100 X and 1,818.182 Y. Their product remains approximately 2,000,000, subject to rounding.

The initial marginal price is 2 Y per X. The average execution price is approximately 1.818 Y per X, demonstrating price impact.

2.3 Liquidity-provider returns and impermanent loss

A liquidity provider owns a fraction of the pool. Fees can produce income, but the provider’s asset mix changes as traders rebalance the pool. If the external price changes substantially, the value of holding pool assets may be lower than simply holding the original assets. This difference is commonly called impermanent loss, although it becomes permanent when liquidity is withdrawn at the changed price.

For a constant-product pool, if the relative price changes by a factor r, the value ratio of the liquidity position to passive holding, under idealised assumptions and excluding fees, is:

VLP/Vhold = 2√r/(1 + r)

Here r is the new price divided by the original price. The expression assumes equal-value initial deposits, a frictionless constant-product pool and no additional deposits or withdrawals. It is not a complete return model because fees, gas, rewards and changing liquidity must also be considered.

2.4 AMM design variants

Different AMMs use different curves. Stable-asset pools generally use a curve that permits lower slippage near equal prices. Weighted pools permit portfolios with weights other than 50:50. Concentrated-liquidity systems allow providers to select price ranges, increasing capital efficiency but requiring active management and creating greater out-of-range risk.

Important engineering concerns include reentrancy, fee-on-transfer tokens, token decimals, minimum-output checks, deadline parameters, sandwich attacks and oracle manipulation. A user should normally specify a minimum acceptable output rather than accepting any amount calculated from a stale transaction assumption.

3. Lending and Borrowing Protocols

A lending protocol aggregates supplied assets and permits overcollateralised borrowing. Suppliers receive a claim representing their share of the pool; borrowers lock collateral and draw another asset.

Let C be the market value of collateral, D the value of debt and L the maximum loan-to-value ratio. Borrowing is permitted only when:

D/C ≤ L

Equivalently, the maximum debt is:

Dmax = L × C

The condition assumes reliable asset valuations and a defined collateral factor. In practice, protocols use a liquidation threshold, which may be lower than or equal to the maximum borrowing threshold. If the debt exceeds the liquidation threshold after a price decline, a liquidator may repay part of the debt and receive collateral at a discount.

Interest rates commonly respond to pool utilisation. If U is utilisation, B is total borrowed liquidity and S is supplied liquidity, then:

U = B/S

A piecewise rate model may use a low slope below a kink utilisation U*, and a steeper slope above it. This encourages repayment or new supply when liquidity becomes scarce. The exact model is protocol-specific; there is no universal interest-rate formula.

Lending risks

Major risks include collateral price volatility, oracle failure, bad debt, correlated collateral, liquidation congestion, governance changes and smart-contract bugs. A protocol may be solvent under ordinary prices but fail during a rapid market decline when liquidators cannot execute, stablecoins depeg or blockspace becomes expensive.

Risk parameters should therefore be asset-specific. Volatile, thinly traded or correlated assets generally require conservative collateral factors, supply caps and debt ceilings.

4. Stablecoins

A stablecoin attempts to maintain a target value, commonly one unit of a fiat currency. Three broad models are important:

ModelMain backing or mechanismPrincipal risks
Fiat-backedBank deposits or short-term securitiesCustodian, legal and redemption risk
Crypto-collateralisedExcess on-chain collateralLiquidation, oracle and depeg risk
Algorithmic or hybridSupply adjustment, incentives and partial collateralReflexivity, governance and confidence risk

A collateralisation ratio is:

CR = Vcollateral/Vstablecoinsissued

A ratio above 100% indicates overcollateralisation, but the amount of safety depends on collateral volatility, liquidation speed and liquidity. If collateral value falls rapidly, a nominally safe ratio can become insufficient before liquidation occurs.

Stablecoin design must address redemption, reserve transparency, oracle integrity, governance authority and emergency procedures. A stablecoin is not automatically risk-free merely because its price has historically remained near its target.

5. Staking and Liquid Staking

In proof-of-stake systems, validators lock capital and perform consensus duties. Correct behaviour earns rewards; misconduct or failure may result in penalties or slashing. The economic objective is to make dishonest behaviour less attractive than following the protocol.

Liquid staking protocols issue a token representing a claim on staked assets and accumulated rewards. This improves capital efficiency because the receipt token can be used elsewhere, but it also creates additional smart-contract, liquidity, validator and composability risks. If many applications treat the liquid token as equivalent to the underlying asset, a loss of confidence can spread quickly.

Protocol designers should distinguish nominal staking yield from net return. A simplified net return relationship is:

Rnet ≈ Rreward − Rinflation − Rfees − Rexpectedloss

The terms must be expressed over the same period. This is an analytical approximation, not an accounting identity; price changes and compounding may materially alter realised returns.

6. Flash Loans and Composability

A flash loan permits borrowing without conventional collateral provided that the loan, fee and required state conditions are repaid within one transaction. If repayment fails, the transaction reverts atomically.

Flash loans have legitimate uses, including arbitrage, collateral refinancing and liquidation. They also allow attackers to obtain temporary purchasing power for oracle manipulation, governance influence or exploit execution. The key lesson is that “no capital at the beginning of the transaction” does not mean “no economic power.”

Composability means that one protocol can call another and use its tokens or data. It enables rapid innovation: a user may deposit collateral, borrow a stablecoin, swap it, provide liquidity and stake the receipt token in one transaction. However, each dependency adds failure modes. A protocol’s effective risk is often the risk of its dependency graph, not merely its own source code.

Engineers should maintain an inventory of external calls, token assumptions, oracle sources and governance dependencies. Circuit breakers, exposure limits and graceful degradation can reduce contagion.

7. DAO Governance

A DAO requires rules for proposal creation, eligibility, voting, quorum, execution and emergency action. A typical lifecycle is:

  1. discussion and specification;
  2. temperature check or signalling vote;
  3. formal on-chain proposal;
  4. voting period;
  5. timelock;
  6. execution by a governance executor or multisignature authority;
  7. monitoring and post-implementation review.

Governance power may be token-weighted, delegated, quadratic, reputation-based or bicameral. Token-weighted voting is simple and transparent but can produce plutocracy, vote buying and low participation. Quadratic voting reduces the influence of large holdings in theory, but Sybil resistance becomes essential because a participant could split identity across many addresses.

A basic token-weighted support ratio is:

Support = votesfor/(votesfor + votesagainst)

Quorum is commonly defined as:

Quorum = votescast/eligiblevotingpower

These ratios describe a vote but do not determine passage unless the DAO’s rules specify thresholds, abstention treatment, delegation and quorum requirements.

Governance attacks

Important attacks include:

  • Flash-loan voting: temporary borrowed tokens are used to influence a vote if voting power is measured at the proposal or execution block.
  • Vote buying: economic benefits are offered to voters or delegates.
  • Delegation capture: a small number of delegates control effective voting power.
  • Proposal hijacking: malicious code is hidden in an apparently beneficial proposal.
  • Quorum manipulation: abstention or voter apathy allows a minority to pass a decision.
  • Timelock bypass: privileged roles execute changes without the promised delay.

Mitigations include snapshot voting based on historical balances, vote-locking, proposal deposits, quorum rules, timelocks, guardian limits, code review, simulation and explicit separation of proposal, voting and execution powers. Each mitigation has costs: long timelocks reduce responsiveness, while emergency guardians introduce trust.

8. Treasury Management and Protocol Incentives

A DAO treasury may hold native tokens, stablecoins, governance tokens, liquidity positions and claims on future revenue. Sound treasury management begins with a written mandate: objectives, permitted assets, liquidity requirements, risk limits, authority and reporting frequency.

A treasury should distinguish operating liquidity from long-term reserves. Concentrating the treasury in the protocol’s own volatile token can create a reflexive failure: falling token price reduces treasury value, which weakens incentives and confidence, causing further selling.

Protocols commonly distribute token rewards to attract liquidity. This can generate a positive bootstrapping effect, but it may also create mercenary capital that leaves when rewards decline. Sustainable incentives should be connected to measurable protocol value, such as useful liquidity, reliable borrowing capacity, fee generation or security participation.

A simplified net protocol value measure over a period is:

Net value = fees and other revenue − security costs − incentives − operating costs

This is useful for analysis but does not capture token-price expectations, indirect benefits or future liabilities. Emissions should be evaluated for dilution, concentration, sell pressure and governance consequences.

9. Systemic Risk and Sustainable Mechanism Design

Systemic risk arises when failures propagate through interconnected protocols. Common transmission channels include:

  • shared collateral, especially a liquid staking token;
  • common price oracles;
  • stablecoin dependence;
  • rehypothecation of liquidity-provider tokens;
  • leverage and recursive borrowing;
  • common governance or upgrade authorities;
  • bridges and cross-chain messaging.

A useful risk framework asks five questions:

  1. What can fail technically?
  2. What can be manipulated economically?
  3. Which parties bear losses?
  4. How quickly can the system respond?
  5. What happens when several assumptions fail simultaneously?

Mechanism design seeks rules under which desired behaviour is privately rational. This requires identifying participants, information asymmetries, payoffs, constraints and credible penalties. No incentive is sustainable if rewards exceed the value created or if participants can cheaply exploit measurement weaknesses.

Sustainable protocols generally use conservative initial parameters, staged launches, bounded exposure, transparent accounting, independent audits, bug bounties, monitoring, governance timelocks and tested emergency procedures. Audits reduce defects but do not prove economic safety.

10. Solidity and Protocol-Safety Practices

Solidity developers should apply the checks-effects-interactions pattern, use reentrancy protections where appropriate, validate token return behaviour, avoid unsafe assumptions about ERC-20 implementations and use safe arithmetic and access control. Upgradeable contracts require special attention to storage layout, initialisation and admin keys.

Critical functions should be tested with unit tests, integration tests, invariant tests and fuzzing. An invariant is a property that should remain true across valid state transitions, such as “total shares correspond to accounted assets” or “a borrower cannot withdraw collateral while remaining below the required health factor.”

Operational controls are equally important:

  • publish contract addresses and privileged roles;
  • verify deployment bytecode;
  • monitor abnormal transfers and oracle changes;
  • simulate governance proposals before execution;
  • use multisignature administration;
  • document incident-response authority;
  • communicate risks rather than presenting yield as guaranteed.

Applied Case: Illustrative Stablecoin-Lending DAO

Background

Consider an illustrative DAO named Harbor, which issues a crypto-collateralised stablecoin HUSD. Users deposit ETH and liquid staking tokens, then borrow HUSD. HUSD can be exchanged in an AMM and deposited in a lending market.

Problem

The DAO proposes adding a thinly traded governance token as collateral because its market value has risen. The proposal also increases the collateral factor to attract borrowers. A large holder supports the proposal using delegated voting power, and the governance timelock is only two hours.

Analysis

The proposal creates several correlated risks. The governance token has shallow liquidity, so its oracle price can be moved. A high collateral factor permits substantial borrowing against a volatile asset. HUSD liquidity is concentrated in one AMM, and the same governance token is used as a reward asset. If the token price falls, borrowers may default, liquidators may receive an illiquid asset, and HUSD may trade below its target. The short timelock leaves little opportunity for review.

Approach and solution

A safer design would introduce a conservative collateral factor, a supply cap and a debt ceiling. It would require a robust time-weighted price oracle with deviation checks and a minimum liquidity condition. The proposal should undergo a public risk assessment, simulation and a longer timelock. Governance power should be measured using a historical snapshot, and emergency pause powers should be narrowly defined and transparently assigned.

The DAO should also stress-test a rapid 50% collateral-price decline, high gas costs, unavailable liquidators and an AMM liquidity reduction. Treasury reserves should include liquid assets rather than only the governance token.

Outcome

Under this revised approach, growth is slower, but the protocol’s maximum exposure is bounded. A later review can increase limits if the asset demonstrates sustained liquidity, reliable pricing and diversified demand.

Learning points

The case demonstrates that collateral choice, oracle design, governance, liquidity and treasury policy cannot be evaluated independently. Protocol engineering is a systems discipline.

Ethical, Legal and Regulatory Considerations

DeFi systems can expand access, but they can also expose inexperienced users to complex losses, opaque governance and misleading yield claims. Designers should provide accurate risk disclosures, avoid manipulative interface design and distinguish educational information from financial advice.

Legal treatment varies by jurisdiction and may depend on the asset, service, governance structure, custody model and economic function. Decentralisation is not a universal legal exemption. Teams should obtain appropriate legal advice, maintain records and design compliance controls where applicable. Privacy also requires attention: public transactions can reveal financial relationships even when addresses are pseudonymous.

Contemporary Developments

Current protocol engineering increasingly focuses on intent-based execution, account abstraction, restaking, modular blockchains, real-world assets, zero-knowledge systems and cross-chain interoperability. These developments may improve usability and capital efficiency, but they also introduce new trust assumptions, sequencer risks, legal questions and dependency chains. The correct evaluation is not whether a technology is innovative, but whether its additional complexity creates value greater than its additional risk.

Chapter Summary

DeFi protocols combine smart contracts, economic incentives, liquidity and governance. AMMs replace order books with pricing curves; the constant-product model explains reserve updates and price impact. Lending systems depend on collateral ratios, interest-rate models, reliable oracles and effective liquidation. Stablecoins require credible backing and redemption mechanisms, while staking and liquid staking trade security participation for capital efficiency and additional dependency risk.

Flash loans demonstrate the power of atomic composability and the need to defend against temporary capital-based manipulation. DAOs formalise proposal, voting, timelock and execution processes, but remain vulnerable to concentration, vote buying, flash-loan voting and governance capture. Treasury policy and token incentives must be assessed for sustainability rather than short-term growth.

The central engineering lesson is that security includes code, economics, governance and operations. Conservative parameters, bounded exposure, transparent assumptions, testing, monitoring and credible emergency processes are essential to responsible protocol design.

Key Terms

AMM: A protocol that prices trades algorithmically from liquidity-pool reserves.

Automated market maker: Another term for an AMM-based exchange mechanism.

Constant-product invariant: The relationship x × y = k used by a common two-asset AMM.

Slippage: The difference between an expected trade price and the executed price.

Impermanent loss: Underperformance of a liquidity position relative to holding assets, under specified assumptions.

Liquidity provider: A participant who deposits assets into a trading pool.

Collateral factor: The maximum permitted borrowing value relative to collateral value.

Liquidation threshold: A risk boundary beyond which collateral may be liquidated.

Oracle: A mechanism that supplies external or derived data to a smart contract.

Stablecoin: A token designed to maintain a target value.

Staking: Locking assets to support proof-of-stake consensus.

Liquid staking token: A transferable token representing a claim on staked assets.

Flash loan: An atomic loan that must be repaid within the same transaction.

Composability: The ability of protocols and contracts to interact as building blocks.

DAO: A blockchain-based organisation governed through encoded rules and collective decision-making.

Quorum: The minimum participation required for a governance decision.

Timelock: A delay between approval and execution of a governance action.

Governance attack: An attempt to gain or exploit decision-making power for harmful purposes.

Systemic risk: The possibility that one failure propagates through interconnected protocols.

Mechanism design: The design of rules and incentives to produce desired participant behaviour.

Review Questions

Short Answer Questions

  1. What is the constant-product invariant in a two-token AMM?
  2. Why does a large AMM trade normally experience greater price impact?
  3. What is the purpose of a liquidation threshold in a lending protocol?
  4. How does a flash loan differ from a conventional collateralised loan?
  5. What function does a governance timelock serve?

Long Answer Questions

  1. Explain how an AMM operates, derive its output formula and discuss its principal risks.
  2. Compare fiat-backed, crypto-collateralised and algorithmic stablecoins.
  3. Analyse the relationship between staking, liquid staking and systemic risk.
  4. Explain how DAO voting can be attacked and evaluate appropriate mitigations.
  5. Discuss why token emissions may bootstrap liquidity but fail to create sustainable protocol value.

Analytical / Application Questions

  1. A pool contains 5,000 units of X and 10,000 units of Y. Ignoring fees, calculate the Y output for a trade of 500 X and explain the price impact.
  2. Design risk parameters for a lending market accepting a volatile governance token as collateral. Justify your collateral factor, oracle requirements, supply cap and liquidation approach.
  3. Evaluate the Harbor case as a systems-risk problem. Identify at least four connected failure channels and propose a governance process for approving the revised design.

Multiple Choice Questions with Answers

Question 1

In a fee-free constant-product AMM with reserves x and y, which expression gives the output Δy for an input Δx of token X?

A. Δy = x + y + Δx

B. Δy = (y × Δx)/(x + Δx)

C. Δy = (x × Δx)/(y + Δx)

D. Δy = x × y × Δx

Correct Answer: B. Δy = (y × Δx)/(x + Δx)

Question 2

A lending protocol has collateral worth 200 units and a maximum loan-to-value ratio of 60%. What is the maximum debt under the stated rule?

A. 80 units

B. 120 units

C. 140 units

D. 333.33 units

Correct Answer: B. 120 units

Question 3

Which feature most directly limits the damage caused by a malicious approved DAO proposal before execution?

A. A governance timelock

B. A higher AMM fee

C. A larger token supply

D. A lower block gas limit

Correct Answer: A. A governance timelock

Question 4

What is the principal requirement of a flash loan?

A. The borrower must lock collateral for seven days

B. The loan must be repaid, including its fee, within the transaction

C. The borrower must be a DAO delegate

D. The loan can only be used to buy stablecoins

Correct Answer: B. The loan must be repaid, including its fee, within the transaction

Question 5

If a pool begins with 1,000 X and 2,000 Y and receives 100 X in a fee-free constant-product trade, approximately how much Y is paid out?

A. 100 Y

B. 181.82 Y

C. 200 Y

D. 220 Y

Correct Answer: B. 181.82 Y

Question 6

Which statement best describes impermanent loss?

A. A permanent loss caused only by smart-contract compilation

B. The difference between a liquidity position and passive holding under changing prices

C. A guaranteed fee charged to every liquidity provider

D. The loss of governance rights after delegation

Correct Answer: B. The difference between a liquidity position and passive holding under changing prices

Question 7

Why can a liquid staking token create systemic risk?

A. It cannot be transferred between contracts

B. It introduces dependencies involving validators, its smart contract, liquidity and applications using it as collateral

C. It always has zero market value

D. It prevents users from earning staking rewards

Correct Answer: B. It introduces dependencies involving validators, its smart contract, liquidity and applications using it as collateral

Question 8

What does governance quorum measure?

A. The number of smart contracts deployed by the DAO

B. The proportion of eligible voting power participating in a vote

C. The market capitalisation of the treasury

D. The number of transactions in an AMM pool

Correct Answer: B. The proportion of eligible voting power participating in a vote

Question 9

Which design choice most directly reduces flash-loan voting risk?

A. Measuring voting power from a historical snapshot

B. Removing all proposal discussions

C. Increasing token transfer speed

D. Using a thinner liquidity pool

Correct Answer: A. Measuring voting power from a historical snapshot

Question 10

Which is the strongest reason to avoid concentrating a DAO treasury entirely in its own volatile governance token?

A. It eliminates all voting rights

B. It can create reflexive losses when a falling token price weakens both treasury capacity and confidence

C. It makes accounting impossible in every jurisdiction

D. It guarantees that staking rewards are zero

Correct Answer: B. It can create reflexive losses when a falling token price weakens both treasury capacity and confidence

Ethereum & Solidity
Chapter 12 of 15