Aave, previously known as ETHLender, has catapulted to the forefront of the DeFi space. Aave was the first in the space to come up with the idea of a Flash Loan. This is a quick tutorial to build and deploys a smart contract for Flash Loan.

This post was originally published in QuickNode.


Before flash loans, you would have to stake an over-collateralized asset to loan another asset. For example, if I wanted to borrow one DAI I would have to deposit another cryptocurrency that exceeded that value. In other words, you had to have money to borrow money. Flash Loans demolished this idea. And they opened up doors for a new loaning system. They did this by allowing users to borrow without putting up anything as collateral. In this tutorial you will learn how this is possible and how you can do it yourself!

About Aave

Taken from the Aave website.

Aave is a decentralised non-custodial liquidity market protocol where users can participate as depositors or borrowers. Depositors provide liquidity to the market to earn a passive income, while borrowers are able to borrow in an over collateralized (perpetually) or undercollateralized (one-block liquidity) fashion.

While that is entirely correct, it may not make much sense to you if you aren’t already familiar with all of the DeFi industry jargon. You could think of Aave as being a decentralized pseudo-bank. Instead of a central bank that validates all of the transactions, Aave has smart contracts that do all of this work in an automated fashion. Depositors put their tokens into Aave, and begin earning interest on their deposit. Borrowers on the other hand will do the opposite. They will take money out of Aave and will begin accruing interest on the amount borrowed. In order to do this, they must be overcollateralized.
There is another method for those that don’t want to deposit money into Aave, and just want to borrow. This is the Flash Loan we mentioned earlier.

About Flash Loans

The previously mentioned Flash Loan is a new way of borrowing assets on the blockchain. Initially implemented by Aave, other trending DeFi protocols such as dYdX quickly followed suit in adding this new feature. There is a property that all Ethereum transactions share that enable Flash Loans to be possible. And this key feature is atomicity.
A transaction is atomic whenever the series of its operations are indivisible and irreducible. Or in plain english— either all or none of the transaction occurs. No halfsies! The Flash Loan leverages atomicity to allow a user to borrow without posting collateral.There are two caveats to mention. First of all, whenever you borrow an asset in a Flash Loan you have to pay a fee of 0.09% of the amount loaned. Secondly, you must pay back the loan in the same transaction in which you borrowed. While this ability is great, it is somewhat limited in its use. Flash Loans are primarily used for arbitrage between assets.

Remix Setup

For the sake of simplicity, we will be using the Remix IDE.
This is a browser-based IDE. Also known as an Integrated Development Environment.Remix comes with the ability to write, debug, deploy, and otherwise manipulate Ethereum Smart Contracts.


When you load up Remix in your browser, you will be greeted by this menu.

We won’t be doing a deep dive on the IDE, as the focus of this tutorial is on the Flash Loan. However, you will want to become familiar with the four sections highlighted: main panel, side panel, icon panel, and terminal.


Before we start writing our smart contracts we will want to download a browser extension that allows us to interface with the Ethereum blockchain. There are several tools out there that unlock such functionality, but the most popular one is MetaMask.

MetaMask Setup

A step-by-step breakdown of how to install MetaMask.

  1. You will start by downloading the extension off of the website above.
  2. Click on your newly installed extension and agree to the terms and conditions.
  3. Create a secure password!
  4. Write down the mnemonic seed phrase. This should be in the physical world, and shouldn’t be kept anywhere on your computer.

If the four steps outlined above are completed you are all ready to start writing your first smart contracts!

The Smart Contract

Smart contracts allow us to read and write data to the blockchain by executing deterministic programs. When coding a smart contract for use on Ethereum, we use a programming language called Solidity. Solidity files end in the .sol extension.

You can delete any files that may be in your workspace when you first boot up Remix.

You will want to create several files:

  1. FlashLoan.sol
  2. FlashLoanReceiverBase.sol
  3. ILendingPoolAddressesProvider.sol
  4. IFlashLoanReceiver.sol
  5. ILendingPool.sol
  6. Withdrawable.sol

The following code snippet is the implementation of FlashLoan.sol.
This Flash Loan will be borrowing 1 DAI.

pragma solidity ^0.6.6;
import "./FlashLoanReceiverBase.sol";
import "./ILendingPoolAddressesProvider.sol";
import "./ILendingPool.sol";

contract FlashloanV1 is FlashLoanReceiverBaseV1 {

    constructor(address _addressProvider) FlashLoanReceiverBaseV1(_addressProvider) public{}

 /**
        Flash loan 1000000000000000000 wei (1 ether) worth of `_asset`
     */
 function flashloan(address _asset) public onlyOwner {
        bytes memory data = "";
        uint amount = 1 ether;

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

    /**
  This function is called after your contract has received the flash loaned amount
     */
    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.
        // !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !!
        //

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

}

To summarize, we start by importing the dependencies required to execute our Flash Loan. Some of these dependencies are called abstract contracts. An abstract contract has at least one function that isn’t implemented. You can think of it as a blueprint of a house. A builder uses this blueprint to make a house. However, in our analogy the blueprint is an abstract contract, you are the builder, and the house is the derived contract.

In our case the Flash Loan contract is using an abstract contract called FlashLoanReceiverBaseV1. It provides necessary implementation details such as repayment of the Flash Loan.

Now to break down the code line by line.

  1. First, we have to define the solidity compiler version. In this case, it’s 0.6.6.

     2-4. Importing dependencies for the smart contract

      6. The FlashLoanV1 contract is inheriting from the FlashLoanReceiverBaseV1 contract.

      8. We passed the address of one of the Lending Pool Providers of Aave. In this case, we are providing the address of DAI Lending Pool. 

     13. We have defined a function called flashLoan. It takes the address of the asset we want to flash loan. In this case the asset is DAI.

14. We don’t have any need of data for the flash loan, so we are passing an empty string.

15. We are defining the number of DAI(in terms of wei which is 10^18) we want to loan.

16. We initialize the LendingPool interface which is ILendingPoolV1 provided by Aave so that we can call the flashLoan function.

17. Finally, we call our flashLoan function. The function takes 4 main parameters. First we pass the address which will receive the loan. In our case, it’s our own contract. Second, we pass the address of the asset. In our case, it’s the address of DAI in the Kovan network. Third, we pass the amount of assets, and in our case it’s 1 “ether” amount of units(or 10^18 in “wei” units). Last but not least, we pass the data value which in our case is an empty string.

24-31 Next, we define the second function which is executeOperation. It’s where we utilize the flash loan. It’s called internally after the flashLoan function is successfully executed. It takes 4 main parameter which are –
        1. The address of reserve to which we will have to pay back the loan.
        2. The amount of asset
        3. The fee that is charged by the protocol
        4. Additional parameter which is used internally by the function.

33. It checks if we received the appropriate amount of loan or else it will throw an error message.

34. At this point, this is where you would implement logic for any arbitrary use case.

40. We add the fee along with the loan amount by using add function provided by SafeMaths library.

41.At last we pay back the total debt or loan amount back to the lending pool.

Deploying The Contract

  1. First, open your MetaMask and set your network to “Kovan Test Network”.

2. Use this gist for defining the dependencies for flashloan smart contracts. Click each of the links and paste the code into the corresponding Solidity file you made earlier.
        a.ILendingPool
        b.IFlashLoanReceiver
        c. ILendingPoolAddressesProvider
        d. FlashLoanReceiverBase
        e. Withdrawable

3. Switch to the “Solidity Compiler” tab. Set the compiler to 0.6.6 and click on “Compile FlashLoan.sol”.

4. You should see some warnings but no error message.

5. Now, we are all set to deploy the contract to the Kovan network. Switch to “Deploy & Run Transactions” tab. Under the environment field, change it from JavaScript VM to Injected Web3. This should open MetaMask asking for your permission.

6. Make sure the “CONTRACT” field is set to FlashLoan.sol. Provide the address of LendingPool in the text field that is next to the deploy button. In our case, it will be 0x506B0B2CF20FAA8f38a4E2B524EE43e1f4458Cc5. Then click “Deploy”. It should open up MetaMask. 

Note: A list of all deployed contract addresses can be found here. There, you can find the addresses of various Lending Pools supported by Aave. Though the addresses are different for every token, the procedure remains the same.

7. Click on “Confirm”. Upon doing so, you should see a success notification from MetaMask. There should now be a “Deployed Contracts” in the side panel.

Funding The Flash Loan

Under the new “Deployed Contracts” tab, you will be able to copy the deployed contract’s address. We will come back to this step later; in the meantime we need to add some DAI to our Flash Loan contract. This is because Flash Loans need funds in the contract to successfully execute. For that, you can jump to this link to get some DAI tokens (be sure to connect to the “Aave v2 Market” with a little “K” in the top right corner). Click on the faucet, paste in your MetaMask wallet address, and wait for confirmation.

After obtaining confirmation, we are going to add the DAI token to MetaMask. For that, open your MetaMask. Click on “Add Token” at the bottom. In the “Token Contract Address” field enter 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD. This is the contract address for DAI in Kovan. After clicking “Next”, It should display the DAI you got from the faucet earlier.

Next up, click on the DAI token. Click on “Send” and it should open a window similar to the picture below.

Enter our Flash Loan’s contract address, which we found out where to obtain earlier. Enter the amount which we want to send. In our case, we will send 10 DAI. Then click on “Next”. Click on “Confirm”! You have now successfully given your Flash Loan contract 10 DAI.

Executing The Flash Loan

Head back to Remix. Under the deployed Flash Loan contract, there’s another “flashloan” text field. This field takes a contract address of the asset we want to use. In our case it’s the Kovan Testnet’s DAI contract, which is 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD. With that field correctly filled in, you can now hit the “transact” button as shown below.

Upon clicking the button, MetaMask should pop up asking for approval of the transaction. Confirm the transaction and you should be greeted by a success message. In Remix’s terminal you should see an URL. Click on that and you should be redirected to Etherscan.

Under “Tokens Transferred”, you should see three different transactions.

  1. The red arrow highlights the transfer of 1 DAI from LendingPool to our contract.
  2. The orange arrow indicates the payback of 1 DAI along with the fees back to the Landing pool.
  3. The blue arrow shows the interest generated DAI which has its separate utility.

Conclusion

We were successfully able to write the smart contract for a Flash Loan! We were able to borrow DAI from the pool, pay the Flash Loan fee, and then repay the borrowed amount all in a single transaction. You just borrowed money with no collateral!

About the author 

Radiostud.io Staff

Showcasing and curating a knowledge base of tech use cases from across the web.

TechForCXO Weekly Newsletter
TechForCXO Weekly Newsletter

TechForCXO - Our Newsletter Delivering Technology Use Case Insights Every Two Weeks

>