aave – Finematics https://finematics.com decentralized finance education Thu, 21 Jan 2021 19:17:01 +0000 en-GB hourly 1 https://wordpress.org/?v=5.8.1 https://finematics.com/wp-content/uploads/2017/09/cropped-favicon-32x32.png aave – Finematics https://finematics.com 32 32 Aave – The Road To $3 Billion https://finematics.com/aave-explained/?utm_source=rss&utm_medium=rss&utm_campaign=aave-explained&utm_source=rss&utm_medium=rss&utm_campaign=aave-explained https://finematics.com/aave-explained/#respond Wed, 20 Jan 2021 20:04:25 +0000 https://finematics.com/?p=1218

So what is Aave all about? How was it able to go from 0 to $3B in total value locked in less than a year? And what’s the use case for the AAVE token? You’ll find answers to these questions in this article. 

Let’s start from the beginning.  

ETHLend 

The initial version of Aave – which is currently one of the most popular lending protocols in decentralized finance – came into existence in 2017. Before the rebranding that happened later in September 2018, the project was known as ETHLend. 

ETHLend was started in Finland by Stani Kulechov. Stani, a law degree graduate, discovered Ethereum, realised the power of smart contracts and decided to build a peer-to-peer lending protocol. 

Finland was clearly not a usual location for a new tech company, with the majority of other crypto firms launching in venture-capital-rich places such as Silicon Valley, New York, London, Hong Kong or Singapore. 

This also shows one of the most interesting properties of decentralized finance. In contrast to traditional finance where a new fintech startup requires a lot of capital and staff just to comply with all the banking regulations, a new defi project can be launched by even a single person with not a lot of upfront capital needed.

The first version of ETHLend was deployed to the Ethereum mainnet in early 2017 and started attracting interest in the Ethereum community. 

ICO and Rebranding 

Stani saw the potential of decentralized lending and decided to raise money via an initial coin offering (ICO) at the end of 2017 to fund further development of ETHLend. As we mentioned earlier funding a project outside of typical venture capital locations can be quite challenging. However, the ICO model allows everyone in the world to participate.

ETHLend was able to raise $16.2M which was quite moderate considering the craziness of the 2017 ICO mania. 

The ICO allowed for hiring more developers who were able to focus on making improvements to the protocol throughout 2018. This was all despite the native ETHLend token – LEND – losing most of its value in the post-ICO era. 

The ETHLend team soon realised that the peer-to-peer lending model of the protocol was becoming more and more problematic.

In the peer-to-peer model, users interact with other users via smart contracts. This can be quite inefficient especially if there is no one on the other side who wants to interact with us. 

A lot of other projects, such as Uniswap and Compound, that came into existence at the end of 2018, started leveraging another model – peer-to-contract. 

The peer-to-contract model is based on a contract with pooled funds that can be instantly used by the users of the protocol. This eliminates the wait time necessary to find a counterparty and makes the whole process of interacting with a decentralized protocol smoother. 

This was also the time when the team behind ETHLend decided to change their model from peer-to-peer to peer-to-contract and rebrand from ETHLend to Aave. 

Aave

The name Aave comes from Finnish where it means “a ghost”. This is also why we can now see a friendly ghost in the Aave’s logo. 

When it comes to the protocol itself, Aave users can become depositors or borrowers. Depositors provide funds to borrowers in return for interest on their deposit. Borrowers are willing to pay interest on the amount they borrowed in exchange for having a lump sum of money available immediately.

Users can, for example, supply a stable coin such as DAI and start generating interest according to the DAI supply interest rate. This is determined by the ratio between supplied and borrowed DAI.

The supplied DAI can then be used by borrowers. Borrowers have to supply collateral, for example, ETH to be able to borrow other tokens. All the standard loans in Aave are overcollateralized which means that the value of supplied collateral is higher than the amount that can be borrowed. This protects the protocol from being undercollateralized and not being able to repay depositors. 

In this model, depositors basically provide liquidity to the protocol, this is also why Aave is very often described as a decentralised liquidity market protocol.  

On top of variable interest rates, Aave also offers stable borrow rates which is a distinctive feature not present in other popular lending defi protocols, such as Compound. 

In Aave, depositors who provide funds to a smart contract receive aTokens. The value of aTokens is pegged to the value of the underlying token at a 1:1 ratio. What is interesting is that the balance of aTokens represents their deposited amount plus the accrued interest and it keeps increasing according to the current borrow interest rate of the protocol. Also, aTokens are just ERC20 tokens. This means you can basically send them to someone else and the balance of their aTokens will keep increasing in their wallet automatically, which is pretty cool. 

If you want to learn more about how exactly lending works in defi and why is it even needed in the first place, check out our other article that covers this topic in depth. 

Another important concept popularised by Aave is flash loans. 

Flash Loans

A flash loan is a feature that allows you to borrow any available amount of assets from a designated smart contract pool with no upfront collateral needed. The caveat is that a flash loan has to be borrowed and repaid within the same blockchain transaction. 

These constructs are useful building blocks in DeFi as they can be used for things like arbitrage, swapping collateral and self-liquidation.

Fortunately enough, we also wrote a separate article that explains the mechanics of flash loans and you can check it out here

DeFi Summer

After a couple of years of work, Aave launched on the Ethereum mainnet at the beginning of 2020 and started building users’ interest and its total value locked (TVL) in the protocol. 

This quickly escalated in May 2020 when a period of DeFi super-growth also called DeFi Summer started. 

Before DeFi Summer, the total value locked in Aave, which is one of the key metrics when it comes to a lending protocol, was at around $40M. 

With launches of new DeFi protocols and new yield farming opportunities, Aave’s TVL started rising dramatically. 

$60M in June, $400M in July. August was closed with a whopping $1.5B in TVL. This number remained at $1.5B in September despite the cool down across the whole DeFi space. Although October saw a drop back to around $1B, at the end of November we were once again at an all-time high with $1.6B locked. At the end of 2020, Aave’s TVL was touching $2B. In 2021, a major surge in DeFi tokens pushed Aave’s TVL to over $3B by mid-January.

This is basically a 50x increase in TVL in around 6 months – quite astonishing. 

Besides that, Aave hit another major milestone – $1B in flash loans volume. 

Additionally, there were a few other important events that took place during DeFi Summer. 

Aave raised $3M from venture capital firms: Three Arrow Capital and Framework Ventures who purchased Aave’s native token LEND. 

In July 2020 Aave was granted an electronic money license by the U.K. Financial Conduct Authority. This strategic move will make it possible for Aave to become a fiat gateway and easily onboard people to its own protocol. 

On top of this, also in July, Aave announced an upgrade to the tokenomics of the protocol conveniently named Aavenomics. 

Aavenomics

Aavenomics aimed at making Aave more decentralized by allowing token holders to participate in the governance of the protocol.

Some of the most important elements of the upgrade were the migration from the LEND token to a new token AAVE in a 100:1 ratio, new Ecosystem Incentives and the Safety Module.

The Safety Module allows for staking AAVE tokens and acts as insurance against a potential shortfall event. If an event like this occurs, up to 30% of the tokens staked in the safety module could be slashed and would provide a way to repay everyone affected. 

Although major shortfall events are unlikely, they can still happen. An example of such an event would be if a popular stable coin loses its peg to the US dollar. 

In exchange for staking their tokens users receive staking rewards in the form of additional AAVE tokens. Currently, the rewards are at around 6% annually and are generated from the protocol fees.  

The token migration was initiated in October 2020 and went smoothly with most of the LEND holders exchanging their tokens in the first couple of weeks. 

So far, we’ve seen 7 Aave Improvement Proposals (AIPs). Most of the proposals involve either adding a new asset as collateral or tweaking some of the risk parameters of the already existing tokens that can be used in the protocol.

V2

In the meantime, The Aave team was relentlessly working on delivering an upgraded version of the protocol. 

Aave V2 went live in December 2020 and brought a lot of new features and improvements such as:

Collateral Swap. Users can swap their collateral from one token to the other. For example, they can swap their collateral from ETH to DAI if they believe that ETH may lose value in the future. Collateral Swap is possible thanks to flash loans and it was explained in our article about flash loans. 

Batch Flash Loans. Users can now flash borrow multiple assets at the same time, all of it within the same Ethereum transaction. 

Debt Tokenization. In V2, borrowers receive tokens that represent their debt. This in turn enables another feature:

Native Credit Delegation. This allows for opening up access to liquidity without providing collateral. A very useful feature that can be used, for example, to provide a credit line to an institution, a cryptocurrency exchange or even other decentralized protocol under certain conditions. This feature in and of itself is probably worth writing another article. 

Besides all of that, V2 contracts are highly optimised which results in lower gas fees. In some cases, a user can save up to 50% of the gas cost when comparing to V1.

Future 

Aave is clearly one of the most important protocols in the decentralised finance space and there is a big chance it will remain one of the main building blocks in defi for the foreseeable future. 

One of the strong aspects of Aave is its community, also known as Aavengers, with a lot of members supporting the protocol pretty much from the time of their ICO. 

Due to Ethereum’s popularity, interacting with Aave and other defi protocols can be quite expensive, especially when working with small amounts of money. 

To solve this issue, Aave, similarly to other major defi protocols, is also exploring the possibility of launching on layer 2. This should make decentralized lending and borrowing even more accessible to everyone. 

So what do you think about Aave? How big will it become in the future? 

If you enjoyed reading this article you can also check out Finematics on Youtube and Twitter.

]]>
https://finematics.com/aave-explained/feed/ 0
Lending and Borrowing in DeFi Explained – Aave, Compound https://finematics.com/lending-and-borrowing-in-defi-explained/?utm_source=rss&utm_medium=rss&utm_campaign=lending-and-borrowing-in-defi-explained&utm_source=rss&utm_medium=rss&utm_campaign=lending-and-borrowing-in-defi-explained https://finematics.com/lending-and-borrowing-in-defi-explained/#respond Mon, 16 Nov 2020 20:29:32 +0000 https://finematics.com/?p=1115

So have you ever been wondering how lending and borrowing works in DeFi? How are the supply and borrow rates determined? And what is the main difference between the most popular lending protocols such as Compound and Aave? We’ll answer all of these questions in this article. 

What is Lending and Borrowing

Let’s start with what lending and borrowing is. 

Lending and borrowing is one of the most important element of any financial system. Most people at some point in their life are exposed to borrowing, usually by taking a student loan, a car loan or a mortgage. 

The whole concept is quite simple. Lenders a.k.a. depositors provide funds to borrowers in return for interest on their deposit. Borrowers or loan takers are willing to pay interest on the amount they borrowed in exchange for having a lump sum of money available immediately.

Traditionally, lending and borrowing is facilitated by a financial institution such as a bank or a peer-to-peer lender. 

When it comes to short term lending & borrowing, the area of traditional finance that specializes in it is called the money market. The money market provides access to multiple instruments such as CDs (certificates of deposits), Repos (repurchase-agreements), Treasury Bills and others. 

Lending and Borrowing in Crypto 

In the cryptocurrency space, lending and borrowing is accessible either through DeFi protocols such as Aave or Compound or by CeFi companies, for instance, BlockFi or Celsius.

CeFi or centralized finance operates in a very similar way to how banks operate. This is also why sometimes we call these companies “crypto banks”. BlockFi, for example, takes custody over deposited assets and lends them out to either institutional players such as market makers or hedge funds or to the other users of their platform.

Although the centralized lending model works just fine, it is susceptible to the same problems as centralized crypto exchanges – mainly losing customer deposits by either being hacked or other forms of negligence (bad loans, insider job etc.). 

You can also argue that the CeFi model basically goes against one of the main value propositions of cryptocurrencies – self-custody of your assets. 

This is also where DeFi lending comes into play. 

Lending and Borrowing in DeFi

DeFi lending allows users to become lenders or borrowers in a completely decentralized and permissionless way while maintaining full custody over their coins. 

DeFi lending is based on smart contracts that run on open blockchains, predominantly Ethereum. This is also why DeFi lending, in contrast to CeFi lending, is accessible to everyone without a need of providing your personal details or trusting someone else to hold your funds. 

Aave and Compound are two main lending protocols available in DeFi. Both of the protocols work by creating money markets for particular tokens such as ETH, stable coins like DAI and USDC or other tokens like LINK or wrapped BTC.

Users, who want to become lenders, supply their tokens to a particular money market and start receiving interest on their tokens according to the current supply APY. 

The supplied tokens are sent to a smart contract and become available for other users to borrow. In exchange for the supplied tokens, the smart contract issues other tokens that represent the supplied tokens plus interest. These tokens are called cTokens in Compound and aTokens in Aave and they can be redeemed for the underlying tokens. We’ll dive deeper into their mechanics later in this article. 

It’s also worth mentioning that in DeFi, at the moment, pretty much all of the loans are overcollateralized. This means that a user who wants to borrow funds has to supply tokens in the form of collateral that is worth more than the actual loan that they want to take. 

At this point, you may ask the question – what’s the point of taking a loan if you have to supply tokens that are worth more than the actual amount of the loan taken. Why wouldn’t someone just sell their tokens in the first place? 

There are quite a few reasons for this. Mainly, the users don’t want to sell their tokens but they need funds to cover unexpected expenses. Other reasons include avoiding or delaying paying capital gain taxes on their tokens or using borrowed funds to increase their leverage in a certain position. 

So, is there a limit on how much can be borrowed? 

Yes. The amount that can be borrowed depends on 2 main factors. 

The first one – how much funds are available to be borrowed in a particular market. This is usually not a problem in active markets unless someone is trying to borrow a really big amount of tokens.

The second one – what is the collateral factor of supplied tokens. Collateral factor determines how much can be borrowed based on the quality of the collateral. DAI and ETH, for example, have a collateral factor of 75% on Compound. This means that up to 75% of the value of the supplied DAI or ETH can be used to borrow other tokens. 

If a user decides to borrow funds, the value of the borrowed amount must always stay lower than the value of their collateral times its collateral factor. If this condition holds there is no limit on how long a user can borrow funds for.

If the value of the collateral falls below the required collateral level, the user would have their collateral liquidated in order for the protocol to repay the borrowed amount.

The interest that lenders receive and the interest, that borrowers have to pay are determined by the ratio between supplied and borrowed tokens in a particular market. 

The interest that is paid by borrowers is the interest earned by lenders, so the borrow APY is higher than the supply APY in a particular market.

The interest APYs are calculated per Ethereum block. Calculating APYs per block means that DeFi lending provides variable interest rates that can change quite dramatically depending on the lending and borrowing demand for particular tokens. 

This is also where one of the biggest differences between Compound and Aave comes in. Although both protocols offer variable supply and borrow APYs, Aave also offers stable borrow APY. Stable APY is fixed in a short-term, but it can change in the long-term to accommodate changes in the supply/demand ratio between tokens. 

On top of stable APY, Aave also offers flash loans where users can borrow funds with no upfront collateral for a very short period of time – one Ethereum transaction. More on the flash loans here. 

To better understand how the DeFi lending protocols work, let’s dive into an example.

How Does It Work

Let’s dive deeper into the mechanics of Compound and cTokens. 

In our example, a user deposits 10 ETH into Compound. In exchange for 10 ETH, Compound issues cTokens in this case cETH. 

How many cETH tokens will the user receive? This depends on the current exchange rate for a particular market, in this case, ETH. When a new market is created the exchange rate between cTokens and underlying tokens is set to 0.02. This is an arbitrary number, but we can assume that each market starts at 0.02. We can also assume that this exchange rate can only increase with each Ethereum block. 

If the user supplied 10 ETH when the market was just created they would’ve received 10/0.02=500 cETH. Because the ETH market has been operating for a while we can assume that the exchange rate is already higher. Let’s say it is 0.021. 

This means that the user would receive 10/0.021=~476.19 cETH. If the user decided to immediately redeem their ETH, they should receive roughly the same amount as it was deposited, which is around 10 ETH. 

Now, here is when the magic happens. The user holds their cETH.  This is just another ERC20 token and can be sent anywhere. The main difference is that cETH is necessary to redeem the underlying ETH from Compound. On top of that, cETH keeps accumulating interest, even if it is sent from the original wallet that initiated the deposit to another wallet. 

With each Ethereum block, the exchange rate would increase. The rate of the increase depends on the supply APY which is determined by the ratio of supplied/borrowed capital. 

In our example, let’s say that the exchange rate from cETH to ETH increases by 0.0000000002 with each block. Assuming that the rate of increase stays the same for a month we can easily calculate the interest that can be made during that time. 

Let’s say on average we have 4 blocks per minute. This gives us the following numbers.

0.0000000002*4*60*24*30=0.00003456. Now we can add this number to the previous exchange rate. 0.021+0.00003456=0.02103456. 

If the user decides to redeem their ETH they would receive 476.19*0.0213456=~10.0165 ETH. So the user just made 0.0165 ETH in a month which is around 0.16% return on their ETH. It’s worth noting that the original amount of cETH that the user received hasn’t changed at all and only the change in the exchange rate allowed the user to redeem more ETH than was initially deposited. 

Aave uses a similar model with interest being accumulated every single block. The main difference is that aTokens’ value is pegged to the value of the underlying token at a 1:1 ratio. The interest is distributed to aToken holders directly by continuously increasing their wallet balance. aToken holders can also decide to redirect their stream of interest payments to another Ethereum address.

When it comes to borrowing, users lock their cTokens or aTokens as collateral and borrow other tokens. Collateral earns interest, but users cannot redeem or transfer assets while they are being used as collateral. 

As we mentioned earlier the amount that can be borrowed is determined by the collateral factor of the supplied assets. There is also a smart contract that looks at all the collateral across user’s account and calculates how much can be safely borrowed without getting liquidated immediately. To determine the value of collateral Compound uses its own price feed that takes prices from several highly liquid exchanges. Aave on the other hand relies on Chainlink and falls back to their own price feed if necessary. 

If a user decides to repay the borrowed amount and unlock their collateral, they also have to repay the accrued interest on their borrowed assets. The amount of accrued interest is determined by the borrow APY and it is also increased automatically with each Ethereum block. 

Risks

DeFi lending, although reducing a lot of risks associated with centralized finance, comes with its own risks.

Mainly the ever-present smart contract risks, but also quickly changing APYs. For example, during the last yield farming craze, the borrow APY on the BAT token went up to over 40%. This could cause unaware users who were not tracking Compound interest rates daily to get liquidated by having to repay more than expected in the same period of time. 

So what do you think about lending and borrowing in DeFi? What is your favourite platform? 

If you enjoyed reading this article you can also check out Finematics on Youtube and Twitter.

]]>
https://finematics.com/lending-and-borrowing-in-defi-explained/feed/ 0
How To Code A Flash Loan With Aave https://finematics.com/how-to-code-a-flash-loan-with-aave/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-code-a-flash-loan-with-aave&utm_source=rss&utm_medium=rss&utm_campaign=how-to-code-a-flash-loan-with-aave https://finematics.com/how-to-code-a-flash-loan-with-aave/#respond Mon, 12 Oct 2020 14:30:27 +0000 https://finematics.com/?p=1022 So how can you code a flash loan with a few easy steps? And how can you interact with Aave’s smart contracts? You’ll find answers to these questions in this tutorial. 

What are Flash Loans? 

A flash loan is a feature that allows you to borrow any available amount of assets from a designated smart contract pool with no collateral. Flash loans are useful building blocks in DeFi as they can be used for things like arbitrage, swapping collateral and self-liquidation.

Flash loans, although initially introduced by the Marble protocol, were popularised by Aave and Dydx. 

So, what’s the catch? 

A flash loan has to be borrowed and repaid within the same blockchain transaction. 

If you’d like to learn more about flash loans check out our article on flash loans here

Before we start 

This guide requires a basic understanding of Solidity smart contracts and how to use Remix. You can find Remix documentation here

It also requires having your Metamask wallet installed and switched to the Kovan testnet. 

To execute any smart contracts on Ethereum you’ll also have to have some ETH in your wallet. You can get some Kovan testnet ETH by going to faucet.kovan.network and logging in with your Github account. You can request 1 testnet ETH once per day. 

We’ll also need some DAI. To request DAI go to testnet.aave.com/faucet and click on DAI, than hit the “Submit” button. 

Okay, the last step is to set up your Remix environment. Go to remix.ethereum.org and select 0.6.6+ version of the Solidity compiler. 

Flash Loan Smart Contract

Great, time to start working on our flash loan. Let’s start with creating a basic smart contract file. 

Here is the first piece of code we need.

pragma solidity ^0.6.6;

import "https://github.com/aave/flashloan-box/blob/Remix/contracts/aave/FlashLoanReceiverBase.sol";
import "https://github.com/aave/flashloan-box/blob/Remix/contracts/aave/ILendingPoolAddressesProvider.sol";
import "https://github.com/aave/flashloan-box/blob/Remix/contracts/aave/ILendingPool.sol";

contract Flashloan is FlashLoanReceiverBase {
    constructor(address _addressProvider) FlashLoanReceiverBase(_addressProvider) public {}
}

This will import all the necessary dependencies and create a basic FlashLoan.sol smart contract that inherits from FlashLoanReceiverBase which is an abstract contract that provides a few useful things such as a way of repaying the flash loan.

The Flashloan.sol constructor accepts the address of one of the Aave’s lending pool providers. We’ll get to this later.

You can now hit the compile button. 

This should download all the relevant dependencies and result in an error as we haven’t implemented all of the necessary methods from the FlashLoanReceiverBase just yet.

Time to add 2 missing functions. First one is our actual flashLoan function that will be used to trigger a flash loan. The other one is the missing method from FlashLoanReceiverBaseexecuteOperation that will be called after the flash loan method is triggered. 

Flash Loan Function

Let’s add the flashLoan function first. 

Here is the code snippet. 

function flashloan(address _asset) public onlyOwner {
        bytes memory data = "";
        uint amount = 1000000000000000000;

        ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
        lendingPool.flashLoan(address(this), _asset, amount, data);
    }

Time to make sure we understand all the relevant parts. 

The flashLoan function parameter _asset is an address of an asset that we want to borrow using a flash loan, for example, ETH or DAI.

We define our function as onlyOwner, so only the owner of the contract can call the function.

uint amount = 1000000000000000000;

Here, we’re defining the borrowed amount in the minor unit – wei that is 10^18, so this value is equal to 1. If we pass the DAI address as _asset we’ll be borrowing 1 DAI, if we pass the ETH address we’ll be borrowing 1 ETH.

Now we can use a ILendingPool interface provided by Aave and call flashLoan function with all the required parameters such as the asset that we want to borrow, the amount of that asset and an extra data parameter.

Even after adding our flashLoan function, the code will still not compile as we have to add the missing executeOperation function.

executeOperation Function

Time to implement the last missing bit before we can try triggering our flash loan function.

executeOperation function will be called by the LendingPool contract after a valid amount of asset is requested in a flash loan.

Here is a code snippet for the executeOperation function.

function executeOperation(
        address _reserve,
        uint256 _amount,
        uint256 _fee,
        bytes calldata _params
    )
        external
        override
    {
        require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?");

        // Your logic goes here.

        uint totalDebt = _amount.add(_fee);
        transferFundsBackToPoolInternal(_reserve, totalDebt);
    }

All the parameters for the executeOperation function will be passed automatically after a valid flash loan is triggered using the flashLoan function.

The require check is used to validate that we received a correct amount from a flash loan.

Next, we can insert any arbitrary logic that we want to execute. At this step we have all the funds from a flash loan available, so we can, for example, try to execute an arbitrage opportunity.

After we made use of a flash loan, it’s time to repay it.

uint totalDebt = _amount.add(_fee);

Here, we are calculating how much we have to repay which is the borrowed amount + 0.09% of the borrowed amount.

The last step is to call transferFundsBackToPoolInternal to pay back our flash loan.

Now, we can try to compile our code again. This time everything should compile just fine.

Time to trigger our flashLoan function.

Running The Code

Great, our flash loan smart contract is compiled and ready to be deployed.

Let’s start with preparing 2 necessary things:

  • LendingPoolAddressesProvider – to deploy our smart contract we need to find the address of the Aave’s lending smart contract on the Kovan testnet. You can find all the addresses here. The Kovan address is 0x506B0B2CF20FAA8f38a4E2B524EE43e1f4458Cc5
  • DAI address – we need a contract address of DAI (or any other asset you want to borrow) on the Kovan testnet. The DAI Kovan address is 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD

Time to deploy our smart contract.

  1. Go to “Deploy & Run Transactions” on Remix
  2. Select “Injected Web3” (Make sure your Metamask is switched to Kovan)
  3. Select a contract to be deployed – FlashLoan.sol
  4. Pass the LendingPoolAddressesProvider that we found a few steps earlier to the field next to the “Deploy” button
  5. Hit “Deploy” button
  6. Confirm your Ethereum transaction via Metamask

If everything went ok – great! We now have our FlashLoan.sol smart contract deployed on the Ethereum testnet – Kovan.

Here is the crucial step in running our smart contract. We have to send some DAI into the smart contract we just created to be able to pay for the flash loan fee.

You can find your smart contract address by checking the Metamask transaction that you previously approved. The transaction for creating a smart contract should look similar to this one here. From that transaction, you can extract the smart contract address (0x27016b23BEE0553A4aAa89b25Be58b93Fe647BBe in our case).

Time to trigger our flashLoan function from the deployed contract. Remember about passing a correct address of the asset you want to borrow. In our case it’s DAI address on the Kovan testnet.

After triggering the flashLoan function and accepting an Ethereum transaction via Metamask, you should see a similar transaction to this one here.

Congrats! You just made your first flash loan!

If you enjoyed this tutorial you can also check out Finematics on Youtube and Twitter.

]]>
https://finematics.com/how-to-code-a-flash-loan-with-aave/feed/ 0
Flash Loans Explained (Aave, dYdX) https://finematics.com/flash-loans-explained/?utm_source=rss&utm_medium=rss&utm_campaign=flash-loans-explained&utm_source=rss&utm_medium=rss&utm_campaign=flash-loans-explained https://finematics.com/flash-loans-explained/#respond Mon, 12 Oct 2020 14:27:47 +0000 https://finematics.com/?p=993

So what are flash loans all about? And how can they be used to borrow millions of dollars worth of crypto with no collateral? You’ll find answers to these questions in this article.

Introduction 

A flash loan is a feature that allows you to borrow any available amount of assets from a designated smart contract pool with no collateral. Flash loans are useful building blocks in DeFi as they can be used for things like arbitrage, swapping collateral and self-liquidation.

Flash loans, although initially introduced by the Marble protocol, were popularised by Aave and dYdX. 

So, what’s the catch? 

A flash loan has to be borrowed and repaid within the same blockchain transaction. 

The concept of a transaction on a blockchain such as Ethereum is no different to the traditional definition of a transaction in computer science. 

Transactions 

A transaction represents a set of operations that must be executed in an atomic way – either all the steps are executed or the transaction is rolled back and none of the steps take place. 

Let’s take a simple database transaction as an example. If you’re already familiar with this concept feel free to skip this part. 

Imagine a database table that represents users’ balances. 

Alice’s balance is $1000 and Bob’s balance is $500. Alice sends Bob $500. In this case, we, of course, have to subtract $500 from Alice’s balance and add $500 to Bob’s balance. So we start writing our database update statements. 

This is cool, but what happens if the first update executes but the second one fails for some reason? (maybe id=2 is not present in the system and we made a mistake thinking it’s Bob’s id)

If this happens we would end up in an inconsistent state with Alice’s balance equal to $500 and Bob’s balance also equal to $500. 

To avoid situations like this we have to use transactions. 

In the above situation, in SQL, we just need to wrap both statements with BEGIN; and COMMIT; keywords. Once we do that, we can safely assume that either both statements are executed correctly or none of them are – leaving Alice’s and Bob’s balances untouched. We often say that if different steps are a part of the same transaction they are atomic, hence indivisible – all or nothing. 

Ethereum Transaction

When it comes to Ethereum, every common operation, such as sending ETH, sending ERC20 tokens and interacting with smart contracts are executed within a transaction scope. 

Transactions are grouped together and included in Ethereum blocks. We can easily see all of the transactions that were included in a particular block on any popular block explorer, such as Etherscan. 

One Ethereum transaction can consist of multiple steps, for example, you could supply ETH and borrow DAI on Compound, swap half of your borrowed DAI for USDC on Curve and provide liquidity to DAI/USDC pool on Uniswap – all in one single Ethereum transaction. Of course, if any of these steps result in an error, the whole transaction will be rolled back and none of the steps will take place. Remember – you will still pay gas fees, even for failed contract executions.  

The number of steps in a single transaction is only bounded by the gas cost, so although, in theory, you could create a valid transaction with thousands of steps, realistically it’d be rejected because of the max gas cost limit per block. 

Flash Loans  

Now, let’s dive a little bit deeper into flash loans. 

First of all, the most important part of executing a flash loan is to find a flash loan provider. Projects such as Aave or dYdX developed smart contracts that allow defi users to borrow different coins from a designated pool under the condition that they are repaid within the same Ethereum transaction. There is usually a fixed cost associated with using flash loans. Aave contracts, for example, require the borrower to return the initial amount + an extra 0.09% of the borrowed amount. The fee is split between depositors, who provide the funds that can be borrowed, and integrators, who facilitate the use of Aave’s flash loan API. A part of this fee is also swapped to AAVE tokens and burned. 

Once the amount is borrowed from the lending pool it can be used for any other arbitrary actions assuming that at the end of the chain of different steps, the initial flash loan is repaid.

Because the loan has to be repaid within one transaction, there is no risk of borrowers not repaying their borrowed amount. The only risk is the always present smart contract and platform risk. 

Flash loans are becoming more and more popular with some of the users borrowing as high as 14M DAI on Aave. 

Use Cases

There are 3 most common use cases for flash loans. 

Arbitrage. Flash loans can magnify the profit of executing a successful arbitrage opportunity.

Let’s imagine that there is a price discrepancy in the DAI/USDC pools between Uniswap and Curve. You can trade 1 DAI for 1 USDC on Curve, but you only need 0.99 DAI to buy 1 USDC on Uniswap. Now you can try to execute the following arbitrage. 

  1. Borrow 100,000 DAI from Aave via flash loan 
  2. Swap 100,000 DAI for USDC on Uniswap and receive 101,010 USDC
  3. Swap 101,010 USDC for 101,010 DAI on Curve 
  4. Repay initial 100,000 DAI + 0.09% fee = 100,090
  5. Profit 920 DAI 

This looks nice, but we have to take a few extra things into consideration

  1. Network fees – arbitrage transactions with multiple steps can be quite expensive. Always take transaction fees into account when calculating your profits. 
  2. Price Slippage – always calculate how much price slippage you’ll experience while executing your order (a hint – it depends on the size of your order and the liquidity present in the liquidity pool)
  3. Frontrunning – there is a high chance that someone else will spot the same opportunity and will manage to get their transaction mined ahead of you. On top of that, bots that monitor the mempool can pick up your profitable arbitrage opportunity and send the same transaction with a higher gas fee, profiting them instead of you, basically stealing your arb opportunity.

The next use case for flash loans is a collateral swap

Let’s say you have borrowed DAI from Compound with ETH as collateral. You can swap your collateral from ETH to, for example, BAT in the following way:

  1. Take a flash loan in DAI to cover the amount of DAI that was borrowed
  2. Repay your Compound loan with borrowed DAI 
  3. Withdraw your ETH 
  4. Swap your ETH for BAT on Uniswap 
  5. Supply BAT as collateral on Compound 
  6. Borrow DAI against your BAT collateral 
  7. Repay flash loan with borrowed DAI + fee 

Congrats, you just swapped your collateral from ETH to BAT and paid 0.09% of the borrowed amount for this. 

The last but not least example is self-liquidation.

Imagine the following scenario: You have a loan in DAI on Compound with ETH as collateral. The ETH price keeps going down and you’re approaching the liquidation level. You also don’t have or don’t want to deposit more ETH to decrease your liquidation level and you also don’t have the DAI required to repay the loan. Now, instead of allowing the MakerDAO contract to liquidate your collateral and charge you the liquidation fee, you can take the following steps:

  1. Take a flash loan for the amount of DAI that you owe
  2. Repay your DAI loan and withdraw your ETH
  3. Swap enough ETH to DAI in order to repay the flash loan + fees 
  4. Keep the rest of your ETH 

These were the 3 most common use cases for flash loans. Of course, the concept of flash loans is quite new and there are still a lot of use cases to be discovered in the future. 

Flash Loans and DeFi Hacks

Flash loans, similarly to crypto, can be used for both good and bad. When it comes to the latter, flash loans were used in most of the recent defi hacks and allowed hackers to magnify their potential profits as they do not require any upfront funds. 

One of the most famous hacks was the BzX hack where a flash loan was used to manipulate the Uniswap oracle price. As usual, the problem was not in the use of flash loans, but rather in some incorrect assumptions when it comes to using Uniswap as a price oracle.

Events like these are sometimes costly for the people affected by them, but they usually result in the strengthening of the whole defi ecosystem, making it more and more antifragile in the future.  

Coding & Furucombo 

Although flash loans are predominantly used by developers, it is also possible to use them without doing any coding. Projects such as Collateralswap, Defisaver or Furucombo make it possible. 

You can also check out our guides on how to code a flash loan with Aave here and how to use Furucombo here. So no matter if you are familiar with coding or not – you can find something that works for you. 

So, what do you think about flash loans? Have you ever used them? And do you think they are good for the defi ecosystem?

If you enjoyed reading this article you can also check out Finematics on Youtube and Twitter.

]]>
https://finematics.com/flash-loans-explained/feed/ 0