# Replacing the Banker with a Function
## A Mathematician's Guide to Decentralized Finance
Shen-Ning Tung, National Tsing-Hua University
<style>.reveal {font-size: 28px;}</style>
---
## I. The Global Picture — Architecture & Vision
> Trust is not a leap of faith; it is the deterministic output of a distributed state machine.
---
### Defining the Transformation: Fintech vs. DeFi
Before we dive into the math, we must distinguish between "digitalizing" a bank and "rebuilding" finance.
* **Fintech (Digitized TradFi)**: Centralized institutions using modern tech stacks. You have an app, but the bank still holds the *"Master Ledger"* and the *"Kill Switch."*
* **DeFi (Decentralized Finance)**: A peer-to-peer ecosystem where *Smart Contracts* act as the custodian and clearinghouse.
* **The Paradigm Shift**: Moving from *Subjective Trust* (Law/Reputation) to *Objective Truth* (Cryptographic Proofs).
---

[What is DeFi (Decentralized Finance)?](https://whiteboardcrypto.com/defi-decentralized-finance/)
[DeFi Beyond the Hype](https://wifpr.wharton.upenn.edu/wp-content/uploads/2021/05/DeFi-Beyond-the-Hype.pdf)
[The Cambridge Centre for Alternative Finance](https://ccaf.io/defi/ecosystem-map/visualisation/graph)
---
### The Blockchain as a Global State Machine
For a mathematician, a blockchain is simply a distributed, deterministic transition system.
* **The State ($S$)**: A snapshot of all balances and contract data at time $t$.
* **The Transition Function ($f$)**: The rules of the protocol (the code).
* **The Formula**: $S_{t+1} = f(S_t, \Delta)$
* $\Delta$ represents a block of transactions.
* Integrity is maintained because thousands of nodes must compute the same $S_{t+1}$ and reach consensus.
---

[What is a Blockchain?](https://whiteboardcrypto.com/what-is-a-blockchain/)
[The tl;dr of Blockchains/Web3](https://youtube.com/playlist?list=PLEGCF-WLh2RKVT7xUwu0dCBGo3KH51XlS&si=6qBfs6aO3heUmU01)
[Dan Boneh: Blockchain Primitives: Cryptography and Consensus](https://youtu.be/7Cu8KQmUhu0?si=YQnixg-Z6kg9Xd8i)
---
### The Engine of DeFi: Ethereum & The EVM
<div style="font-size: 32px;">
To turn a ledger into a financial system, we need a Universal Computer capable of executing arbitrary logic.
* **Smart Contracts**: Self-executing programs where the terms of the agreement are written directly into lines of code. They are autonomous (no middleman) and *immutable* (cannot be changed once deployed).
* **The Ethereum Virtual Machine (EVM)**: A global, decentralized CPU. It ensures that every node in the network executes the same code and arrives at the same result—guaranteeing *mathematical determinism*.
* **Gas & Halting Problem**: To prevent infinite loops in a Turing-complete system, every operation costs "Gas." This serves as a resource allocation mechanism and a formal constraint on computation.
</div>
---

[Ethereum & Bitcoin Transaction Visualizer](https://txcity.io/v/eth-btc)
[What is Ethereum?](https://ethereum.org/en/what-is-ethereum/)
[What Are Smart Contracts and How Do They Work?](https://chain.link/education/smart-contracts)
---
### Oracles: The Bridge to Reality
A closed mathematical system cannot natively "know" the price of Gold or the outcome of a game.
* **The Oracle Problem**: How do we bring external data into a deterministic system without introducing a single point of failure?
* **Decentralized Oracles**: Systems like *Chainlink* use a committee of nodes to provide a "consensus" data feed.
* **Application**: This allows a smart contract to trigger a *liquidation* or a payout based on real-world events (e.g., $ETH$ price dropping below $1800$).
---

[What Is a Blockchain Oracle?](https://chain.link/education/blockchain-oracles)
[What Is Chainlink? A Beginner’s Guide](https://blog.chain.link/what-is-chainlink/)
---
### Summary: The Architecture of Integrity
| Feature | Traditional System | DeFi System |
| :--- | :--- | :--- |
| Enforcement | Legal Prose (Ambiguous) | Mathematical Code (Precise) |
| Custodian | Centralized Bank | Self-Custody / Smart Contract |
| Verification | Post-hoc Audits | Real-time Cryptographic Proofs |
| Interoperability | Siloed APIs | Open Composability ("Money Legos") |
<small>**The "Money Lego" Framework**: DeFi protocols are modular by design. Layer 1 provides settlement, tokens serve as raw materials, and lending/trading protocols act as building blocks. Developers "snap" these bricks together to create complex strategies without seeking institutional permission.</small>
---

[What is DeFi (Decentralized Finance)?](https://whiteboardcrypto.com/defi-decentralized-finance/)
[DeFi Beyond the Hype](https://wifpr.wharton.upenn.edu/wp-content/uploads/2021/05/DeFi-Beyond-the-Hype.pdf)
[The Cambridge Centre for Alternative Finance](https://ccaf.io/defi/ecosystem-map/visualisation/graph)
---
## II: Market Mechanics — How DeFi Works
> Liquidity is an invariant, and price is the slope of a curve defined by the balance of reserves.
---
### Beyond Order Books: Automated Market Makers (AMMs)
<div style="font-size: 28px;">
In traditional markets, a trade requires a counterparty (Buyer $\leftrightarrow$ Seller). In DeFi, you trade against a Liquidity Pool.
* **The Liquidity Pool**: A smart contract holding a pair of tokens (e.g., $X$ and $Y$).
* **The Mathematical Rule**: The pool uses a *Constant Product Invariant*: $$x \cdot y = k$$
* $x$: Quantity of Token A
* $y$: Quantity of Token B
* $k$: A constant that must be maintained during a trade.
* **The "Peer-to-Pool" Model**: Anyone can become a *"Liquidity Provider" (LP)* by depositing assets, earning a pro-rata share of trading fees.
</div>
---

[What Are Automated Market Makers (AMMs)?](https://chain.link/education-hub/what-is-an-automated-market-maker-amm)
[Mastering AMMs: Guide to Automated Market Makers](https://threesigma.xyz/blog/defi-automated-market-maker-guide)
[Mastering AMMs: Exploring Order Books and Intents](https://threesigma.xyz/blog/defi-automated-market-maker-guide)
---
### The Geometry of Price Discovery
<div style="font-size: 28px;">
Price is not "set" by an admin; it is a mathematical consequence of the reserve ratio.
* **The Marginal Price**: Defined as the negative slope of the curve at a specific point: $y = k/x$: $$P = \frac{dy}{dx} = -\frac{y}{x}$$
* **Slippage**: Because the curve is a hyperbola ($y = k/x$), every trade shifts the ratio $y/x$.
* *Infinitesimal trades*: Price remains near the spot $y/x$.
* *Large trades*: Significant displacement along the curve results in an exponential increase in the effective price.
* **Asymptotic Liquidity**: The pool can never be fully depleted of an asset; as quantity approaches zero, the price approaches infinity.
</div>
---
### Worked Example: Trading on the Curve
* **Initial State**: Pool holds *100 ETH* ($x$) and *200,000 USDC* ($y$).
* **The Invariant**: $k = 100 \times 200,000 = 20,000,000$.
* **The Spot Price**: $P = y/x = 2,000$ per ETH.
* **The Trade**: A trader wants to buy 10 ETH.
* *New ETH reserve ($x'$)*: $100 - 10 = 90$ ETH.
* *New USDC reserve ($y'$)*: $20,000,000 / 90 = 222,222.22$ USDC.
* **The Cost**: Trader must pay $222,222.22 - 200,000 = 22,222.22$.
* *Effective price*: \$2,222.22 per ETH.
* *Slippage*: $\approx 11.1\%$ slippage from the initial spot price.
---

[Uniswap University](https://uniswap.university/)
---
### Algorithmic Lending & Money Markets
Protocols like **Aave** replace loan officers with a *Utilization-based Interest Rate Model*.
* **The Utilization Rate ($U$)**: Measures the capital efficiency of the pool.$$U = \frac{\text{Total Borrows}}{\text{Total Liquidity}}$$
* **Equilibrium Logic**:
* *Low $U$*: Excess supply $\rightarrow$ Low interest rates to incentivize borrowing.
* *High $U$*: Scarcity $\rightarrow$ Sharp interest spikes to attract lenders and force debt repayment.
---
### The Kinked Interest Rate Model
The rate function $R(U)$ is a piecewise linear function centered around an *Optimal Utilization* ($U_{opt}$):
* **The "Healthy" Zone ($U < U_{opt}$)**: Rates rise gently to manage normal demand.$$R_t = R_0 + \left( \frac{U_t}{U_{opt}} \right) R_{slope1}$$
* **The "Emergency" Zone ($U \geq U_{opt}$)**: Rates spike aggressively to protect protocol liquidity.$$R_t = R_0 + R_{slope1} + \left( \frac{U_t - U_{opt}}{1 - U_{opt}} \right) R_{slope2}$$
* **The "Kink"**: $R_{slope2}$ is usually an order of magnitude higher than $slope1$ (e.g., jumping from $4\%$ to $100\%$). This acts as a mathematical "emergency brake" to prevent pool depletion.
---

[DeFi Money Markets 2024](https://threesigma.xyz/blog/defi-money-markets-2024-guide)
[Aave docs](https://aave.com/docs)
[Compound docs](https://docs.compound.finance/)
---
### Risk Management: Over-collateralization
In a pseudonymous system without legal recourse, all credit is secured by a *Collateral Invariant*.
* **The Collateralization Ratio ($CR$)**: $$CR = \frac{\sum (\text{Collateral Assets} \times \text{Price})}{\text{Total Debt Value}}$$
* **Loan-to-Value (LTV)**: The maximum leverage allowed (e.g., $LTV = 75\%$ implies a minimum $CR$ of $133\%$).
* **The Oracle Dependency**: The system's safety is strictly bound to the accuracy and latency of external price feeds.
---
### The Liquidation Function
The "fail-safe" mechanism that maintains system-wide solvency.
* **Trigger Condition**: If $CR < \text{Liquidation Threshold}$, the position is flagged as "under-collateralized."
* **The Forced Exit**: Automated "Liquidator" bots repay the debt in exchange for the collateral at a Liquidation Bonus (e.g., a $5\%-10\%$ discount).
* **Mathematical Solvency**: By liquidating before $CR < 100\%$, the protocol ensures that every dollar of debt is always backed by more than one dollar of market value.
---
### Liquidation Walkthrough: A "Hard Money" Event
1. **Open Position**: Deposit 1 ETH (\$2,000). Borrow 1,500 USDC ($LTV = 75\%$).
2. **Current State**: $CR = 2,000 / 1,500 = 133.3\%$ *(Healthy)*.
3. **Market Shock**: ETH price drops to *$1,700*.
4. **Breach**: $CR$ becomes $113.3\%$. If the threshold is $120\%$, the position is now *liquidatable*.
5. **Execution**: A bot detects the breach, repays the 1500 USDC, and claims the ETH at a discount.
**The result**: Debt is cleared by code, not by credit committees or bailouts. The math is the ultimate arbiter of solvency.
---

[What Are Stablecoins and How Do They Work?](https://www.gemini.com/cryptopedia/what-are-stablecoins-how-do-they-work)
[The Sky Protocol: Sky's Multi-Collateral Dai (MCD) System](https://makerdao.com/en/whitepaper/#introduction)
---
## III. Synthesis — Mechanism Design & The Future
> The bedrock of future finance is not the institution, but the formally verified proof.
---
### Mechanism Design: Engineering Rational Behavior
In a permissionless system, we cannot "ban" bad actors; we must make it mathematically unprofitable to be one.
* **Agent-Based Economics**: We model the protocol as a game where autonomous agents maximize their own utility.
* **Slashing & Incentives**:
* *Positive Incentives*: Yield and rewards for "honest" participation (following the protocol).
* *Negative Incentives*: Malicious behavior (e.g., double-spending or downtime) results in the automated forfeiture of "staked" capital (*Slashing*).
* **Sybil Resistance**: Requiring a "Proof of Stake"—an economic cost that makes it prohibitively expensive for a single actor to subvert the system via multiple identities.
---
[8 reasons why blockchain mechanism design is hard](https://a16zcrypto.com/posts/article/8-reasons-why-blockchain-mechanism-design-is-hard/)
[Permissionless Mechanism Design](https://www.gauntlet.xyz/resources/permissionless-mechanism-design)
[Blockchain Protocols and Web3: A Glimpse Under the Hood](https://youtu.be/-mWjDgVWl20)
---
### When the Math Breaks: The Terra/Luna Collapse
<div style="font-size: 28px;">
Theory must meet reality. In May 2022, the Terra ecosystem provided a $40 billion case study in mechanism failure.
* **The Setup**: TerraUSD (UST) was an algorithmic stablecoin. Unlike DAI (over-collateralized by ETH), UST was backed by a game-theoretic arbitrage loop with its sister token, LUNA.
* **The Death Spiral**: A loss of confidence triggered a feedback loop:
* UST drops below $1 $\rightarrow$ Users burn UST to mint LUNA $\rightarrow$ LUNA supply hyper-inflates $\rightarrow$ LUNA price crashes $\rightarrow$ UST loses more backing.
* **The Lesson**: The system was *locally stable* but *globally fragile*. It assumed a constant presence of rational arbitrageurs and failed to account for "bank run" dynamics where liquidity vanishes instantly.
</div>
[Luna Brothers, Inc.](https://www.bitmex.com/blog/luna-brothers-inc)
---
### Privacy via Zero-Knowledge Proofs (ZKP)
The "Transparency Paradox": Blockchains are public, but finance requires privacy.
* **ZKP Definition**: A cryptographic method where a *Prover* convinces a *Verifier* that a statement is true (e.g., "I am solvent") without revealing the underlying data (e.g., "my balance").
* **Mathematical Applications**:
* *Private Credit*: Prove your $Collateral > Debt$ without revealing your wallet's full history.
* *Identity*: Prove you are a verified citizen or >18 without sharing your name or ID.
* *Scalability (zk-Rollups)*: Bundling 10,000 transactions into a single "Succinct Proof" that the main chain can verify in milliseconds.
---
[Zero Knowledge Proofs: An illustrated primer](https://blog.cryptographyengineering.com/2014/11/27/zero-knowledge-proofs-illustrated-primer/)
[Zero Knowledge Proofs: An illustrated primer, Part 2](https://blog.cryptographyengineering.com/2017/01/21/zero-knowledge-proofs-an-illustrated-primer-part-2/)
[Decentralized Identity: The Ultimate Guide 2025](https://www.dock.io/post/decentralized-identity)
---
### Open Problems: The Frontiers of DeFi
This is an invitation for students to apply advanced mathematics to unsolved challenges:
* *Formal Verification*: Using formal methods (e.g., TLA+, Coq) to prove a smart contract is bug-free before it handles billions of dollars.
* *Systemic Risk & Contagion*: Modeling the "Money Lego" effect—how the failure of one protocol propagates through the hyper-connected liquidity network.
* *MEV (Maximal Extractable Value)*: Studying the game theory of transaction ordering to prevent sophisticated bots from "taxing" users through front-running.
---
### Your Career: Beyond the Classroom
Digital Finance is a rare field where pure math translates directly into production infrastructure.
* **Protocol Architect**: Designing the next generation of invariant curves and interest rate models.
* **Risk Quantitative (Quant)**: Running Monte Carlo simulations for firms like [*Gauntlet*](https://www.gauntlet.xyz/) or [*Chaos Labs*](https://chaoslabs.xyz/) to stress-test protocol parameters.
* **The Opportunity**: You are at the intersection of Cryptography, Game Theory, and Distributed Systems. The "Wild West" era is ending; the *"Era of Rigor"* is beginning.
---
## Final Closing Thought
> Digital Finance is not about 'disrupting' banks; it is about building a financial system that is as predictable and transparent as the laws of mathematics.
{"description":"Blockchain technology forms the foundation for decentralized finance (DeFi). It's a system that allows different parties to work together without needing to trust each other. Data like transactions and account balances are stored in \"blocks\" and linked together cryptographically, creating an immutable and auditable history. This makes it incredibly difficult to tamper with data. The system relies on a consensus protocol, such as Proof of Work or Proof of Stake, to ensure all participants agree on the valid version of the blockchain.","title":"DF_sildes","contributors":"[{\"id\":\"9e38ee55-7b6f-408d-a9e3-a3a99f1fde0e\",\"add\":215416,\"del\":196910,\"latestUpdatedAt\":1772859204688}]"}