defi 80/20

June 2022

Ken Deeter has a great thread on the five core concepts to grok 80% of DeFi.

  • ERC20 tokens

  • Stablecoins

  • Automated market makers

  • Automated lending and borrowing

  • Automated investment strategies

Once you get these, the rest of DeFi is just forking, remixing, and iterating.

I once heard the OG Chris Dixon recommend learning DeFi through the canonical protocols: Maker DAO, Uniswap, Curve, Balancer, Compound, Aave, and Yearn. 

his piece will explore each concept and the corresponding protocols.

Before we get into it, let’s do a quick 101 on what DeFi is and why it matters.

How DeFi is changing the game

History lesson

DeFi - decentralised finance - is an open, globalised alternative to the traditional financial system (in crypto speak, “TradFi”) based on decentralised blockchains. Power is pushed back into the hands of end-users (consumers, companies, and institutions) to manage their money without relying on third-party intermediaries.

You can think of all the possible actions in a financial system as “money verbs”: holding, spending, borrowing, lending, investing, staking, trading, and betting. DeFi enables us to exercise these money verbs for crypto assets.

The creation of Bitcoin in 2009 laid the groundwork for DeFi by facilitating peer-to-peer payment transfers on a trustless blockchain. The Bitcoin blockchain is a credibly neutral settlement layer for transactions in its native BTC token.

Ethereum created the infrastructure for DeFi by unlocking the ability to program any asset through smart contracts. Ethereum’s programmability enables a DeFi stack to be built on top.

While the Bitcoin blockchain can only settle BTC, Ethereum is an asset agnostic settlement layer. Any asset (not just ETH) can be tokenised (represented through a fungible or non-fungible token) and exchanged on the blockchain.

DeFi protocols can be built on top using smart contracts. These protocols are the mechanics of how DeFi products work. They enable the money verbs. Many protocols have application interfaces, but anyone can build new frontend applications for them because the code is open.

Aggregators bundle applications together so that users can access them in one place.

In 2017, many crypto projects raised funding through initial coin offerings. Some of the veteran DeFi protocols came alive around this time.

The big inflection point was DeFi Summer 2020 started by lending protocol Compound launching its COMP governance token. Since then, new DeFi applications have exploded, and users have continued flooding in.

DeFi has expanded to other blockchains, but Ethereum remains the hotbed for most activity.

There’ve been two phases of DeFi protocols. Over the years, they’ve shifted from a peer-to-peer to a peer-to-contract model. In peer-to-peer, protocol users interact directly with each other, for example, buyers interact with sellers, and lenders interact with borrowers. Most off-chain markets work this way, but using this model on-chain results in lots of transactions, high gas costs, and inefficiency when there isn’t another user to take the other side of a transaction.

With peer-to-contract, users’ funds are pooled in smart contracts and they don’t have to interact with each other. This means fewer transactions, less gas expense, and concentrated, rather than fragmented, liquidity.

What DeFi unlocks

To see the benefits of DeFi, let’s explore it through three lenses: open and permissionless, disintermediation, and efficiency.

Openness is rooted in the blockchain. A blockchain is a ledger of transactions stored on a decentralised network of computers. Anyone can access a blockchain to read the data, but nobody owns it. The ledger is immutable. Once transactions are recorded, they can’t be changed, so the blockchain is censorship-resistant.

DeFi protocols are powered by smart contracts. Smart contracts are “if-then, then that” programs that run automatically once deployed. They receive inputs and spit out predetermined outputs. Because they’re programmable, smart contracts unlock new digital assets and instantiations of the money verbs that were previously impossible in TradFi.

The DeFi stack is based on open-source code, which anyone can view, audit, and use. Open-source unlocks composability. DeFi protocols run on the same base layer blockchain code, use the same token standards, and can mix and match each other's code and build on top of each other like money legos. New protocols can piggyback off their predecessors without reinventing the wheel each time, hence supercharging innovation and network effects. Everything only needs to be built and solved once (shout out Naval).

Composability leads to interoperability, where the outputs of one protocol or application can be the inputs to others, creating a fluid and symbiotic ecosystem where users can move around with minimal switching costs, compared with the silos of TradFi.

In TradFi, there are still around one billion unbanked people globally who don’t have access to financial services. We take this for granted in the West. But, in the current system, people without a bank account are shut out from managing their money. TradFi is permissioned because users have to go through banks. DeFi is permissionless. Anyone with an internet connection can use it, regardless of their background and where they live. Users only need to connect their wallets and can retain a pseudonymous identity without having to share all their data.

DeFi disintermediates banking. By migrating the financial system to a blockchain with decentralised protocols, users stay in control of their assets and don’t have to hand over margin.

TradFi “internet banking” is skeuomorphic: legacy bricks and mortar infrastructure with digital rails on top. DeFi offers an internet-native financial system that runs automatically on code, not humans. The result is instant transaction settlement, lower fees, and less margin for error. Users can access global liquidity any time they want, unconstrained by geographic borders and opening hours. Downstream, there’s no more counterparty risk and reduced transaction costs.

Now we know what DeFi is and why it matters, let's get into the core concepts.

ERC20 tokens

Tokens are digital representations of assets that sit on the blockchain.

Two kinds of tokens map to assets in the real world: fungible and non-fungible. Financial assets are fungible because they’re completely interchangeable, hence represented by fungible tokens.

ERC20 is the framework for fungible tokens on Ethereum. By standardising the basic functionality for fungible tokens, ERC20 makes it easy for protocols and applications to build generic infrastructures that accept all tokens conforming to the standard, rather than creating custom versions for multiple variations. Developers can easily predict how their tokens interact with other parts of Ethereum.

The ERC20 token standard comprises six required functions, two required events, and three optional functions for the smart contract governing the token.

Required functions

✔  totalSupply returns the current total supply of tokens under the contract

✔  balanceOf returns the token balance of the wallet address calling the smart contract 

✔  approve enables an account to allow another address to spend a specific amount of its balance

✔  transfer for sending tokens from one address to another

✔  transferFrom enables an address to transfer its balance to another address

✔  allowance shows how much an address is allowed to spend from another address

Required events

✔  Transfer is triggered when an account successfully uses the transfer or transferFrom functions. It gives the address of the sender and recipient and the number of tokens sent

✔  Approval is triggered when the approve function is called and returns the owner, sender, and approved amount

Optional functions

✔  name to give the token a name

✔  symbol to give the token a symbol

✔  decimals for how divisible the token is

Minting and burning functions can be incorporated into the contract as well. These are usually only callable by authorised accounts.

The programmability of ERC20 tokens makes them incredibly versatile. In DeFi, they can be used for digital money (as a cryptocurrency), equity, utility, and governance. Equity tokens represent ownership in an asset or pool of assets. They’re used to incentivise users to contribute a resource to a network, such as LP tokens given to users who deposit liquidity in trading pools. Utility tokens unlock functionality in a smart contract, like in Compound where users need to deposit approved collateral tokens to access loans. Governance tokens provide voting rights in a protocol or application.

Standardisation leads to composability, and composability is innovation. ERC20 tokens are portable across all protocols, so tokens received in one protocol can be used for a different purpose in others. Users get more choices and lower exit costs because they can take their tokens anywhere in the DeFi ecosystem.

Stablecoins

Stablecoins are a hybrid of fiat currencies and decentralised crypto. They’re where TradFi meets DeFi.

ETH and other cryptocurrencies are extremely volatile, making them difficult to use as a medium of exchange. It’s hard to price goods and services in a currency when its value is constantly fluctuating.

Stablecoins aim to maintain a fixed value by pegging to another asset.

There are four categories of stablecoins: fiat-backed, crypto-backed, precious metal-backed, and algorithmic.

Fiat-backed stablecoins are underpinned by fiat reserves. Each stablecoin is usually backed by one equivalent unit of fiat money. The best example, USDC, is pegged to USD 1:1 and managed by a consortium of Circle and Coinbase. Fiat-backed stablecoins are a bridge into crypto because they’re still backed by (apparently “safe”) fiat money and easily convertible. However, they’re inherently centralised as the fiat reserves are held by the issuer or another institution, so holders still need to trust a custodian. They bring fiat monies on-chain but don’t fundamentally change the system.

Crypto-backed stablecoins use crypto assets as collateral. Because crypto-assets are volatile, crypto-backed stablecoins are usually overcollateralised to preserve the stability of the stablecoin as much as possible. For example, a $1 crypto-backed stablecoin could be backed by $2 of crypto collateral. When the value of the collateral declines, more needs to be posted to support the value of the stablecoin. Unlike fiat-backed stablecoins, crypto-backed coins are end-to-end decentralised as the collateral is held by Ethereum accounts, not an off-chain centralised entity.

Precious metal-backed stablecoins use resources like gold to maintain their value. Such coins, like Pax Gold, experience the same centralisation challenges as fiat-backed coins, as holders need to trust the issuer or other institution to manage the reserves.

Instead of being backed by another asset, algorithmic stablecoins automatically adjust their supply in response to the market value. Supply is elastic but non-dilutive. If the stablecoin exceeds its target value, holders receive proportionally more to bring the price down. If the stablecoin falls below its target value, holders get a proportionate reduction to push the price up. Holders need to trust the algorithm and the absence of a reserve makes it hard for algorithmic stablecoins to handle large contractions. Ampleforth is an algorithmic stablecoin where expansion and contraction of the AMPL token aim to bring its value back to equilibrium within 5% of the target price.

Dai

Dai is the godfather of stablecoins run by MakerDAO. The Maker protocol aims to keep Dai soft-pegged at $1.

Anyone can lock up approved crypto assets in a smart contract Maker Vault and borrow Dai against them.

Holders of the Maker governance token (MKR) manage the protocol and keep Dai stable by approving each collateral type and determining their risk parameters. These include the collateralisation threshold, liquidation ratio, liquidation penalty, debt ceiling (maximum amounts borrowable for each vault and the whole protocol), stability fees, collateral auction durations, and auction bid duration. The riskier the collateral asset, the more stringent the parameters.

If MKR holders govern well and keep Dai stable, they benefit through MKR token appreciation.

Market participants called Keepers support the peg by selling Dai when the market price trades above $1 and buying Dai when it falls below.

Vaults must be overcollateralised to create a buffer in case the collateral depreciates. The collateralisation threshold depends on the type of collateral.

Borrowers must ensure their collateral value exceeds the vault liquidation threshold to avoid getting liquidated. Otherwise, Keepers trigger automatic auctioning of the collateral to repay the borrowed Dai plus a liquidation penalty. Any remaining collateral can be withdrawn by the borrower. Keepers are rewarded in Dai, as a proportion of the balance of the liquidated vault, for triggering auctions.

If the collateral auction generates enough Dai to pay off the debt and penalty, any residual goes to the borrower. In a shortfall, the remaining balance is paid from the Maker Buffer pool of fees. If that still doesn’t cover the balance, the protocol would mint new MKR tokens and sell them for Dai to repay the debt. This backstop aligns MKR holder incentives with Dai borrowers as they need to be diligent in approving collateral and setting parameters to avoid liquidations and getting diluted by increased MKR printing.

Dai received from the collateral auction goes into the Maker Buffer to reduce the risk of MKR holders being diluted in the future (by having more supply to cover future liquidations) and make staking payouts to Dai holders.

As long as the vault remains collateralised, there’s no repayment schedule, and users can keep their Dai as long as they want.

When borrowers want their collateral back, they repay Dai plus a Stability Fee (also denominated in Dai). While the Dai debt is outstanding, the Stability Fee accrues to the vault. It can be toggled up and down by MKR holders to stimulate or constrict Dai supply. Repaid Dai gets burned, and excess Dai above a certain level in the Maker Buffer from Stability Fee payments and collateral sales is used to buy up and destroy MKR tokens on the open market. This “buy and burn'' creates constant upward pressure on the MKR token price.

On top of benefitting from Dai’s stability, holders earn rewards through staking. The Dai Savings Rate (DSR) is the easiest way to do this. Borrowers can lock their Dai into the DSR smart contract on the Maker protocol and earn interest. There’s no minimum deposit, and Dai can be withdrawn at any time. DSR is highly variable because it’s adjustable by the MKR governance holders.

Moving the DSR up and down is another lever for MKR holders to control the supply of Dai and maintain the peg: if the market price of DAI is above $1, they can reduce the DSR to decrease demand and bring the price down, whereas if the market price is below $1, they can increase the DSR to boost demand and juice the price up.

Maker comes with an Emergency Shutdown Module initiable by MKR holders. It's intended for system upgrades and emergencies like market crashes or hacks and ensures Dai holders and vault users get back the net value of tokens they’re entitled to under the smart contracts. Dai holders may still get back less than $1 of collateral for 1 Dai if the collateral depreciates.

Automated market makers (AMMs)

This area can get quite complex, so let’s go slow.

AMMs are a form of decentralised exchange (DEX).

What’s a DEX?

There are thousands of different tokens in the Ethereum network, and it needs a liquid market for exchanging them.

Traditional exchanges (in crypto and TradFi) are centralised intermediaries that sit between supply and demand, matching buy and sell orders. DEXs are a new form of exchange where users trade their tokens directly with open and permissionless smart contracts, not an intermediary, and always retain control of their tokens.

There are three types of DEXs: on-chain order books, off-chain order books, and AMMs.

In the order book model (used in TradFi) buy and sell orders are matched by an exchange algorithm. Buyers and sellers place separate orders, and the trade gets executed if they converge on a price. The price of the asset is usually quoted as the mid-market between the highest bid and lowest ask.

Order books rely on market makers to guarantee liquidity when there’s nobody on the other side of the trade. These market makers are financial institutions (like investment banks) or professional traders that create multiple buy/sell orders to match the orders of retail investors, so they’ll always step in to take the other side of a trade when there’s no other counterparty. Without them, liquidity could dry up, and prices would slip a lot.

Replicating order books on-chain is difficult because every call of the smart contract costs gas, which makes updating orders expensive. The model is uneconomical for centralised market makers.

In off-chain order book exchanges, buyers and sellers trade on peer-to-peer order books outside the blockchain to optimise for speed and cost, then settle on-chain. DEXs like dYdX and IDEX have adopted this model. A user submits their buy or sell order to the order book, a counterparty submits the other side of the trade, the smart contract confirms the funds are available to trade, and the trade is executed.

AMMs are the dominant DEXs. AMMs are robotic market makers that can provide immediate liquidity for any token through liquidity pools and a pricing algorithm 24/7. They’re blockchain native market makers as their pooled token inventory and pricing algorithm live on-chain.

AMMs are defined by three features:

✔  Liquidity providers depositing tokens in liquidity pools

✔  Liquidity pools comprised of token pairs

✔  A constant function algorithm to price tokens in the pools

Liquidity pools are smart contracts that lock up tokens and facilitate trading between them. Users can swap pool tokens according to the smart contract rules, instead of relying on centralised order books and market makers.

In the order book model, traders can set limit prices for a trade to execute at a predetermined price in the future if the market price hits that value, giving them complete certainty about what they’ll pay. AMMs only allow traders to specify the slippage they’re prepared to tolerate, which still leaves some price uncertainty.

Market makers must be able to quote exchange prices for trading their assets based on how much the trader wants and the market maker’s inventory. Rather than price following whatever market makers are willing to buy or sell at, AMMs use pricing algorithms that automatically adjust token prices in response to every trade in the pool based on a set of rules. These algorithms create pricing curves where each point on the curve is a different marginal exchange rate for the tokens in the pool.

Different algorithms suit different assets depending on the relationship between them. The main AMMs (Uniswap, Curve, and Balancer) are constant function market makers (CFMMs). CFMMs continually adjust the price of tokens in the pool after every trade so that the reserves produce a constant value.

Anyone can become a liquidity provider (LP) by depositing tokens in a pool, so the benefits of market-making are no longer confined to big institutions and traders, like in order exchanges.

In return for providing liquidity, LPs receive LP tokens which earn them a proportionate share of the fees from trading in the pool.

Uniswap, Curve, and Balancer have put different spins on the AMM model, so let’s explore each one.

Uniswap

Uniswap is the leading AMM launched in November 2018. LPs deposit equivalent values of two tokens to a liquidity pool based on their exchange rate and get LP tokens back. LPs are incentivised to deposit equivalent values of both tokens. If not, they could be immediately arbitraged by traders.

Traders can swap any token they hold by finding a liquidity pool with that token and the one they want to receive. In return, they pay a small trading fee, distributed proportionally to the LPs for that pool.

Uniswap started only swapping ETH pairs, but now any ERC20 tokens can be traded directly.

Two smart contracts drive Uniswap’s operations. The “factory” contract adds new tokens to the protocol by creating a new smart contract for each unique token pair. The “exchange” contract facilitates all token swaps.

Uniswap uses a constant product pricing algorithm. Token pairs are priced so that Uniswap’s post-trade volumes of tokens x and y multiplied together always produce a fixed constant: token x volume * token y volume = k (constant value).

Pool token prices are driven by their ratio. Swapping for a token reduces its volume in the pool. The bigger the swap as a proportion of the size of the pool (the more it takes the pool out of balance), the more expensively the pool will price the swap, and the more of the other token the user will need to pay to make it. This is just supply and demand: a greater supply of a token reduces its price, scarcer supply drives up its price. Bigger pools can absorb bigger swaps with less price movement for a better user experience.

Trades that take the pool further away from equilibrium get progressively more expensive, while trades that take the pool from imbalance closer to equilibrium are underpriced relative to the real exchange rate of the tokens to incentivise rebalancing.

Since the constant product pricing algorithm continually adjusts token prices to demand, Uniswap pools can provide liquidity for any size trade. Nobody can drain a token completely from a pool because it would be prohibitively expensive.

CFMMs need to maximise the efficiency of the capital deposited by LPs. Capital efficiency just means producing a higher return on the same initial investment.

In previous versions of Uniswap, only a fraction of the assets in liquidity pools were available for trading at a given price. All the liquidity in pools was equally distributed along the price curve between zero and infinity. Most tokens trade in a narrow price range, so much of the liquidity was idle and wasted. For example, USDC/DAI predominantly trades between $0.99 and $1.01, but in Uniswap v1 and v2 only 0.5% of capital in the liquidity pool was used for that range, so LPs were missing out on significant fees from the bulk of trading.

Uniswap’s latest v3 introduced concentrated liquidity. LPs can now allocate their deposits to specific price ranges that they think will yield the highest fees. V3 creates individualised price curves for each LP. Users trade against the combined liquidity supplied by all the individual price curves covering the current price. If the current price moves outside the LP’s range, they can adjust it to avoid missing out on fees. Rational LPs will always do this, so there’s little risk of no liquidity being available if prices move significantly outside their expected trading range.

The capital efficiency improvements are enormous. LPs can invest less capital but still provide the same liquidity depth as v2 at the most active points in the price curve.

Before concentrated liquidity, Uniswap LP tokens were ERC20s. Now that LPs can create their own price curves, their positions are no longer fungible, so they’re represented by NFTs (ERC721 tokens). Each token pool can have different fee tiers, rather than a standard fee across the whole protocol, to reflect the varying risk of token pairs.

We said earlier that AMMs don’t permit limit orders (where traders specify a price and the trade is automatically executed if that price is met in the future) and only allow traders to set price slippage, which leaves uncertainty about the final execution price. Uniswap v3 offers range orders which approximate limit orders as traders can provide a single token as liquidity within a specific range and the trade is executed if the target token price crosses the full range of the order.

Uniswap is governed by the UNI token, which gives holders the right to propose and vote on new developments. Most UNI tokens are distributed to users of the protocol.

AMM economics

LPs make money in AMM pools from fees and lose money from impermanent loss.

Impermanent loss is unique to AMMs, and not an issue for order book DEXs. It describes when LPs incur a temporary loss compared to the return they would have earned if they hadn't deposited their tokens in the liquidity pool and just held onto them.

The loss occurs when the price difference between two tokens in a pool diverges from when the LP entered the pool. The bigger the divergence, the greater the impermanent loss. Prices staying the same, or at least moving in the same direction, is good for LPs, and divergence is bad.

Impermanent loss creates a correlation spectrum: the more correlated the token pair, the better the profit prospects for LPs; while the less correlated the token pair, the worse the profit prospects.

Let’s zoom in on how impermanent loss unfolds.

AMM pricing algorithms ensure token prices respond to supply and demand in the pool. Discrepancies may emerge between token prices in the pool and their prevailing market prices. If the price of one token in a pool diverges from its market price, arbitrageurs will seek to exploit the delta either by buying the token from the pool (if it’s less than the market price) or selling the token to the pool (if it’s higher than the market price).

If arbitrageurs buy more of a token from the pool, the price will eventually increase to parity with the market price, and they’ll stop buying it. Whereas, if arbitrageurs sell more of a token to the pool, the price will decrease to parity with the market price and they’ll stop selling it.

The larger the weighting of a token in the pool, the less the potential impermanent loss because there’s increasingly less difference between holding the token and depositing it in the pool.

Arbitrageurs are the “smart money.” By exploiting mispricings, they regulate pool prices. They’re only willing to pay less than the true value of a token, which undercuts the fee paid on their trade. Retail traders pay above the true value and are where LPs earn their fee spread.

It’s called impermanent loss because the loss is only on paper until the LP withdraws their liquidity from the pool. If they don’t withdraw and the token prices reconverge, the loss is reversed. But if the LP withdraws their tokens before prices realign, it becomes a permanent loss.

Curve

Curve is a competing AMM that focuses on trading like assets to minimise slippage and impermanent loss.

V1 of the protocol was stablecoin pools, and v2 launched crypto pools for differentially priced (but still like) assets, such as wrapped BTC and ETH tokens.

Similar to Uniswap v3’s concentrated liquidity, crypto pools concentrate liquidity at current trading prices. Whereas in Uniswap v3, LPs need to readjust their liquidity range whenever token prices move outside it, in Curve v2, crypto pools automatically readjust the range for allocating liquidity via an internal oracle.

Uniswap’s constant product pricing algorithm isn’t suitable for similarly priced assets. Curve uses a hybrid constant product and constant sum function trading multiplication for addition, so token x + token y = k (constant value).

Curve has different pool types: plain, lending, and metapools. In plain pools, all assets are ERC20 tokens, and LPs earn a share of the pool’s trading fees. With lending pools, LPs earn interest from lending their tokens, on top of trading fees. Interest not paid out to LPs gets reinvested in the pool to generate more interest. In metapools, tokens in one pool can be traded with the LP tokens of another base pool, which means the tokens in the base pool can be traded without adding more tokens to that pool and diluting them. LPs can earn more trading fees by depositing their LP tokens in the metapool. The underlying tokens in the base pool are still tradeable, not only the LP tokens.

Anyone can create liquidity pools through the Curve factory or become an LP of an existing pool by depositing one or all of the tokens in the pool. If an LP deposits one token, it gets split across the other tokens, so they’re exposed to all of them. Depositing the smallest coin in the pool earns the LP a deposit bonus.

CRV is the native token for CurveDAO, which runs the protocol. It’s distributed to LPs and used to align their incentives with the long-term interests of the protocol.

CRV has three functions - voting, staking, and boosting - which LPs can only access by vote-locking their CRV in exchange for veCRV (vote-escrowed CRV). LPs can lock up their CRV for one week to four years, but the more they lock and the longer they lock it up for, the more veCRV they receive. Locking is irreversible, so once the holder has locked up their CRV, they can’t withdraw them until the vote-locking period expires. veCRV can’t be transferred, and it can only be obtained by locking up CRV.

veCRV holders can vote on CurveDAO proposals and pool parameters and receive boosted rewards by getting half of all Curve trading fees (the other half go to “normal” LPs). These fees are aggregated and used to buy 3CRV (the LP token for the DAI, USDC, and USDT TriPool), then distributed to veCRV holders. LPs can boost themselves or do it through the yveCRV and yvBOOST vaults on Yearn (more later).

Every Curve pool has a liquidity gauge measuring how much liquidity LPs are providing, and the gauge has a weight representing how much of the daily CRV inflation it receives. veCRV holders vote on the distribution of CRV to different pools, so they can boost their earnings by directing more CRV rewards to their pools.

Balancer

Balancer is an AMM with two sides: liquidity pools and a trading platform.

The Vault smart contract holds and manages all tokens in Balancer liquidity pools and acts as the portal for users to join, swap, and exit. Token inventory and accounting are managed by the Vault. Each pool has unique logic for how its tokens can be traded.

Concentrating liquidity in the Vault means multiple trades can be executed in one or multiple pools, but only the final net token amounts are settled. This produces greater gas efficiency because tokens aren’t transferred on each swap, and the Vault just updates token balances. For example, token a > token b > token c > token d could be done in one batch swap. The Vault also enables flash loans and arbitraging price differences between pools without holding any tokens. Even though all tokens are stored in the same inventory, pool balances are independent, and the price behaviour of one pool doesn't affect others.

Balancer’s liquidity pools are more flexible than other AMMs as the tokens, fees, and logic are customisable. Anyone can create a new pool using existing pool types or from scratch by defining the criteria for joining, exiting, and trading with the pool.

Let’s quickly look at the different template pool types:

✔  Weighted pools are used for general trading, including uncorrelated tokens. They can hold up to eight tokens with any weighting, not just 50/50 like other AMMs. More tokens mean more potential trading pairs and more fees

✔  Stable pools are used for soft-pegged tokens that trade around a similar price region, such as stablecoins and synthetics because they minimise slippage

✔  MetaStable pools are an extension of stable pools designed for correlated but non-pegged tokens

✔  Liquidity bootstrapping pools enable the pool creator to keep adjusting the token weightings

✔  Managed pools are designed for managing funds with up to fifty tokens with weight shifting and swap pausing mechanisms

The Balancer Smart Order Router ensures traders get the best price by scanning all pools for the cheapest way of structuring trades. This can be via a single swap or a batch swap across multiple pools. The cheapest pools will be the ones with the most divergent price and token distribution. Once it’s found the optimal route, the router executes the trade through the Vault. This is a win-win for traders and LPs: traders get the best price possible, and pools with divergent prices are rebalanced.

Different pools use different pricing algorithms. Weighted pools, liquidity bootstrapping pools, and managed pools use a weighted generalisation of the constant product formula that allows for more than two tokens and unequal weightings. Stable pools and metastable pools use a stable maths equation, which combines the constant sum and constant product functions and facilitates 1-1 trades where significant slippage only occurs when there’s a big difference in token balances.

LPs receive Balancer Pool Tokens (BPTs) in return for providing liquidity. All trading fees are paid into the pool and accrue to the BPTs. As well as distributing trading fees to BPT holders, the protocol can also retain a portion for Balancer DAO. It currently reserves 10%. LPs also receive weekly allocations of Balancer Governance Tokens (BAL), which carry voting rights.

Balancer has a token staking system similar to Curve’s veCRV. veBAL (vote-escrowed BAL) is acquired by providing liquidity to the 80/20 BAL/WETH pool, then staking the BPT received. veBAL holders get more voting power, including the right to vote on liquidity mining distribution from gauges, and 75% of trading fees collected by the protocol. BPT can be staked from one week up to one year. The more and longer BPT are staked, the more voting power the holder gets.

Gauges are contracts that allocate liquidity mining rewards. Liquidity mining rewards are provided by Balancer and its partners as an added incentive to draw liquidity to certain pools. Every pool eligible for liquidity mining has a gauge. For LPs to benefit from it, they must stake their BPT there.

Automated lending and borrowing

Lending and borrowing are ancient money verbs. TradFi orchestrates them around “money markets” run by centralised banks or peer-to-peer fintech firms.

DeFi lending and borrowing protocols enable users to lend and borrow tokens through automated smart contracts. Lenders and borrowers interact with a smart contract, so they don't have to negotiate terms like the loan value, maturity, and interest rate.

Lenders deposit their tokens in a protocol and earn passive income from the supply APY. The protocol aggregates the supply of deposited funds in a pool, giving lenders more liquidity because they don’t have to wait for a loan to mature to withdraw their deposits.

When lenders supply tokens, they receive native ERC20 tokens from the protocol redeemable for the deposited tokens at any time. Interest accrues to lenders through the ERC20 tokens and is added to the outstanding loan balance for the borrower to repay.

Borrowers deposit tokens as collateral and can receive a loan in seconds.

Lenders earn higher rates on their deposits than savings accounts, and borrowers still pay lower fees than TradFi because they have access to a competing global supply of lenders, retain custody of their funds, and save on taxes by securing capital without selling assets.

Most lending and borrowing protocols offer variable rates based on the supply and demand of the token. High demand for a token reduces its liquidity, so interest rates rise to incentivise supply and disincentivise borrowing. Low demand decreases interest rates to discourage supply and create more borrowing demand. The challenge with variable rates is they reduce certainty for lenders and borrowers about how much they earn or pay, so some fixed products have emerged to fix this.

Borrowers’ ability to take out loans in DeFi is shaped by two factors:

✔  Token supply available to borrow, relative to demand

✔  Collateral requirements

More token supply in a protocol creates liquidity and reduces the APY for borrowing that token.

DeFi protocols have relied on overcollateralised loans, where borrowers have to lock up tokens greater in value than what they borrow so that lenders are guaranteed to get repaid, even if the borrower runs out of money.

Protocols have different collateral factors - the maximum amount that can be borrowed against collateral - depending on its quality. If the outstanding loan balance exceeds the amount permitted by the collateral factor, the protocol automatically liquidates the collateral. This could happen when the collateral depreciates or the borrowed token appreciates.

On liquidation, collateral is sold to buy back the token owed to the lender. Most DeFi loans have an indefinite maturity as long as the outstanding balance stays below the collateral factor, so the borrower can repay whenever they want.

Overcollateralisation has helped bootstrap DeFi by giving lenders confidence to lend with no default risk, but it inherently limits who can use it.

With overcollateralisation, only users with capital can borrow more. Borrowing is mostly for leverage on trading and short selling. Most of the world needs to borrow because they don’t have capital. In TradFi, borrower creditworthiness is assessed through the “Five Cs” of character (borrowing history), capacity (debt-to-income), capital (available liquidity), conditions (loan value and APY), and collateral. In overcollateralised loans, all the focus is on collateral and loan conditions. Overcollateralisation also traps excess capital in protocols that could be earning returns elsewhere.

For DeFi to go mainstream, undercollateralised loans - backed by some or no collateral - are needed. These will make DeFi more inclusive, boost lending APYs to compensate for increased risk from lack of collateral, and free up idle capital to earn returns.

There are three main categories of undercollateralised loan products: flash loans, third-party risk assessments, and crypto-native credit scores.

In flash loans, funds are borrowed and repaid simultaneously in the same transaction, so there’s virtually no default risk. Use cases are predominantly limited to arbitraging price discrepancies between exchanges with leverage, swapping collateral, and self-liquidation to repay a loan and claim back collateral before a protocol takes it.

Third-party risk assessments enable undercollateralised lending by introducing a group of credit assessors who determine the risk appetite of the protocol and vouch for borrowers. Users qualify as credit assessors by staking a certain amount of tokens. If the borrower defaults, credit assessors who approved the loan get their collateral slashed. If the loan is repaid, they receive a reward. The challenge is scaling a network of risk assessors with sufficient data and tools to make credit decisions and stand behind borrowers.

Crypto native credit scores aim to leverage users’ on-chain activity history to determine their repayment abilities. Activity will need to connect to real-world identity. Otherwise, users with poor credit scores could apply for new loans with different wallets. Probably, zero-knowledge proofs will be used to tie credit scores to real-world identity without revealing the borrower’s identity to lenders.

Other undercollateralised products include off-chain integrations incorporating off-chain data into lending assessments, personal network bootstraps where lenders invite borrowers to join an eligible pool, real-world asset loans using non-crypto asset collateral represented on-chain as NFTs, NFT-collateralised loans, and digital asset loans where lenders retain custody of the purchased asset until they're repaid.

Now let’s turn to the two biggest DeFi lending and borrowing protocols: Compound and Aave.

Compound

Compound pioneered automated lending and borrowing in DeFi.

Users deposit their tokens in the protocol and earn interest by lending them to borrowers. Lenders receive cTokens based on an exchange rate representing their supplied tokens plus interest over time. The exchange rate depends on the supply APY.

Interest accrues every new block added to the blockchain while the lender’s deposits are locked in the protocol. As interest accumulates, the lender’s exchange rate on their cTokens increases, so on redemption they get back more of the underlying tokens than they deposited.

Borrowers lock up tokens as collateral which earn interest but can’t be redeemed as long as their loan is outstanding. Loans are closed when the borrower repays the lent funds and accrued interest. Interest is the borrow APY and increases each block. The borrow APY is usually higher than the supply APY because not all supplied tokens are “utilised” for lending. Nonetheless, they still earn interest, so the borrow APY needs to be higher to ensure all lenders get a return even when their tokens aren’t lent.

Part of the interest paid by borrowers is set aside as reserves for insurance controlled by COMP token holders.

If the outstanding loan value is greater than the amount allowed by the collateral factor, automated bots called “keepers” liquidate the loan by buying the collateral at a discount to the market price and converting it to repay the lender.

COMP token holders run the protocol. Users receive the tokens through liquidity mining, and, in return, they can propose and vote on changes to the protocol.

Compound Labs (the originating team) has also spun up Compound Treasury and Gateway. Compound Treasury works with businesses and institutions to convert their USD into USDC and supply them to the Compound protocol while abstracting away all the complexity of conversion, private key management, and interest rate volatility. Gateway is a cross-chain interest rate market allowing users to borrow the native assets of one chain with collateral from another.

Compound wants to be a developer product. Their vision is to become the base layer lending and borrowing protocol integrated with applications. Future users shouldn’t know Compound exists because it’s hidden behind the user interface.

Aave

Aave differs from Compound in two main ways:

✔  Lenders receive aTokens pegged to the tokens they deposit 1:1, so interest is paid by delivering them more aTokens

✔  Borrowers can access stable (not just variable) rates

Aave has also led the way in uncollateralised lending by pioneering flash loans and a credit delegation product for depositors to “delegate” their collateral to other users to borrow against, so it can earn additional returns rather than sitting idle.

With Aavenomics, Aave users receive AAVE tokens giving them the right to participate in governance by making and voting on proposals. AAVE tokens can be staked in the Aave Safety Module in return for more tokens and a share of protocol fees. Holders can either stake their AAVE tokens directly or provide the liquidity tokens from the AAVE/ETH Balancer AMM pool.

The Safety Module defends against shortfall events which cause lenders to lose money (like a smart contract bug, liquidation risk, or oracle failure) by selling up to 30% of the staked AAVE. If Safety Module reserves aren’t sufficient to cover the deficit, there will be a Recovery Issuance of AAVE tokens, and a backstop module would maintain an ongoing bid to keep them above a certain price.

Borrowers receive debt tokens when they initiate their loan and they’re burned on repayment. Debt tokens are modelled on ERC20, except they’re non-transferable, so they omit the transfer and allowance functions.

Every Aave borrower account has a “health factor.” Accounts get liquidated when this goes below 1. Other users can make a liquidation call on the loan and receive discounted collateral (or an equivalent amount of collateral aTokens, if they prefer) in return. The health factor is calculated as the borrower’s collateral balance (in ETH) * the current liquidation threshold for all the borrower’s outstanding assets / the borrower’s total borrowed balance (in ETH).

Automated Investment Strategies

Automated investment strategies help users find the highest yield opportunities in DeFi. Given its nascency, DeFi is still incredibly inefficient, and there are rich pickings for alpha. The catch is that identifying these opportunities is easily a full-time job, so automated investment strategies simplify the process by delegating it to code.

Yield farming is the process of maximising profits in DeFi by continuously allocating capital to the highest returning protocols. It draws on different strategies across DeFi, including lending, borrowing, providing liquidity, and staking to achieve the highest possible returns.

If a protocol starts offering subpar returns compared to others, the yield farmer will make a “crop rotation” by moving their tokens to another one.

Protocol returns are shaped by liquidity mining, leverage, and risk. Liquidity mining is where protocols distribute tokens to their users to incentivise them to keep providing liquidity to the protocol. Leverage is using debt to amplify returns as the user can buy more of a token than if they only used their capital. Risk comes from the possibility of being liquidated, smart contracts breaking, and protocol attacks.

This is a bit nebulous, so let’s jump into Yearn.

Yearn

Yearn was one of the first automated investing protocols. It’s a yield optimiser that maximises returns for depositors by switching their funds between different DeFi protocols.

Yearn started by helping users lend their stablecoins to the highest returning protocols, but as yield farming and liquidity mining made earning yield more complex, yVaults were developed.

yVaults are pooled funds of crypto assets deployed to different strategies. Each yVault can have multiple strategies voted on by the Yearn community. Depositors in the pool benefit from socialised gas costs and passive yield generation and rebalancing. They pay a 2% fee for general overheads and 20% on profits.

Like everything else in DeFi, yVaults are open, so other protocols and applications can build on top of them. Partners typically use yVaults as collateral for lending, borrowing, or generating a yield on their users’ funds, and they receive some of the vault’s performance fees.

Deposited funds go to the vault contract, and then get deployed to one or more strategy contracts. Users receive ERC20 yVault tokens representing their share of the vault. As the yVault generates profits, yVault tokens appreciate because there are more underlying tokens in the vault to redeem on withdrawal. Users can exit the vault at any time by burning their yVault tokens.

Anyone can become a strategist by creating a strategy for a yVault and passing a vetting process. Guardians and strategists monitor yVault returns and manage any crises.

Most funds in yVaults are invested in a strategy, but some idle amount is retained. When users withdraw their tokens from the vault, they’re deducted from the idle amount with no charge. If there’s no idle amount left, they’re taken from the deployed funds with a withdrawal fee.

“I have access to all the same protocols as Yean does. Couldn’t I just do this myself?”

Fair questions.

Yearn has three edges. The first two apply to all vaults, and the last one is specific to Curve-linked vaults.

First, batching transactions together in the pool spreads gas fees over a high volume of users, reducing per-user costs. Second, Yearn magnifies returns with leverage from Iron Bank.

The last one is more complex. Read this slowly.

Yearn has yveCRV and yvBOOST yVaults that magnify staking rewards on CRV tokens, compared to what users receive staking in Curve directly.

Several Yearn vaults provide liquidity into Curve pools.

Yearn has a yveCRV vault (otherwise called the “Backscratcher” vault) where depositors lock up their CRV tokens and get back yveCRV for a share of Curve’s trading fees. Users of the vault delegate their voting power on the veCRV tokens to Yearn, and Yearn optimises this voting power to maximise rewards in all of Yearn’s Curve pool vaults. Yearn locks 10% of the CRV tokens it earns from Curve-based strategies across all vaults into the yveCRV vault, so depositors in that vault earn Yearn’s share of Curve trading fees, giving them more than double the rewards they’d get if they staked in Curve themselves. The remaining 90% of CRV tokens Yearn earns are re-deposited in the vault (excluding the yvUSDN3Crv vault that locks 50% of earned CRV into the Backscratcher vault and swaps the remaining 50%).

On top of this, Yearn has a yvBOOST vault for users to reinvest and compound the trading fees they earn in the yveCRV vault. The yvBOOST vault automatically claims users’ 3CRV rewards and uses them to acquire more yveCRV tokens by purchasing them on the open market or minting them. Yearn also buys yvBOOST tokens on the open market, unwraps them into yveCRV and adds them to the yvBOOST vault to increase the underlying value of yvBOOST.

CRV tokens in yveCRV and yvBOOST vaults can’t be withdrawn. Users exit the vaults by swapping their yveCRV and yvBOOST tokens on SushiSwap, where Yearn provides liquidity.

Yearn users control the protocol through the YFI governance token. Distribution of YFI was one of the fairest in crypto, as it went exclusively to users of the protocol, with no pre-mine and no team or investor allocation. YFI holders can propose and vote on changes to the protocol, as well as earn a small fee for participating.

Phew, that was a lot. Time to close this out.

Thanks for reading

Hopefully, this has helped you understand DeFi better! Please shout if you think I missed anything :)

One thing I’ve taken from writing this is the importance of reading whitepapers and developer docs. There’s no substitute for them! You can read 50 different articles about a protocol, or spend a few hours digging into their documentation to understand them from the bottom up.

I’m just a guy writing to test his understanding of DeFi. It’s risky and none of this is financial advice. DYODD.