flash loans – Finematics https://finematics.com decentralized finance education Tue, 13 Oct 2020 17:28:49 +0000 en-GB hourly 1 https://wordpress.org/?v=5.8.1 https://finematics.com/wp-content/uploads/2017/09/cropped-favicon-32x32.png flash loans – Finematics https://finematics.com 32 32 How To Use Furucombo https://finematics.com/how-to-use-furucombo/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-use-furucombo&utm_source=rss&utm_medium=rss&utm_campaign=how-to-use-furucombo https://finematics.com/how-to-use-furucombo/#respond Mon, 12 Oct 2020 14:38:47 +0000 https://finematics.com/?p=1007 So have you always wanted to try using some of the more advanced DeFi constructs such as flash loans but didn’t want to get too deep into coding? If the answer is yes, Furucombo may be an ideal tool for you. 

Let’s start with what Furucombo actually is. 

Furucombo

Furucombo is a tool that allows you to construct an Ethereum transaction using a simple drag-and-drop user interface. It can visualise complex DeFi transaction by showing a chain of interactions displayed as individual “cubes”. Each cube represents one specific interaction, for example, taking a flash loan or swapping coins on Uniswap. 

How To Take A Flash Loan

Okay, now let’s try to take a flash loan in Furucombo. If you want to learn more about flash loans you can check out our other article here.

  1. Go to https://furucombo.app/combo
  2. Click on the cube with the + sign to add a new cube
  3. Search for Aave and Flashloan 
  4. Select a token that you want to borrow and the borrowed amount 
  5. Click the Set button
  6. You’ll see 2 cubes added to the combo. Flashloan cube is a special case as every flash loan has to be repaid within the same Ethereum transaction. Because of that Furucombo creates 2 instead of 1 cube for you
  7. Now, you’re ready to add some arbitrary steps between the 2 flash loan cubes
  8. In our example, after we borrow 1,000 DAI from Aave via a flash loan we swap borrowed DAI for USDC on Uniswap and swap USDC back to DAI on Curve. 
  9. At the end of all the steps, we have to repay the initial loan + 0.09% fee
  10. Before you’ll able to execute your transaction you have to connect your wallet such as Metamask in the last step of your combo 

  11. After the wallet is connected you can Approve and execute your transaction

In our example, depending on the current price of USDC/DAI pairs on Curve and Uniswap, you’ll most likely end up with having to pay more than the amount that was borrowed. 

This is, of course, because there is usually no arbitrage opportunity in USDC/DAI between these 2 most popular decentralized exchanges. On top of that, you’ll be paying extra 0.09% of the borrowed amount in fees for being able to take a flash loan on Aave.

Next Steps 

After you make yourself familiar with the Furucombo interface you can try adding more cubes to the example. 

You can, for example, borrow funds from Compound, create a new vault in MakerDAO or add liquidity to a liquidity pool on Uniswap. 

Furucombo is an ideal tool for people who want to be able to create more complex Ethereum transactions. One thing that we have to remember is that you’ll be always limited to what combos you can create by the available cubes. For example, currently, there is no way to use some of the less popular DeFi protocols such as SushiSwap or Cream. 

If you’re ready to dive a little bit deeper and start writing your own smart contracts you can check out our guide on how to code your own flash loan with Aave here.

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

]]>
https://finematics.com/how-to-use-furucombo/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