How to create your own Flashloan in Aave

Programming Image

It took a few bucks to make a huge profit 1,271 ETH that was equivalent to $3,600 at that time with Flashloan. This Flashloan magic sounds indescribable and simply amazed a lot of people when it occurred. There have been some actual transactions in the underlying blockchain and some people really crazed. In this blog, I’d like to introduce what a Flashloan is (please skip if you know the term already) and step-by-step guide how to write it in Aave protocl with solidity programming language. I tested it could run in Ropsten test network already.

There was a barrier for non-IT people and beginners to perform a Flashloan because of programming skill (solidity programming language is used mostly). Implementation of smart contracts was required to perform such transactions. If you think you’re not that kind of person, I published how to do a Flashloan without coding in Furucombo service. Please check this out.

How to create a Flashloan transaction without coding?

What is a Flashloan?

Let’s take this sentence from Aave document.

Performing a Flash Loan

Flash Loans are special uncollateralised loans that allow the borrowing of an asset, as long as the borrowed amount (and a fee) is returned before the end of the transaction. There is no real world analogy to Flash Loans.

I think you might have the understanding what a normal loan is already. A normal loan means you a borrower can take out either money, asset, or property that is expected to be paid back with interest to lender in the future. Flash Loans are special uncollateralised loans that allow the borrowing of an asset, as long as the borrowed amount (and a fee) is returned before the end of the transaction. Now you don’t need any collateralization or interest to borrow money (assets) in DeFi but only some fees plus transaction costs only. There are various protocols providing Flashloan such as dYdX, Aave and Uniswap. Flashloans might open a door for everybody to borrow massive amount of money in crypto world. As long as the liquidity pool allows to lend and that amout is available in the pool, people can borrow unlimited money.

The nuances of Flashloans vary in the providing protocols. We will cover only Aave Flashloan for now but this article is the comparison of the different flashloan providers (Aave, dYdX and Uniswap).

Comparison betwen Flashloan providers: Aave vs dYdX vs Uniswap

How to do a Flashloan in Aave?

According to the official document, there are 3 ways to perform a Flashloan by your hands. I’ll perform a simple way by creating smart contract files and compile it and deploy in my project directory, which is No.1 case.

  1. In your project
  2. With Truffle box
  3. With Remix

You need to install Truffle and run the command truffle init to create a Truffle project. I located all required smart contract files under the directory named aave as below. Please refer the files in this repo or download the smart contracts from Aave repo.

aave_flashloan

$ truffle version
Truffle v5.0.36 (core: 5.0.36)
Solidity v0.5.8 (solc-js)
Node v13.7.0
Web3.js v1.2.1

$ truffle init

$ ls -al
drwxrwxr-x  2 user user 4096 Jun 24 12:17 contracts
drwxrwxr-x  2 user user 4096 Jun 24 12:17 migrations
drwxrwxr-x  2 user user 4096 Jun 24 12:17 test
-rw-rw-r--  1 user user 4235 Jun 24 12:17 truffle-config.js

$ cd contracts
$ mkdir aave

$ ls -al
-rw-rw-r-- 1 user user Jun 24 21:09 Address.sol
-rw-rw-r-- 1 user user Jun 24 13:33 EthAddressLib.sol
-rw-rw-r-- 1 user user Jun 24 21:10 FlashLoanReceiverBase.sol
-rw-rw-r-- 1 user user Jun 24 21:03 IERC20.sol
-rw-rw-r-- 1 user user Jun 24 13:34 IFlashLoanReceiver.sol
-rw-rw-r-- 1 user user Jun 24 20:46 ILendingPoolAddressesProvider.sol
-rw-rw-r-- 1 user user Jun 24 12:26 ILendingPool.sol
-rw-rw-r-- 1 user user Jun 24 13:40 SafeERC20.sol
-rw-rw-r-- 1 user user Jun 24 13:36 SafeMath.sol

Now you have to write your own flash loan in a file FlashLoan.sol in the directory contracts. What does this contract do? Let me simplify what we need to code with 3 stemps. As you notice, we just need to code only 2 functions for the minimum implementation. Sweet.

  1. Invoke the flash loan function flashloan from Aave lending pool to a specified address
  2. Lending pool transfer send borrowed assets to the specified address and call the function executeOperation on the specified address
  3. The same function executeOperation needs to return the debt with 0.09% fee in borrowed asset

Here are the interfaces I used for my implementation. I’ll show how to code each function in the next section.

function flashloan(
        address _asset,
        uint256 _amount
) external {}

function executeOperation(
        address _reserve,
        uint256 _amount,
        uint256 _fee,
        bytes calldata _params
) external {}

How to code a Flashloan in Aave for Ropsten

It looks straightforward. Please note that I did not perform any financial transactions such as arbitrage or swap tokens in the function executeOperation but just borrowed ETH and reimburse it immediately.

If you got some ideas what to do, please replace the lines with what you’d like to do at 29 and 30 in this gist.

Our flashloan function calls another flashloan function. What is this? This is the Lending Pool smart contract that was deployed at the address of Ethereum network. This address depends on which environment you will borrow money from (means Mainnet, Ropsten, Kovan). Additionally this Lending Pool address can be given by the Lending Pool Address Provider contract. In this example I used Ropsten network so the Lending Pool address provider is 0x1c8756FD2B28e9426CDBDcC7E3c4d64fa9A54728.

Please confirm your deploying environment and asset from this official link and replace the address in the contract file aave/FlashLoanReceiverBase.sol with your Lending Pool address provider.

The Lending Pool’s flashloan needs some parameters, _receiver is an address where the Lending Pool sends money out. So if you treat a token for example DAI, you will have to allow transfer from the Lending Pool to the appropriate address in advance. _reserve is the contract address of the underlying asset, so if you borrow DAI then this is the contract address of DAI.

Let’s look through the executeOperation function now. Do you remember the flashloan should be executed with _receiver? The Lending Pool will call in executeOperation at the address of _receiver next.

In this function it’s free whatever you want, you can assemble your money-legos and reimburse the borrowed money to the Lending Pool at last.

// Time to transfer the funds back
uint256 totalDebt = _amount.add(_fee);
transferFundsBackToPoolInternal(_reserve, totalDebt);

(Optional) How to compile and deploy a contract in network?

If you’re familier with Truffle that’s quite easy to deploy a smart contract and call it. Here’s some commands you can try in truffle console.

Compile the written smart contract codes locally and deploy the in Ropsten network.

$ truffle compile
$ truffle migrate --network ropsten

Get the deployed address and call your flashloan function for ETH reserves address in Ropsten. I borrowed 10 ETH from the Lending Pool and reimbursed the debt with the specified fee. Please note that you needed to transfer little ETH from your wallet to the deployed contract address because the contract address needs to pay the fee for borrowing.

truffle(ropsten)> let flashloan; Flashloan.deployed().then((ret) => { flashloan = ret; })
truffle(ropsten)> let result = await flashloan.flashloan("0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", web3.utils.toWei("10", "ether"))
truffle(ropsten)> web3.eth.getBalance(flashloan.address, (error, balance) => { console.log(web3.utils.fromWei(balance, 'ether')); })

If you haven’t set up truffle.js for main Ethereum network or Ropsten network to connect, you will need to add specific configuration with Infura setup. Here’s an example for Ropsten network.

Here’s the sample codes I used in github. I hope this does help for you.

aave_flashloan

Leave a Reply

Your email address will not be published. Required fields are marked *