1/81
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
Defi Characteristics
Smart Contract Foundation - services executed by transparent auditable code rather than centralized institutions
Open Access - anyone can access through interest
Always Available - protocols operate continuously (unlike regular banks with banking hours, holidays, or geographic restrictions)
FTX
Collapsed in November 2022
$8 billion lost
opaque accounting and centralized control
users locked out
Defi Protocols
all transactions visible on-chain
users maintain full control over assets
zero downtime or fund freezes
cryptographic certainty instead of institutional trust
all transactions, collateral ratios, and protocol balances are publicly auditable in real-time
can only lend to anon using only on-chain verifiable assets
Centralized Exchanges
function as black boxes
users must trust management with custody of funds
Composability
all DeFi protocols can be combined to create sophiscated financial products
permissionless composability, so innovation does not require approval from any central authority
Main Protocols: stablecoins, AMMs, lending, perpetuals, governance
Example: acquire stablecoins, supply stablecoins to lending pool and receive interest-bearing tokens, use tokens as collateral to borrow and trade on Uniswap or GMX (tokens still earn yield)
Volatility Problem
native cryptos (ETH, BTC) experience dramatic price swings
unsuitable for predictable loan payments, merchant payment processing, denominating financial contracts (stating what currency to use in contract)
Stablecoin Solution
digital cash pegged to fiat currencies (typically USD) or crypto or algorithm
price anchor (stable reference for defi protocols)
safe haven (preserves value during crypto crashes)
programmable (smart contracts and blockchain capabilities)
enables other DeFi primitives
Fiat-Backed
backed by cash (typically USD) or short term U.S. treasury securities (loans to government) held in traditional bank accounts
1:1 to fiat
subject to off-chain aduitors
examples: USDC (Circle), USDT
risk: requires trusting centralized entity with reserves, issuers can freeze addresses and block transactions, subject to government intervention and compliance requirements
if price below $1, arbitrageurs buy cheap tokens (non USDC), redeem for USDC for $1, pocket difference, demand increases → price rises
if price above $1, mint new USDC and sell them, supply increases → price drops
Crypto-Collaterized
over-collateralized with crypto assets
up to 150% ratio ($150 ETH backs $100 DAI)
if collateral value drops below threshold, automatically liquidate collateral
user returns stablecoin plus stability fee to reclaim collateral
all data on-chain
example: DAI (MakerDAO)
if above $1, mint more DAI by opening more vaults or swap USDC for DAI to increase supply
if below $1, repay loans (burn DAI) and retrieve collateral or swap DAI for USDC to reduce supply
pros: more transparent, more decentralized, and more censorship resisitant than fiat-backed
cons: more complex than fiat-backed, capital-inefficient, code vulnerabilities could drain collateral, heavy reliance on USDC for Peg Stability Module (PSM) so not that decentralized, liquidation can cascade
Algorithmic
incentive mechanism adjusts supply based on demand
mint/burn relationship with governance token (LUNA for UST)
example: UST (Terra) → failed
risk: death spiral if market confidence breaks (mass withdrawal)
if above $1, burn token to mint stablecoin
if below $1, burn stablecoin to mint token
Traditional Order Books
requires matching buyers to sellers
constant order placement and cancellation
high frequency updates
high gas costs
AMM Solution
liquidity always available
no need to match orders
algorithmic pricing
single transaction
passive liquidity provision
AMMs
pool holds reserves of two tokens
liquidity providers deposit both in proportion to current price
invariant ensures some formula of reserves stays constant (sum, product, etc.)
price and supply adjusts to maintain invariant
always available, no operator needed
example: Uniswap (general purpose), Balancer (multi-asset pools), Curve (stablecoin-optimized)
Over-Collateralized Lending
lock up collateral more than loan value
if collateral price drops, collateral ratio drops (less for collateral)
borrow to maintain ETH exposure while accessing liquidity, anonymous, tax efficient
global, permissionless access to liquidity without personal info or delays
automatic liquidation if collateral drops below threshold
less capital efficient than traditional loans
Lending in Action
lenders deposit liquidity into protocol and receive interest-bearing tokens
lock collateral and borrow against it (interest goes to lenders)
interest rates adjust based on utilization (high demand leads to higher rates which lead to more lenders)
borrowers repay principal plus interest to unlock collateral
Perps
no expiration (can hold positions indefinitely)
long positions (rise) and short positions (fall)
periodic payments between longs and short to keep price anchored to spot price
example platforms: dYdX (order book-based), GMX (pool-based leverage), Hyperliquid (high-performance L1=low latency)
Purpose of Perps
offset spot holdings with short positions
express market views with leverage
arbitrage funding rates and spot prices (exploit difference in price)
gain exposure without holding underlying assets
Governance via DAOs
create proposals for protocol changes (fee adjustments, parameter updates, treasury spending, or code upgrades)
governance token holders votes on-chain (voting power proportional to token holdings)
changes execute automatically when passed
maximal transparency
Maximal Extractable Value (MEV)
reorder, insert, or censor transactions to extract additional profit
example: user buys ETH, bot detects pending transaction, bot buys before transaction, bot sells post transaction, bot profits from price movement
DeFi Stack
stablecoins, AMMs, lending, perps, governance
each entry builds on primitives before it
Peg Stability Module (PSM)
DAI price stabilized through 1:1 swaps with USDC
DAI also backed by U.S. treasury bonds
45% backed by USDC, 30% backed by bonds, 25% backed by crypto
Hybrid Approaches for Stablecoin
backed by real-world assets and crypto collateral
integrated with fiat
community control through DAO governance
transparent with regular audits and proof-of-reserves
Constant-Sum Market Maker (CSMM)
linear invariant
x + y = k, delta x = delta y
1:1 exchange
vulnerable to arbitrage
unable to react to external market price changes (if market price shift to not 1 Y per 1 X, arbitrageurs can exploit)
one token can get completely drained
unsafe in practice (not used in real-life)
1mil USDC → 1mil DAI (1.0000 price, 0% price impact)
Constant-Product Market Maker (CPMM)
hyperbolic invariant
x y = k, delta y = (delta x * y)/(x + delta x)
trades cause slippage
larger trades causes more deviations between prices
when pool prices deviate from external markets, arbitrage trades profit until pool’s ratio aligns with global market
slippage prevents pool drainage
used for crypto since no assumption of fixed ratio
1mil USDC → 980392 DAI (0.9804 price, 1.96% price drop)
Slippage
difference between average execution price and marginal price at start of trade
Curve’s StableSwap
A(x+y) + D = AD + (D³)/(4xy)
A(x+y) provides flat pricing near equilibrium
(D³)/(4xy) ensures infinite liquidity at extremes
A is tuning parameter to control hybrid behavior (critical amplification coefficient)
D is total liquidity
low slippage when prices near 1:1
better capital efficiency (large trades have minimal price impact)
CPMM at extremes prevent pool drainage
used for stablecoin exchanges to allow for simple swaps
1mil USDC → 999990 DAI (0.99999 price, 0.001% price drop)
Amplification Coefficient (A)
tuning lever in stableswap
higher A value → flatter around equilibrium (closer to CSMM)
Loan-to-Value Ratio (LTV)
maximum borrowing against collateral
example: 80% LTV on ETH allows $800 loan against $1000 collateral
lower LTV for volatile assets
set by protocol governance
leveraged trading and accessing liquidity without selling assets → avoiding taxable events
Utilization Rate (U)
U = total borrowed / total available liquidity
low U → interest rates fall to encourage borrowing
high U → interest rates rise to incentivize repayment and attract liquidity
optimal rate ~80%
Kinked Interest Rate Model
balance capital efficiency with liquidity risk
below optimal U → interest rates rise slowly to encourage borrowing and maximize capital efficiency (gentle slope)
above optimal U → interest rates surge sharply to prevent pool drainage and attract new liquidity (steep slope)
Health Factor (HF)
HF = (total collateral value * weight avg liquidation threshold)/(total borrow value)
HF > 1 → safe
HF <= 1 → under-collateralized, eligible for liquidation
affected by collateral asset value decreasing, borrowed asset value increasing, taking on additional debt
improve HF by supplying more collateral or repaying debt
example: initial $10000 in ETH with threshold 80% for $6000 in GH, HF=10000×0.8/6000=1.33, ETH drops to $7000, HF=7000×0.8/6000=0.933, liquidate
Liquidation Process
triggered by borrower’s health factor falling below 1
automated liquidator bots monitor blockchain and identify vulnerable position
liquidator calls liquidate, repaying borrower’s debt for them
liquidator receives portion of borrower’s collateral at discount (liquidation bonus), usually 5-10%
previous example: HF=0.933 ($7000 ETH collateral, $6000 GHO debt), with 5% liquidation bonus
liquidator spends $6000 GHO, receives $6300 ETH, profits $300
protocol recovers $6000 GHO and remains solvent
borrower’s debt cleared, receives $700 ETH collateral, lost $6300 to liquidation
Blockchain Oracle
feeds external data to smart contracts
needed to trigger liquidation
has multiple independent sources
resistant to short-term manipulation
de-centralized with no single point of failure
Flash Loan
borrow with zero collateral
loan must be borrowed and repaid with same atomic transaction
reverts if lending contract did not get repaid
used for arbitrage, liquidations, collateral swaps
“money lego” for developers and traders
Atomic Transaction
all or nothing
if every step succeeds, transaction occurs
if any step fails, transaction reverts
Oracle Manipulation Attack
borrowing massive capital through flash loan
use funds to execute swap on low-liquidity DEX to artificially inflate price of token X
gives inflated token X to as collateral to lending protocol using manipulated DEX as oracle, borrows maximum ETH with falsely valued collateral
repays original flash loan, keeps stolen ETH, price of token X crashes, protocol no longer solvent
Oracle Security Strategies
Decentralized Oracle Networks (DONs) - aggregate price data from multiple independent sources
Time-Weighted Average Price (TWAP) - calculate average price over time window (30 minutes), resistant to short-term price spikes
Multi-Source Validation - price agreement across all sources needed before accepting value, detects and rejects outliers
Aave Protocol
liquidity protocol
choose between variable and stable interest rates
pioneered flash loans
supports diverse range of assets as collateral, including volatile and niche tokens
why derivatives exist
mature markets need tools to manage and speculate on volatility
derivatives enable strategies like hedging and leveraged speculation
instead of trading assets directly, trade a contract that derives value from the asset (an echo of the original object)
hedging
protect holdings from price drops
leveraged speculation
amplify market exposure
spot trading
spot trading:
simplest form of trading of the tokens themselves
direct exchange for immediate ownership with no expiration/complex mechanics
traditional futures
traditional futures:
contract to buy or sell at a set price on a future data
like preordering a phone (price now, transaction later)
fixed expiration forces price convergence
short
contract to sell at future time with fixed price now
long
contract to buy at future time with fixed price now
perpetual futures
crypto innovation
futures contract that never expires
hold positions indefinitely with high leverage
make/lose money based on how perp price changes in the future
need to anchor price to reality if no expiration
short profit formula: position size * (entry perp price - exit perp price)
long profit formula: position size * (exit perp price - entry perp price)
spot vs futures vs perpetuals
spot:
no expiration
low/no leverage
direct ownership of asset
price anchor by market price
traditional futures:
fixed date expiration
has leverage
only contract ownership
price anchor by expiration date
perp futures:
no expiration
high leverage
contract only ownership
price anchor by funding rate
why do perps need the funding rate mechanism
without expiration date, perp contract price can drift far from actual spot price making it meaningless
funding rate mechanism
periodic payment between long and short position holders
creates incentives that anchor perp prices to spot prices
when perp price > spot price
market is bullish with more longs
longs pay shorts, making long positions expensive and shorts profitable
reward shorts > pushes perp price down toward spot
funding positive
when perp price < spot price
market is bearish with more shorts
shorts pay longs
reward longs > push perp price up toward spot
funding negative
maintain contract relevance and utility by preventing perp price from drifting
funding rate formula
funding payments calculated every 8 hours
amount = position size * funding rate
funding rate = fixed interest rate + premium
premium = percentage difference between perp and spot prices (Pperp-Pspot)/Pspot averaged over time to prevent manipulation
interest component balances borrowing cost differences, reflect how usd changes?
positive funding rate example
setup:
position: long 1 BTC
spot price: $100,000
perp price: $100,120 (bullish premium)
position notional (entry size): $100,120
interest: 0.01%
calculate premium:
P = (100,120-100,000)/100,000=0.12%
calculate funding rate
F = 0.12%+0.01%=0.13%
calculate payment
payment = 100,120 × 0.13% = $130.16
double edged sword of leverage and liquidation
leverage
main attraction of perpetuals
control large positions with small capital deposits called margin
liquidation
deposit automatically liquidated if loss is about to exceed the deposit
if short, you are forced to buy
if long, you are forced to sell
liquidation cascade
liquidation is a risk when many traders cluster at similar price points
after breaking through a liquidation wall, a cluster of traders are liquidated simultaneously and the exchange dumps all their positions causing the price to change drastically
new price can break through another liquidation wall and make another cluster of traders liquidate, causing a chain reaction
case study decentralized perps: GMX
trader vs pool model
pioneer on-chain perpetuals on layer 2 networks like arbitrum???
pooled liquidity model centered around GLP token eliminating need for traditional order books
GLP
multi-asset liquidity pool where users deposit variety of tokens into one pool and receive GLP tokens in return representing their share of the entire pool
trading mechanism:
traders trade directly against GLP pool
liquidity providers collectively act as single counterparty “house”
oracle base pricing
GMX uses high speed oracles like chainlink that aggregate prices from major centralized exchanges
key feature: zero slippage, large orders do not impact price. use oracle price
profits and losses go to and from the GLP pool
liquidity providers betting that traders will lose more than they win, earning fees and trader losses as yield
case study decentralized perps: Hyperliquid
new gen, central limit order book (CLOB) on own application-specific blockchain
makes traditional exchange mechanics fully on-chain
CLOB:
traditional model used by centralized exchanges/stock markets
public ledge of all buy and sell orders at different price levels visible to all participants
trader-to-trader
traders match against each other directly
buy orders need to find corresponding sell orders
market makers provide liquidity
native price discovery
prices are discovered on-platform thorugh order matching
market price is last matched trade where highest bid meets lowest ask
gmx vs hyperliquid trade off
gmx:
strengths
zero slippage
simple lp participation
capital efficient
predictable execution prices
weaknesses
no native price discovery
oracle dependency risk
lps bear all trader P&L risk
prices imported not discovered
hyperliquid:
strengths
native price discovery
traditional market dynamics
no oracle dependency
real-time order matching
weaknesses
slippage on large orders
requires market maker presence
thin books > high slippage
complex infrastructure needs
gmx vs hyperliquid comparison summary
gmx:
liquidity from glp pool (collective lps)
price from external oracles
zero slippage because use oracle price
counterparty: pool vs trader
infrastructure uses L2 smart contracts
best for predictable execution
hyperliquid:
liquidity from individual market makers
price from on-chain order matching
variable slippage depending on order book depth
counterparty: trader vs trader
custom blockchain infra
beset for price discovery and transparency
blockchain mempool
when user sends a transaction, it enters the mempool (memory pool)
public waiting area for unconfirmed transactions
each node maintains own mempool version, converging on similar pending transaction sets
transparent: all transactions, contents, and gas fees are publicly visible
what is MEV
Originally “miner extractable value” in proof-of-work systems
evolved now “Maximal Extractable Value”
core definition:
maximum value extractable by block producers through strategic inclusion, exclusion, or reordering of transactions within blocks they create, beyond standard block rewards and transaction fees
information asymmetry
MEV is possible because transactions are public and can be reordered before confirmation
block producers and “searchers” exploit this by monitoring the mempool for profitable opportunities
core MEV strategies
front-running
executing transactions before victims by paying higher gas fees
back-running
capitalizing on price movements immediately after target transactions
sandwich attacks
combining front-running and back-running to trap victim transactions
front-running mechanics
front-runner spots profitable pending transaction in mempool (like large DEX swap that will move an asset’s price)
attacker submits own transaction with higher gas fee to get priority inclusion
front-runner executes first, causing price to move up
original transaction gets worse price, and attacker gets more value
back-running mechanics
execute transaction immediately after a target transaction to profit from price impact
ex: if large trade causes price imbalance between two DEXs, a back-runner can buy on cheaper DEX and sell on pricier DEX
less harmful than front-running, doesn’t worsen victim’s execution, just profits off of it
sandwich attack
first frontrun, then victim trades, then backrun
one of most common and harmful MEV strategies
liquidation MEV: necessary evil
in decentralized lending, when borrower’s health factor drops below threshold, their position is eligible for liquidation
liquidators repay debt in exchange for the collateral at a discount (liquidation bonus)
highly competitive process, with multiple liquidator bots engaging in gas bidding wars to try an get their transaction first (others fail)
liquidation MEV is essential for protocol health
ensures under-collateralized loans close quickly, protecting protocols from accumulating bad debt
oracle latency MEV
blockchain oracles vitally bring off-chain data to smart contracts, but are slow
oracles update every n minutes or after significant price deviations
latency problem
delay between real-world price changes and on-chain oracle updates creates oracle latency
window where smart contracts operate on outdated info
exploitation opportunity
attakers monitor real-world prices and on-chain prices, exploiting discrepancies
can have catastrophic consequences for protocols
ex: LUNA/UST 2022 collapse
case study: LUNA De-peg
during LUNA price crash, real-world prices on centralized exchanges like binance fell faster than on-chain oracles updated
attackers could buy buy a lot of tokens for real price and deposit into protocol where it is worth more under outdated oracle
protocol allows to borrow against that inflated collateral
after oracle updated, protocol got a lot of debt
pros/cons of MEV
pros
price efficiency: arbitrage MEV maintains consistent pricing across different DEXs
protocol solvency: liquidation MEV provides powerful incentives ensuring lending protocols remain solvent by quickly closing under-collateralized positions
network incentives: MEV revenue can constitute a significant portion of block producer income, incentivizing rubust network security and participation
cons:
frontrunning and sandwich attacks harm victims through slippage, execution prices, and losses
network congestion: fierce competition among MEV bots create gas wars that inflate transaction fees and clog the network for everyone
centralization risk: high-value MEV opportunities favor entities with more resources
MEV mitigation strategies
chain-level and protocol solutions
modify fundamental blockchain rules or transaction supply chain to reduce harmful MEV on protocol level
application-level
strategies that decentralized apps, especially DEXs use to protect their users from bad MEV attacks
private transaction relays
most widely adopted MEV mitigation
how works
users send transactions directly to a private relay instead of public mempool
relay forwards transactions to specialized block builders with agreements to include them
key benefit
transactions are hidden from public MEV bots until included in a block
limitation
users must trust relay and builder to not exploit themselves
but reputation and economic incentives of major builders prevent bad behavior
centralization problem which proposer-builder separation (PBS) combats
validators who propose blocks also build them
to maximize profit, proposers run resource-intensive MEV extraction software, which favor large staking pools
small solo-stakers cannot compete and profit less from their blocks since they make less MEV
pressures users to stake with large pools, driving validator centralization
proposer-builder separation (PBS) solution
separate roles into two specialized actors
builders (specialists):
highly specialized entities that build maximally profitable blocks with MEV before submitting bids to proposers
proposers (validators):
select most profitable block from competing builders based on bid amount
no need for MEV expertise
does not stop MEV, but acknowledges extracting MEV is difficult
builders must bid their potential profit in order to get their block built
money is moved from few specialists who find MEV to all validators who secure the network
proposer-builder separation (PBS) benefits
solo stakers are as profitable as large pools since neither build the actual blocks, both accept the winning bids from open market
no more pressure for validator centralization
creates competitive building market that maximizes value returned to all stakers
slippage tolerance: application level MEV protection
most common user-facing MEV protection
when users make swaps, DEX interfaces require them to set a slippage tolerance
if final price exceeds tolerance, the transaction is failed
defends against sandwich profitability since they can only extract so much that it doesn’t fail the user’s transaction
limitation since bots can still extract MEV without triggering limits with an upper bound
batch auctions: application level MEV protection
some DEXs use this instead of sequential execution
collection phase: protocol collects all user trades from short time window into a batch
solving phase: third party solver examines trades in batch and calculates single uniform clearing price
execution phase: everyone in batch receives same prices regardless of submission order
traditional AMMs are sequential where order matters, which attackers can exploit
defi stack
value (stablecoin) > exchange (AMM) > credit (lending) > derivatives (perps) > governance (DAOs)
what is a DAO
rules as code: organizational bylaws encoded in transparent, immutable smart contracts
member control: token holders collectively govern through binding, on-chain votes
no central authority: flat, democatic structure replacing traditional hierarchies
token-weighted voting
most prevalent DAO governance mechanism
voting power scales linearly with token ownership
allows voting power with financial stake
simple implementation, default choice for most DAOs
whale problem with token-weighted voting
when token distribution is unequal, a handful of large holders (whales) can dominate decisions, marginalizing thousands of smaller participants
plutocracy
quadratic voting
solution to wealth concentration by making additional votes exponentially expensive
cost to cast n votes equals n² credits
forces strategic allocation of credits when you vote
ex: if you have 16 credits, you can cast 1 vote on 16 different proposals or cast 4 votes on one critical issue
governance failure: flash loan attack
abuse flash loans to temporarily hijack voting power within single atomic transaction
borrow: attacker gets massive flash loan of governance tokens
vote: temporary voting power passes malicious proposal
execute: proposal executes immediately, draining treasury
repay: flash loan repaid, attacker walks away with funds
ex: Beanstalk Farms, because proposals were executed instantly after passing
solution to flash loan attacks
mandatory time delays between vote passage and execution to prevent instantaneous manipulation
curve wars
2021-2022 multi-billion dollar fight in DeFi to control Curve Finance
Curve: largest exchange for stablecoins and key part of how digital financial systems work
Big players like Convex Finance and Frax Finance constantly bought Curve’s main CRV token to get more voting power
Want to send CRV rewards to their own investment pools, attracting users and giving financial sway
Large amounts of money called Total Value Locked (TVL) at stake
example of how DAO governance works, show game theory in decentralized autonomous orgs
curve governance mechanism
CRV governance token can be locked up for up to 4 years to receive veCRV (vote-escrowed CRV)
veCRV holders voe on which liquidity pools receive weekly emissions of new CRV tokens as rewards
directing CRV rewards to specific pool attracts more liquidity as LPs chase maximum yield
deep liquidity is crucial for stablecoin protocols
control votes > control liquidity > control market
curve battle cycle
loop of increasing dominance
acquire CRV tokens > lock CRV for veCRV voting power > vote to direct CRV rewards to own pool > high rewards attract more liquidity providers to that pool > deep liquidity generates revenue > acquire more CRV tokens with extra fees