# The Mathematical Heart of Decentralized Finance
Shen-Ning Tung, National Tsing-Hua University
## Introduction: Reimagining Finance with Math
### Motivation: Limitations of Traditional Finance
* Familiar Concepts:
* Lending: Banks as intermediaries, access limitations
* Trading: Exchanges, fees, market manipulation
* Payments: Slow, costly, geographically restricted
* Limitations:
* Centralized control: Single points of failure, censorship
* Lack of transparency: Opaque processes, information asymmetry
* Inefficiency: Fees, delays, bureaucratic overhead
### Rebuilding Finance with Math and Computation
* A New Paradigm:
* Replace intermediaries with algorithms
* Establish trust through code, not institutions
* Create open, accessible, and efficient systems
* Key Idea:
* Use mathematical and computational tools to redesign financial systems from the ground up
### What is DeFi? Core Ideas
* Automation:
* Smart contracts execute agreements automatically
* Mathematical logic replaces human intervention
* Transparency:
* Blockchain provides a public, auditable record
* Every transaction is visible and verifiable
* Decentralization:
* Control is distributed across a network
* No single entity has ultimate authority
* Programmability:
* Financial instruments are built with code
* Enables innovation and customization
### DeFi: A Mathematical Transformation
* Traditional Finance:
* Relies on legal contracts, human enforcement, trust in institutions
* DeFi:
* Formalizes agreements in mathematical code
* Enforces rules algorithmically
* Establishes trust through cryptographic proofs
* DeFi is a *mathematical* re-engineering of finance

[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)
### Why Math Matters in DeFi
* Cryptography:
* Secures transactions, protects data, enables digital identities
* Provides the foundation for trust in a decentralized system
* Game Theory:
* Designs incentives, analyzes strategic behavior, prevents manipulation
* Ensures that the system operates fairly and efficiently
* Mathematical Modeling:
* Analyzes financial mechanisms, predicts market behavior, manages risk
* Enables the creation of sound and stable protocols
### Preview of Mathematical Areas
* Data Structures:
* Hash trees (Merkle trees) for efficient verification
* Cryptography:
* Hashing, digital signatures for security
* Distributed Consensus:
* Algorithms for agreement in decentralized systems
* Game Theory:
* Mechanism design, incentive analysis
* Optimization:
* Algorithms for trading, resource allocation
## The Foundation: Blockchain and Smart Contracts
### Blockchain: A Mathematical Ledger
* Core Idea: A distributed, tamper-proof record of information
* Key Elements:
* Data Structure: Merkle Trees
* Cryptography: Hashing and Digital Signatures
[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)
### Merkle Trees: Organizing Data Efficiently
* Hierarchical Structure: Data is grouped, hashed, and summarized
* Efficient Verification: Quickly check if a piece of data is included
* Mathematical Property: Logarithmic time complexity for verification
* Visual: (A simple diagram of a Merkle Tree)

[Blockchain Merkle Trees](https://www.geeksforgeeks.org/blockchain-merkle-trees/)
### Cryptography: Securing the Blockchain
* Hashing:
* Mathematical function that creates a unique "fingerprint" of data
* Properties: One-way, collision-resistant
* Used for: Data integrity, linking blocks
* Digital Signatures:
* Mathematical scheme for verifying authenticity
* Based on: Public-key cryptography
* Used for: Transaction authorization, identity
[Dan Boneh: Blockchain Primitives: Cryptography and Consensus](https://www.youtube.com/watch?v=7Cu8KQmUhu0)
### How Math Provides Security and Trust
* Merkle Trees:
* Mathematical structure ensures data cannot be altered without detection
* Hashing:
* Cryptographic properties guarantee data integrity
* Digital Signatures:
* Mathematical proofs verify the sender and prevent forgery
* Math provides the foundation for trust in a trustless system

[Ethereum & Bitcoin Transaction Visualizer](https://txcity.io/v/eth-btc)
### Smart Contracts: Code as Contracts
* Self-Executing Agreements: Code that automatically enforces the terms of a contract
* Formalizing Agreements: Translating legal language into mathematical logic
* Example:
* If X happens, then Y is executed.
* This logic is written in code and executed by a computer.

[What Are Smart Contracts and How Do They Work?](https://chain.link/education/smart-contracts)
### Ethereum Virtual Machine (EVM)
* Decentralized Computation Engine:
* A global computer that runs smart contracts
* Mathematical Foundations:
* State machines: How the "computer" changes its state
* Formal semantics: The precise meaning of the code
* EVM executes the code of smart contracts
[What is Ethereum?](https://ethereum.org/en/what-is-ethereum/)
### Oracles: Connecting Blockchains to the Real World
* The Challenge:
* Blockchains and smart contracts operate within their own digital environment.
* They often need data from the outside world (e.g., prices, weather, events).
* Oracles Provide Data:
* Oracles are systems that bring external information onto the blockchain.
* They act as bridges between the on-chain and off-chain worlds.
* Example:
* A smart contract for crop insurance might use an oracle to get data about actual rainfall.
* Importance:
* Oracles are essential for many DeFi applications to function correctly and usefully.

[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/)
## Token Economics
### Tokens as Digital Objects
* Digital Assets on Blockchains:
* Represent value, utility, or ownership
* Data records with attributes (quantity, permissions, metadata)
* Properties:
* Fungibility: Interchangeable
* Divisibility: Can be divided
* Transferability: Can be moved
* Programmability: Behavior governed by code
### Cryptocurrencies vs. Tokens
| Feature | Cryptocurrencies | Tokens |
|---------|-----------------|---------|
| Definition | Native digital assets of a blockchain (e.g., Bitcoin, Ethereum) | Represent assets/utility on a blockchain |
| Purpose | Medium of exchange, store of value | Diverse functions in DeFi (governance, utility, etc.) |
| Examples | Bitcoin (BTC), Ethereum (ETH) | Governance (UNI, AAVE), Stablecoins (USDT, USDC) |
### Smart Contracts and Token Management
* Automation of Token Operations:
* Creation and distribution
* Transfer and exchange
* Locking and unlocking
* Governance mechanisms
* Benefits:
* Reduced intermediaries
* Increased efficiency and transparency
* Enforced rules
### Mathematical Models for Token Behavior
* Token Behavior:
* Modeling supply and demand
* Analysis of token flow
* Mathematical Tools:
* Network analysis
* Stochastic processes
* Token Valuation:
* Determining token value
* Factors: utility, governance, scarcity
* Mathematical Tools:
* Discounted cash flow analysis
* Network value calculations
* Game-theoretic models
### Tokenization: Representing Assets Digitally
* Tokenization:
* Representing ownership of assets as digital tokens
* Mathematical Frameworks:
* Mappings between real-world assets and digital representations
* Metadata standards for token properties
* Models for fractional ownership
### Security Tokens and Asset-Backed Tokens
* Security Tokens:
* Represent ownership in financial assets (e.g., stocks, bonds)
* Subject to securities regulations
* Mathematical Focus:
* Legal/regulatory compliance
* Contractual obligations in code
* Asset-Backed Tokens:
* Backed by physical or digital assets (e.g., real estate, commodities)
* Value from the underlying asset
* Mathematical Focus:
* Valuation/verification of assets
* Auditing and proof of reserves

[Beyond Token Issuance](https://pages.chain.link/hubfs/e/definitive-guide-to-tokenized-assets.pdf)
[Defining tokens](https://a16zcrypto.com/posts/article/defining-tokens/)
[Stablecoins 101: Behind crypto’s most popular asset](https://www.chainalysis.com/blog/stablecoins-most-popular-asset/)
## Core DeFi Mechanisms: A Mathematical View
### Decentralized Exchanges (DEXs)
* Trading Without Intermediaries:
* Traditional exchanges use order books and matching engines.
* DEXs use Automated Market Makers (AMMs).
* AMMs:
* Smart contracts that set prices automatically.
* Use mathematical formulas to determine exchange rates.
### Automated Market Makers (AMMs)
* How They Work:
* Liquidity pools: Collections of tokens locked in a smart contract.
* Traders swap tokens with the pool.
* Prices adjust based on the pool's balance.
* Mathematical Formula:
* Determines the price and how it changes with trades.

[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)
### Example: Constant Product Market Maker
* Mathematical Formula:
* $X \cdot Y = K$
* Where:
* $X$ = amount of token 1
* $Y$ = amount of token $
* $K$ = a constant value
* Explanation:
* The product of the two token amounts remains constant.
* Trades change the ratio of tokens, which changes the price.
* 
[Uniswap University](https://uniswap.university/)
### Lending and Borrowing in DeFi
* Decentralized Money Markets:
* Users can lend and borrow cryptocurrencies.
* Protocols use math to manage the process.
* Key Concepts:
* Interest Rates: Determined by supply and demand
* Collateral: Assets used to secure loans
* Liquidations: Automatic selling of collateral when loans are undercollateralized
### Mathematical Models for Risk Management
* Interest Rate Models:
* Algorithms that calculate and adjust interest rates
* Based on factors like utilization rate
* Collateralization:
* Loan-to-Value (LTV) ratios: Limit how much can be borrowed against collateral Mathematical rules to ensure loans are sufficiently backed
* Liquidation:
* Mathematical conditions that trigger liquidations
* Ensures the safety of lenders' funds

[DeFi Money Markets 2024: How Trustless Lending and Borrowing Drive Financial Innovation](https://threesigma.xyz/blog/defi-money-markets-2024-guide)
[Aave docs](https://aave.com/docs)
### Stablecoins: Maintaining Price Stability
* Goal:
* Create cryptocurrencies with a stable value (e.g., pegged to the US dollar)
* Importance:
* Reduce volatility, making crypto more useful for everyday transactions
* Mathematical Mechanisms:
* Different stablecoins use different approaches
* Collateralization, algorithms, etc.

[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)
## The Power of Permissionless Systems
### Challenges of Decentralized Systems
* Open Participation:
* Anyone can join, leading to diverse behaviors
* Many Participants:
* Complex interactions, difficult to model
* Potential for Collusion:
* Groups may try to manipulate the system for their benefit
* Designing systems that are fair, secure, and efficient is a major challenge
### Mathematical Solutions: Cryptography
* Securing Identity and Data:
* Digital Signatures:
* Verify users and transactions
* Prevent fraud
* Zero-Knowledge Proofs:
* Prove something is true without revealing details
* Enhance privacy
* Cryptography provides the mathematical tools for security in open systems
### Mathematical Solutions: Game Theory
* Designing Incentives:
* Mechanism Design:
* Create rules that encourage desired behavior
* Discourage attacks
* Equilibrium Analysis:
* Predict how participants will act
* Ensure the system is stable
* Game theory helps us design systems that work even when participants act strategically
[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)
### Goals: Credibility
* Preventing Fake Identities:
* Cryptographic identity schemes
* Reputation systems
* Mathematical Analysis:
* Evaluating the cost of creating fake identities vs. potential gains
* Credibility means participants can't easily cheat the system
[Decentralized Identity: The Ultimate Guide 2025](https://www.dock.io/post/decentralized-identity)
### Goals: Collusion Resistance
* Preventing Harmful Cooperation:
* Game theory to analyze collusion strategies
* Mechanisms that make collusion difficult or unprofitable
* Mathematical Analysis:
* Studying how coalitions form and whether they are stable
* Collusion resistance means groups can't unfairly disadvantage others
### Goals: Incentive Compatibility
* Aligning Individual and System Goals:
* Mechanism design to create incentives for positive actions
* Mathematical analysis of incentive structures
* Incentive compatibility means participants are motivated to act in ways that benefit the whole system
## The Future of DeFi: A Mathematical Frontier
### Open Problems: Mathematical Challenges
* Formal Verification of Smart Contracts:
* Ensuring code is correct and secure
* Preventing errors and vulnerabilities
* Mathematical tools for proving code properties
* Systemic Risk in DeFi:
* Understanding how risks spread through interconnected protocols
* Developing mathematical models for stability and resilience
* Designing New Mechanisms:
* Creating innovative DeFi protocols and applications
* Using math to optimize efficiency, security, and fairness
### The Potential: Math as the Foundation
* DeFi's Transformative Power:
* Creating a more open, transparent, and efficient financial system
* The Central Role of Math:
* Providing the tools to build secure, robust, and reliable protocols
* Math is not just a tool in DeFi, it's the bedrock
### The Future: A Mathematical Frontier
* Uncharted Territory:
* DeFi presents exciting new challenges for mathematicians
* Innovation and Discovery:
* Mathematical research will drive the future of DeFi
* An Invitation:
* Join the exploration of this dynamic and important field
[Gauntlet](https://www.gauntlet.xyz/)
[Chaos Labs](https://chaoslabs.xyz/)
[Simtopia](https://www.simtopia.ai/)