Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 41 ยท Using Blockchains in Practice

DeFi, DAOs and Governance

Understand decentralized finance: lending with collateral, automated market makers and the constant-product formula, DAO voting and the risks, with runnable code.

Decentralized finance, or DeFi, rebuilds financial services such as trading, lending and saving as smart contracts. Instead of a bank or an exchange holding your money and deciding the rules, a program on a blockchain holds the assets and applies the same rules to everyone. Anyone with a wallet can use it, and anyone can read its code.

A DAO (decentralized autonomous organization) applies the same idea to decision-making: members hold tokens and vote on proposals, and the result is carried out by code. In this lesson you will simulate the three pieces that matter most: an automated market maker, an over-collateralized loan and token voting. These are simplified models in Python, written to show the mechanics. Real protocols add many more safeguards.

Why on-chain finance works differently

A traditional exchange keeps an order book: buyers list the prices they will pay, sellers list the prices they ask, and a matching engine pairs them. That needs fast, cheap updates, which blocks with a few seconds of delay and a fee per operation cannot provide.

DeFi found a different design. Instead of matching people, you trade against a pool of two assets that a formula keeps in balance. Liquidity providers deposit assets into the pool and earn a share of fees. Traders swap with the pool at any moment, with no counterparty to wait for.

flowchart LR
  LP["Liquidity providers"] -->|"deposit both tokens"| Pool["Pool<br/>x of token A, y of token B"]
  Trader["Trader"] -->|"swap A for B"| Pool
  Pool -->|"fees stay in the pool"| LP

Liquidity providers fund the pool; traders swap against it, and the fees go to the providers.

Automated market makers and the constant-product formula

The most famous design is the constant-product market maker. The pool holds x units of token A and y units of token B, and a swap must keep the product unchanged:

x * y = k

If a trader adds dx of token A, the pool must give out dy of token B so that (x + dx) * (y - dy) = k. Solving for dy gives:

dy = y - k / (x + dx) = y * dx / (x + dx)

The price is simply the ratio of the reserves, y / x. Every trade moves the ratio, so large trades move the price a lot. Real pools take a small fee (for example 0.3 percent) from the input amount before the formula is applied, so the product k slowly grows.

Python A constant-product pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Before the swap, one A was worth 2 B, but the trader got a little less than 2 B per A. That difference is the price impact (also called slippage), and it grows quickly with trade size.

Python Price impact grows with the trade size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The curve explains two important facts. First, the pool never runs out: the price of the scarce token keeps rising as it empties. Second, big pools have small price impact, which is why liquidity is the most valuable resource of an AMM.

Arbitrage keeps prices honest

The pool does not look at the outside world. If another market says token A is worth 3 B but the pool says 2 B, someone can buy A from the pool cheaply and sell it elsewhere. Each such arbitrage trade moves the pool price toward the outside price until the profit disappears. Arbitrageurs are what makes pools track real prices, and their profit is paid by liquidity providers, a cost known as impermanent loss.

Python Arbitrage moves the pool to the market price

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fees earned by the pool are meant to compensate for this loss. Whether a pool is profitable for its providers depends on the trading volume versus the price movement.

Lending with collateral

Blockchain lenders do not know who you are, so they cannot chase you for repayment. They use over-collateralization instead: to borrow 100 dollars of one token, you lock, say, 150 dollars of another. A collateral ratio below a threshold triggers liquidation: anyone may repay part of the debt and take the collateral at a discount. Code, not a collections department, enforces the loan.

Python A collateralized loan and a liquidation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The weak point is the price. The loan contract needs to know what the collateral is worth right now, which is a job for an oracle (dApps, Oracles and Wallet Integration). If the price source can be manipulated, for example by a pool with little liquidity, an attacker can fake a crash or a rally and profit. This is one of the most common causes of DeFi losses.

DAOs and governance

Protocols need to change: fees are adjusted, assets are added, bugs are fixed. In a DAO, the people who decide are the holders of a governance token. A typical process looks like this:

  1. Someone submits a proposal: an on-chain action (such as "set fee to 0.25 percent").
  2. A voting period opens. Holders vote with their token balance, usually measured at a snapshot block so that tokens cannot be borrowed or moved just to vote twice.
  3. If the quorum (a minimum amount of participation) is met and the majority approves, the proposal passes.
  4. After a timelock delay, which gives users time to exit if they dislike the decision, the contract executes the action.
Python Token-weighted voting with a quorum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the whale alone is enough to pass a proposal when turnout is low. That is the central weakness of one-token-one-vote: money equals power. Designs to reduce this include quadratic voting (the weight is the square root of the balance), delegation to experts, and time-locked voting tokens. They help, but they also add complexity and can be gamed with many wallets (a Sybil attack, see The Double-Spend Problem and Byzantine Faults).

Risks to keep in mind

  • Smart contract bugs. A single flaw can drain a pool. Audits reduce but never remove this risk (Smart Contract Security Pitfalls).
  • Oracle and price manipulation. Protocols that trust one thin price source are easy targets.
  • Flash loans. A loan that must be borrowed and repaid in a single transaction needs no collateral. It is a legitimate tool, but attackers use it to get huge temporary capital for manipulation.
  • Governance capture. Whales, or an attacker who borrows enough tokens, can pass harmful proposals.
  • Front-running (MEV). Block builders and bots can see pending trades and place their own before yours.
  • Impermanent loss and leverage. Liquidity providing and borrowing both carry losses that beginners often underestimate.
  • Regulation. Rules for lending, securities and money transmission still apply in many countries.

This lesson is about how the machinery works, not financial advice. Real money in DeFi can be lost to bugs, hacks and market swings, and there is usually no bank or insurer to reverse it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a constant-product pool with reserves x and y, what must a swap preserve (ignoring fees)?

    The invariant is x * y = k. When the trader adds some of token A, the pool releases just enough of token B to keep the product at k.
  2. 2. Why does selling a very large amount to a small pool give a poor average price?

    The price is the reserve ratio. A larger trade moves the ratio further, and the trade is priced along the curve, not at the starting spot price.
  3. 3. What is the role of arbitrageurs in an AMM?

    The pool has no view of external prices. Arbitrageurs exploit differences, and in doing so they update the pool price. Their profit is a cost for liquidity providers.
  4. 4. Why are DeFi loans usually over-collateralized?

    Without identity, collateral is the only protection for the lender. If the collateral value falls too low, liquidation covers the debt.
  5. 5. What is a main weakness of one-token-one-vote governance?

    Voting power follows money. Quorums, delegation, quadratic voting and timelocks reduce but do not remove this concentration risk.

Summary

  • DeFi replaces intermediaries with smart contracts that hold assets and apply public rules.
  • A constant-product AMM keeps x * y = k; the price is the reserve ratio, and bigger trades suffer larger price impact.
  • Arbitrage aligns pool prices with the market, at the expense of liquidity providers (impermanent loss).
  • Lending uses over-collateralization and liquidation, and depends on trustworthy price data.
  • DAOs govern protocols with token voting: snapshot, quorum, majority, timelock. Whale dominance is the main weakness.
  • Main risks: contract bugs, oracle manipulation, flash loans, governance capture, MEV and regulation.

Next: Enterprise and Real-World Use Cases, where we ask when a blockchain is the right tool at all.