4. Decentralised Finance#
This tutorial is meant as an introduction to DeFi and covers the main platforms that are present in the world of DeFi. There is an initial overview of stablecoins, and some stories of spectacularly large implosions of stablecoin platforms - to illustrate the importance of using caution in the world of crypto. We will then talk about decentralised exchanges and the ways in which it is possible to swap between different coins, in a way that is not quite peer-to-peer but certainly isn’t centralised/traditional either. This tutorial then discusses how to optimise currency swaps using order routers (which are basically open source arbitrage bots) and how blockchains can learn information that is not already on the blockchain. Next, we will introduce a single decentralised exchange protocol, offering a concise guide on how to use it. Finally, we will conclude with a discussion on decentralised governance and provide a brief overview of lending protocols.
Stablecoins#
Since we’ve already touched on the topic of swapping currencies, let’s delve into stablecoins. Stablecoins belong to the category of tokenised real-world assets, designed to represent fiat currencies in the blockchain environment. In essence, they are digital coins pegged to stable assets from the real world, such as the US dollar. This brings us to a clarification regarding a statement made in the first tutorial: ‘it’s impossible* (with caveats) to hold fiat in the crypto world.’ When you purchase a stablecoin, you aren’t technically holding fiat, as stablecoins can only be redeemed for fiat. However, they do allow you to have exposure to fiat currencies without leaving the DeFi ecosystem. The significant advantage of this is that it provides a natural way to exit volatile cryptocurrency positions. Instead of going to a centralised exchange to swap your crypto for fiat, you can simply exchange it for a stablecoin on a decentralised exchange (which we’ll discuss in more detail later).
There are three main ways that have been in use to help stablecoins keep their peg. The very first one was algorithmic; The creators of these smart contracts aimed to regulate and control the supply of their stablecoin by implementing intricate market-based mechanisms. Their goal was to ensure that the stablecoin’s price on the open market closely matched the price of the asset they were pegged to, often the USD. The first-ever stablecoin, BitUSD, fell into this category. However, a significant drawback that led to the downfall of many algorithmic stablecoins is their susceptibility to catastrophic failures. When one part of the system breaks, it tends to trigger a chain reaction, often resulting in a rapid loss of value for the stablecoin. This situation frequently benefits the individuals responsible for the collapse, turning them into overnight millionaires, while leaving other users with a worthless digital representation on their screens. It’s challenging to provide a comprehensive overview of algorithmic stablecoins because as one fails, a new one often emerges, claiming to have resolved the flaws that led to the demise of its predecessor.
Famous algorithmic stablecoins that failed can count among their ranks: BitUSD (the original stablecoin), but also much more spectacular failures like the explosions of the ‘Iron Finance’ stablecoin which went from a market cap of $2 billion, to basically zero in less than a day. See below for details, if you are interested:
Iron Finance Post-Mortem 17 June 2021
Pictured above is the price chart of the TITAN token, which was supposed to help keep the price of the IRON stablecoin stable.
Even more spectacular was the Terra stablecoin ecosystem collapse. Terra wanted to be a system of algorithmic stablecoins, with one stablecoin for every fiat currency imaginable. Unfortunately for them and their bombastic CEO, the Terra USD token de-pegged and fell to 4 US cents in a day after a series of slight de-peggings in the previous few days, wiping out more than $18 billion worth of market capitalisation.
The Fall of Terra: A Timeline of the Meteoric Rise and Crash of UST and LUNA
Pictured above is the market cap of Terra
Understandably, today’s world of crypto is incredibly sceptical of any algorithmic stablecoins. Which brings us to the second type of stablecoin, the fiat backed stablecoin. The logic is simple, if you hold about $82 billion worth of assets in some bank somewhere, and promise anyone who uses your coin that you will redeem one coin for one dollar, and enough people trust you to keep your promise then you’ve got yourself a stablecoin, like Tether.
Tether market cap over time
When the price of a stablecoin drifts too far from its intended peg, arbitrageurs step in to ensure it returns to its intended value. They do this by either redeeming or minting coins.
However, if you make the mistake of storing your reserves in a poorly diversified location, such as Silicon Valley Bank, you may find yourself on the brink of collapse. This scenario became a reality when approximately $3.3 billion of USDC reserves temporarily vanished, highlighting the risks associated with inadequate diversification.
In the picure above the sharp fall and quick recovery of the price of USDC was a direct result of them storing some of their assets at SVB
USDC’s Depeg Laid Bare the Risks Traditional Finance Poses to Stablecoins
These examples highlight the somewhat impossible tri-lemma of stablecoins; you can have two of the three - capital efficiency, decentralisation or price stability. Algorithmic stablecoins are capital efficient and decentralised, often having very little reserves (if any) to back the stablecoin. Where they fall short is the ‘stable’ element of the stablecoin. Asset backed stablecoins achieve relative price-stability and decent capital efficiency, with one stablecoin backed by just slightly more than one dollar in reserves (see the 2023 USDC Circle Examination Report June 2023).
But this means that there’s a single centralised entity managing those reserves. And this somewhat goes against the mantra of decentralisation, and self-custody of assets.
There is a third and final category of stablecoins, which combine decentralisation and price stability, but fall short on the matter capital efficiency - these are crypto backed stablecoins. This category is less common than the fiat backed stablecoin, and most examples are either very small and in testing phases, like sUSD by Synthetix or crvUSD by Curve, or they’re heavily exposed to a centralised entity, like the biggest crypto backed stablecoin DAI, with over $5 billion in market cap - but the four largest pools of reserves are managed by a centralised entity.
Monetalis Clydesdale and BlockTower Andromeda may sound cryptic, but they refer to US treasuries and corporate bonds managed by centralized entities. The PSM (price stability mechanism) is a system that uses USDC or GUSD, both centralized entities, as collateral. Coinbase, on the other hand, is one of the largest centralized cryptocurrency exchanges. Collectively, these entities control over 21% of the DAI stablecoin reserves. While this diversifies control, it falls short of the fully decentralized ideal.
The concept behind crypto-backed stablecoins is to replace fiat currency reserves with cryptocurrency reserves. However, since cryptocurrencies are inherently volatile, you must deposit more than one USD worth of cryptocurrency to generate one USD worth of stablecoin.
DAI and most DeFi protocols operate using liquidity pools, which are pools of assets where users can deposit one type of asset and receive another in return. In this context, each line in the screenshot represents a different asset pool, serving as the reserve for the DAI stablecoin. Users can deposit assets into these pools, as long as they’re not at capacity, and borrow DAI in return. To make this work, the value of the deposited assets in USD must exceed the value of DAI borrowed by some constant ratio. Borrowers also pay interest on their DAI debt to the platform, which is deducted from the nominal value of their deposited assets.
For instance, consider the stETH Low fee pool (5th from the top) on the screenshot. This pool accepts stETH, a tokenized version of Ethereum (for more detail on what stETH is, look into staked ETH and liquid staking). The “175%” below the pool’s name signifies that for every USD worth of DAI borrowed, a user must deposit at least 1.75 USD worth of Ether as collateral. Falling below this collateral limit allows anyone to repay part of the debt and seize some of the deposited assets as compensation, with an added incentive to seize slightly more assets than the debt’s value. This overcollateralization and liquidation process is a common feature in DeFi.
The most widely recognized and trusted stablecoins include USDT (Tether), USDC (Circle USD), DAI (MakerDAO), BUSD (Binance USD), and TUSD (True USD).
Decentralised exchanges#
Now, let’s shift our focus to where you can actually trade between different cryptocurrencies. We’re already familiar with centralized exchanges, or CEXs, but now let’s explore their decentralized counterparts, known as DEXs, or decentralized exchanges.
In traditional finance, over-the-counter markets rely on prices set by incoming bids and asks. However, sending this kind of data to the blockchain would be incredibly expensive. Given the high cost of storing information on the blockchain, maintaining a conventional order book isn’t feasible. Instead, decentralized exchanges utilize something called automated market makers, or AMMs for short.
In the simplest scenario, where two assets are being traded against each other, such as wrapped Bitcoin (wBTC from tutorial 2) and Ether (ETH), they form a single “liquidity pool.” The most common AMM function used to determine prices in this market is the constant product market maker. This function operates by maintaining the product of the quantities of the two assets in the pool as constant. Consequently, the price is determined by the relative abundance of one asset compared to the other.
The equation would be \(x \cdot y = k\), where \(x\) is the quantity of one asset, \(y\) is the quantity of the other asset and \(k\) is a positive real number. The relative price of \(y\) in terms of \(x\) is \(\frac{y}{x}\), which means that one unit of \(x\) will be able to be traded for \(\frac{y}{x}\) units of \(y\). Yet this price only holds if the trade is infinitesimally small. The actual execution price will be slightly different; the larger the amount traded, the larger the difference will be. This is called “slippage” or in more traditional finance jargon, price impact.
See below for more detailed maths
A fuller (but still not quite what is used in practice) equation is given by
\[ (x+\Delta_x)\cdot(y-\Delta_y) = k \]Where \(x\) represents one asset, \(y\) represents the other asset, \(k\in \mathcal{R}^+\) is a positive real number. If we are swapping asset \(\Delta_x\) of asset \(x\) for asset \(y\), then we will be given \(\Delta_y\) of asset \(y\) in return. Therefore, the price of asset \(y\) in terms of asset \(x\) is given by \(\frac{\Delta_y}{\Delta_x}\). As an example, if the liquidity pool contains 10 ETH and 1 wBTC and \(k\) is set to be 10. From this we might suspect that one ETH should be worth one BTC. Yet if we actually do the calculation in a trade of one ETH for BTC, then \(\Delta_x = 1\) and \(\Delta_y = 1-\frac{10}{11} = \frac{1}{11}\) and thus you will be given one eleventh of a Bitcoin in return and the relative price is one ETH is worth \(\frac{1}{11}\)wBTC rather than \(\frac{1}{10}\) as we initially might have thought. Further after this trade the new market price would be \(\frac{10}{11}\div 11 = \frac{10}{121}\)wBTC for one ETH as wBTC is now relatively more scarce.
Now for another experiment, say the ratios are again 10:1 and we only exchanged 0.5 ETH. You would be given \(\frac{1}{21}\)wBTC in return. But we have that \(\frac{1}{11} = \frac{2}{22} < 2\cdot\frac{1}{21}\). So we are getting more wBTC for a single unit of ETH. The truth is the price is 1 ETH for \(\frac{1}{10}\)wBTC, but only if you trade an infinitesimally small amount of ETH. As your trade gets bigger you experience more and more of what is called in crypto jargon “slippage”, where your actual price differs from your quoted price. This discrepancy would be much lower if the amount of liquidity available in the pool was higher, e.g. if there were 100 ETH and 10 BTC in it instead. In traditional finance jargon, this would be analogous to the price impact of your trade.
You might be wondering how a liquidity pool initially accumulates liquidity. The straightforward answer is that individuals deposit the tokens they own into the pool, which can be either ETH or wBTC, or even both. In return, they receive another token known as an LP token or Liquidity Provider token. These LP tokens essentially act as certificates of deposit, granting holders ownership of a specific portion of assets within the pool. This portion can become more concentrated or diluted over time as more people either withdraw or deposit assets into the pool, but the total amount of assets you own in the pool should stay constant and even slowly increase as you earn interest.
The incentive for depositing assets into the pool lies in the opportunity to earn transaction fees from individuals who exchange assets within the pool. Of course, this introduces some complexity into the equation mentioned above, where \(k\) fluctuates as people deposit or withdraw, and we need to include an extra factor for transaction fees (although we’ll skip over that for now). Additionally, there’s the issue of impermanent loss, which occurs when you deposit assets into a liquidity pool, and one of the assets appreciates in price relative to the other. In such cases, you may not fully benefit from the price appreciation of the asset.
Click for mathematical detail on impermanent losses
To illustrate let’s say you deposit 10 USDC (stablecoin) and 1ETH into a liquidity pool and the relative price is $\frac{1}{10}$ETH for 10 USDC. Let’s say you are given 10% ownership of the pool, so in total it contains 100USDC and 10ETH and now ETH quadruples in value relative to USDC. Arbitrageurs are going to come into the market and trade such that there is now 200USDC in the pool but only 5ETH, so when you go to redeem your certificate of deposit, you will now be given 20USDC and 0.5ETH. Which means that you now have $20+0,5\cdot40 = 40$ USD worth of assets, which is a nice profit of 20 USD. Yet, if you had held the USDC and ETH in your wallet instead, you would have $10$ USDC + $1\cdot 40$ USDC worth of Ethereum, or 50 USD worth of assets instead. Hence, you lost out on $10$ USD worth of price appreciation. The reason this is called impermanent loss, is because if if the relative prices go back to where they were before, then this loss is completely mitigated. This also works in the reverse, protecting you from price depreciation instead.
Now let’s look at some big DEXs. The largest ones is Uniswap V3
You can access this feature just like you normally would by connecting your wallet. Please be aware that network fees might be relatively high. However, it’s important to note that the price impact or slippage is negligible. We will delve into order routing later on.
The next largest is Curve:
Unlike in Uniswap, Curve shows you all the individual pools which you can transact in. Notice that curve offers 3 and even 4 asset pools, but doesn’t provide order routing.
The third largest is Pancake swap, which also automatically does order routing rather than displaying the pools individually.
Order routers#
So what, exactly, is an order router? Examining the liquidity pools on Curve gives us some insight into this question; the most diverse liquidity pools contain at most 4 different assets that you can swap with each other. If, for instance, we want to convert the ETH in our wallet to the stablecoin USDC, we can start by utilizing the Curve “tricrypto2” pool to convert the ETH into USDT. From there, we can proceed to use the Curve “3pool” to convert the USDT to USDC. This process seems straightforward enough, but what if we hold a less commonly used coin and wish to convert it to USDC? In such cases, we might need to make three, four, or even more trades, and there could be multiple potential routes within a single DEX’s ecosystem. How can we be sure that we’re choosing the most efficient route to minimize slippage and transaction fees? This is where order routers come into play. UniSwap and PancakeSwap have integrated order routers, but since they are also DEXs, they allow you to provide assets to smart contracts within their ecosystems without the need to select a specific path.
The biggest order router is 1inch, which routes users through all the available DEXs, unlike the Uniswap and PancakeSwap routers - which try and stay in their own ecosystems. We’ve even used an order router before, THORSwap is both a multi-chain DEX and an order router.
On 1inch, DEX prices and centralisation#
Let’s now turn our attention to how to actually interact with 1inch, and then compare it with Uniswap. The official 1inch app is the following:
1inch - DeFi / DEX aggregator on Ethereum, Binance Smart Chain, Optimism, Polygon, Arbitrum
As always, the first thing you want to do is connect your wallet by clicking on the “Connect wallet” button on the top right (on the same browser you installed your wallet extension for). Once that’s done, we can select the pair that we want to swap. Say we want to turn ETH into USDT. If we look at the price (at the time of writing) about 0,0214 Ether was worth about 35 USD. Using the numbers from the screen this gives a price of 1636,43 USD per Ether.
If we carry through the transaction, then 1inch will first ask us to confirm that we are not in the US by signing a transaction with our wallet.
This is because the Securities and Exchange Commission (SEC), the American version of the AMF, has ‘know your customer rules’ that 1inch does not meet (as it only requires your Ethereum address to transact), and it hires staff in the US who develop the project. Once that is done, we can confirm and send our transaction as usual by signing it again with our wallet.
Let’s compare the price offered by 1inch with the price offered by the centralised exchange Coinbase. The price of Ether there is 1639,26 USD per Ether:
If we then compare the price of Ether on Uniswap (which we use in the same way as 1inch, by first connecting our wallet)
We get a price of 25,3678/0,01556993 = 1629,28 USD per Ether. This is the lowest price of the three (most likely since the order routing of 1inch uses Uniswap pools together with pools from other platforms).
Keep in mind that these prices, especially on platforms like Uniswap and 1inch, change rapidly, and there’s no guarantee that you’ll receive the exact amount of assets displayed on the screen. This is because you may become vulnerable to frontrunning and sandwich attacks, particularly when dealing with significant sums of money. So, it’s not always the case that Coinbase will offer the best deal, 1inch the second best, and Uniswap the worst. Therefore, when conducting asset exchanges, it’s advisable to compare all available platforms. Additionally, the discrepancies between platforms become more apparent as the size of the asset swap increases.
If we look closer at the 1inch swap screen:
We can see a field labelled ‘Route’, if we click on it, it brings up a screen showing how exactly your assets were converted.
In this case it’s routed through a single entity called PMM, which means Private Market Maker, as opposed to AMM which stands for Automated Market Maker. PMMs are centralised entities and are functionally the same as market makers in traditional finance. Using PMMs means that 1inch can bypass slippage.
We should note a caveat regarding the order routers discussed here. They operate off-chain and are not truly decentralised. While Uniswap has made its order routing code public, it still maintains its own servers and API for external use, rather than executing these functions directly on the blockchain. (This has also led to many others copying their order routing contract to compete with them for better prices.) In the case of 1inch, they have opted not to release their code as open source, even though it has undergone multiple independent audits. By relying on these order routers, you are still placing trust in centralised entities.
There are also decentralised on-chain order routers available, which offer some unique features, such as the ability to reverse a transaction if it falls outside your desired price range. They are also less susceptible to frontrunning or other types of attacks. However, these on-chain routers have limitations in terms of flexibility. They are not as efficient as off-chain DEX aggregators and order routers and can only handle a few different exchanges at once. This is because on-chain computation is resource-intensive, and order routers must calculate hundreds or even thousands of potential paths to determine the best one.
Oracles#
Before we dive back into Curve and explore decentralised exchanges (DEXs) further, it’s crucial to discuss oracles. As mentioned at the beginning of this tutorial, a smart contract can only access information that resides on the blockchain. This limitation poses a challenge when you want to obtain real-world data, like the price of gold.
Consider a traditional legal contract where Organisation B commits to paying Person A for a project. You can certainly encode this contract into a smart contract, deposit the agreed-upon payment, and set it to be automatically transferred to Person A upon project completion. However, there’s a critical issue: the smart contract has no means of verifying whether the job has been completed. Without external input, the money will never get transferred. Oracles are designed to address this challenge by bringing “off-chain” data onto the blockchain.
In crypto terminology, oracles act as bridges between off-chain and on-chain data. In the example above, the off-chain data could be a letter from Organisation B confirming the receipt and satisfactory completion of the project. While it’s possible for Organisation B to serve as its own oracle and confirm to the smart contract that the job is done, this approach contradicts the principles of decentralisation that underpin cryptocurrencies.
Enter decentralised oracles, such as Chainlink, The Band Protocol, The UMA Protocol. If you want to read how they work, find an article on Chainlink and Chainlink’s whitepaper below. We won’t address them again, but it’s good to remember that these are like hidden workhorses of DeFi.
What Is Chainlink? Oracles, Nodes and LINK Tokens | Gemini
Chainlink 2.0 and the future of Decentralized Oracle Networks | Chainlink
Using Curve#
Now turning our attention back to Curve, let’s work through what everything means and how to use it for both trading and depositing your assets. Starting with ‘how to deposit’.
When depositing you want to consider a few things; first, how likely are you to experience impermanent loss? Do you want exposure to all currencies in the pool? What kind of fees can you earn? Let’s first focus on vAPY:
vAPY, or variable APY, represents the annual fees you earn when individuals trade on the pool where you’ve deposited your tokens. These fees are distributed as an increasing fraction of ownership in the pool, which is reflected in your growing balance of LP (Liquidity Provider) tokens. This increase occurs as the transaction fees are added as deposits into the pool.
Typically, these fees are relatively low, especially on larger pools with reduced risk. In addition to these fees, Curve offers a secondary reward known as tAPR.
There’s two components to tAPR. First, we will look at the CRV component - CRV stands for the curve governance token (we will discuss governance next), basically Curve mints it’s own token called CRV, and distributes it to anyone who has deposited their assets into a pool as an added incentive. The minting of this token is completely free for the Curve platform.
When you, as a user, wish to claim the CRV (Curve DAO token) that you are entitled to, you need to cover the gas fees to facilitate the transfer from a Curve smart contract to your personal address. This might appear as though it’s akin to inflation or money creation, and to some extent, it is.
To prevent a situation where everyone immediately sells their CRV tokens upon receiving them, Curve offers the option to deposit them into a ‘savings account.’ Once deposited, you are unable to withdraw them for a predetermined duration. By choosing to lock your CRV tokens in a savings account, you ‘boost’ the amount of CRV you earn from providing assets to a liquidity pool. The longer you lock your assets, the higher your earnings. For instance, in the case of the 3pool, if you commit to a four-year lockup, you will receive an annual yield of 1.55% in CRV, compared to the standard 0.62%.
This practice is commonly referred to as ‘staking’ your assets. Additionally, 50% of all trading fees generated on the Curve platform are distributed to those who have staked CRV. This creates a dual incentive structure: it discourages premature selling of CRV tokens while also providing dividend payments to CRV token holders.
The second part of tAPR is the incentive. This you usually see for newer projects that want to attract liquidity to their token. They create a new pool and then agree to pay anyone who deposits liquidity into said pool some yearly reward in their native token.
As an example, the Curve Gear/ETH pool pays anyone a 31.38% yearly reward in the GEAR token -assuming that the price of Gear does not change between today and one year from now.
Note that these kinds of practices that would be deemed anti-competitive in the traditional legal system are perfectly common in DeFi; even 1inch used to cover the gas fees for its user, to attract more users.
Comparison with Uniswap and Pancakeswap#
Compared to other DEXs Curve allows you to deposit just one currency into a pool at a time. Uniswap and Pancake Swap both require you to deposit a pair of currencies. Uniswap doesn’t provide an option to stake LP tokens, while Pancakeswap does into what they call “farms”, functioning in much the same way as Curve LP staking rewards. In general this practice of trying to earn the maximum return possible from all kinds of schemes in the crypto world is called “yield farming”.
Furthermore, when depositing in Curve your tokens are always valid to be traded, but Uniswap V3 and Pancakeswap V3 and a lot of other DEXs allow you to choose the price range around which you provide your liquidity, for example only providing two stablecoins if their relative price is no smaller than 0,99 (Uniswap V2 and Pancakeswap V2 are the same as Curve). In general this increases capital efficiency and fees, but also amplifies impermanent loss. A few links have been provided below for the curious.
Concentrated Liquidity | Uniswap
Concentrated liquidity: Beginner Guide to Uniswap V3 & Liquidity Book
Governance tokens#
To understand how all this incentive madness came about, let’s talk about governance. All reputable DeFi projects are fully open source so anyone can contribute, but this means that anyone can also completely wreck a project if they contribute something stupid or even intentionally destructive. You could also just decide, when creating your DeFi project, that nobody can contribute/make changes; not even yourself, but the code would still be open source. However, this option is not desirable, because you would be outcompeted (for example, Pancakeswap and SushiSwap started out as a copy of the same smart contract used by Uniswap, because they thought they could do the same service, but better). Therefore, it makes sense to want a project to develop, and it makes sense for developers to want to do it in a decentralised way. In order to foster the growth and evolution of a DeFi (Decentralized Finance) platform, creators often establish a DAO (Decentralized Autonomous Organization) and distribute governance tokens to those who wish to participate. These governance tokens provide holders with the ability to vote on proposed platform changes and suggest improvements. The aim is to promote decentralization, with tokens distributed to early platform users. It’s important to note that the DeFi space is driven by technology enthusiasts seeking innovation, rather than just profit.
However, as DeFi competition grew, participants realized the need for a competitive advantage to stay relevant. In a world of open-source code, having an established user base became valuable. Users were hesitant to switch to a competitor offering an identical solution. Moreover, scalability meant more liquidity, reduced price impact, and a competitive edge. Consequently, DeFi platforms devised strategies to incentivize users to choose their protocol. To give these tokens value and prevent them from becoming worthless, some meaning was attached to them, often in the form of ‘governance.’ In some cases, less reputable projects had no plans for a transition to decentralized governance.
This explains the extra rewards, in CRV tokens (Curve DAO tokens), offered to users who deposit tokens into Curve’s liquidity pools. In practice, decentralized governance allows token holders to vote on proposed changes, with the project team, whether volunteers or funded by venture capitalists and protocol fees, implementing these changes
Lending protocols#
Finally, let’s touch on lending protocols, since they are a good demonstration of the presently existing limitations of decentralised finance. The two most famous lending protocols are Aave and Compound - although the stablecoin DAI could also be considered one for reasons that will be clear.
Open Source Liquidity Protocol
When dealing with lending platforms, we encounter a fundamental challenge: trustlessness. Loans inherently require trust or, at the very least, some enforcement mechanism to prevent the other party from making away with the borrowed funds. In the crypto world, where your only information about a counterparty is often their address, it’s evident that sending 10 ETH to address 0xAEF00D82E977738D464819742387662f1dA2Cc8D with the hope of receiving 11 ETH in return a year later is a risky proposition. Lending platforms have tackled this issue by mandating that all loans be overcollateralized. Think of it like mortgages, but even more stringent. Every gwei worth of ETH borrowed must have more than 1 gwei worth of ETH as collateral, either in the same or a different asset. This is the first key point: loans in DeFi require overcollateralization.
The second important aspect is that traditional order books aren’t available, and the constant product bonding curves used in DEXs (Decentralized Exchanges) don’t translate well to loans. Consequently, determining the cost of borrowing, i.e., the interest rate, becomes a bit complex. The simplest and, currently, the most efficient solution is to set a fixed interest rate that depends on one variable: the amount of available funds that have been borrowed.
So, how does one provide funds as collateral, and where do the borrowed funds come from? Surprisingly, they come from the same source. Lending operates through pools, such as a pool of ETH where people can deposit and borrow from. For example, Aave has ETH and DAI pools. Anyone who wants to borrow ETH with DAI as collateral must first deposit some assets into the DAI pool before being eligible to borrow ETH. The specific overcollateralization ratio varies depending on the collateral; riskier assets typically require a larger buffer than less risky ones.
With DAI, for each DAI supplied, someone can borrow 0.93 DAI worth of another asset - this is given by the “max LTV” (loan to value ratio). The interest rate charged by the borrow follows a piecewise linear function of the utilisation rate of the borrowed asset. In our example the utilisation rate for ETH (technically a wrapped version of it called WETH):
is 26.07%, this translates to an interest rate of 2.23% yearly. Those who supplied assets to the WETH pool to be borrowed out, earn an interest rate of 0.5% yearly, with the discrepancy being down to the fact that the platform takes a 15% cut called the ‘reserve factor’ which is used, as the name implies, to increase the reserves in the pool. The reserves are just assets which are owned by the smart contract itself rather than any other address. This helps prevent contagion and large scale liquidation cascades.
It’s worth noting that the interest rate when borrowing is not fixed, unless you explicitly opt for a fixed interest rate loan. Aave offers fixed interest rate loans as an option, but they tend to be more expensive. Typically, the interest rate is assessed and adjusted in every block, fluctuating in response to changes in the utilisation rate.
Lastly, if the price of your collateral falls below the maximum Loan-to-Value (LTV) ratio, a portion of your position that is not adequately collateralised will face liquidation. During liquidation, anyone can repay your loan and, in return, acquire some of your collateral at a discounted rate. This mechanism ensures the platform’s ability to handle relative price fluctuations. Therefore, it’s crucial to ensure that you borrow an amount within the limits set by the maximum LTV. Otherwise, even a minor price fluctuation could result in a portion of your assets being liquidated.
Next tutorial#
In the next tutorial, we examine the problem of gas fees in greater depth, and look at the role of what are called ‘Layer 2 solutions’ in how blockchain is being made cheaper and faster for everyone.