How to Make a Flash Loan using Aave | QuickNode (2024)

8 min read

Overview

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. 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 to deploy an Aave V3 Flash loan smart contract!

Prefer a video walkthrough? Follow along with Sahil and learn how to make a flash loan using Aave in 19 minutes.

Subscribe to our YouTube channel for more videos!

Subscribe

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 EVM Smart Contracts. In this guide, we will deploy a smart contract on Polygon Mumbai Testnet.

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

How to Make a Flash Loan using Aave | QuickNode (1)

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.

Creating A Polygon Mumbai Endpoint

We will use QuickNode as a custom RPC in our MetaMask wallet to propagate transactions faster. This doesn't guarantee faster transaction confirmation but increases the chances of getting the transaction in front of a validator.Sign up for a free QuickNode Polygon Mumbai RPC here.

How to Make a Flash Loan using Aave | QuickNode (2)

Copy the HTTPS URL. We will need it in the next step.

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.
  5. Add the QuickNode Polygon Mumbai Testnet RPC we got in the previous step to MetaMask as a custom RPC. Learn how to add a custom RPC in MetaMask.
  6. Get some Polygon Mumbai Testnet MATIC; you can use QuickNode Multi-chain Faucet.

If the six steps outlined above are completed, you can start writing your first smart contract!

The Flash Loan Smart Contract

Smart contracts allow us to read and write data to the blockchain by executing deterministic programs. Polygon is EVM based chain, so we can use Solidity to write smart contracts on Polygon Mumbai Testnet. Solidity files end in the .sol extension.

We will take a Flash loan for USDC on Polygon Mumbai Testnet.

Create a new file, SimpleFlashLoan.sol, and copy-paste the following code into it.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;

import "https://github.com/aave/aave-v3-core/blob/master/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import "https://github.com/aave/aave-v3-core/blob/master/contracts/interfaces/IPoolAddressesProvider.sol";
import "https://github.com/aave/aave-v3-core/blob/master/contracts/dependencies/openzeppelin/contracts/IERC20.sol";

contract SimpleFlashLoan is FlashLoanSimpleReceiverBase {
address payable owner;

constructor(address _addressProvider)
FlashLoanSimpleReceiverBase(IPoolAddressesProvider(_addressProvider))
{
}

function fn_RequestFlashLoan(address _token, uint256 _amount) public {
address receiverAddress = address(this);
address asset = _token;
uint256 amount = _amount;
bytes memory params = "";
uint16 referralCode = 0;

POOL.flashLoanSimple(
receiverAddress,
asset,
amount,
params,
referralCode
);
}

//This function is called after your contract has received the flash loaned amount

function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external override returns (bool) {

//Logic goes here

uint256 totalAmount = amount + premium;
IERC20(asset).approve(address(POOL), totalAmount);

return true;
}

receive() external payable {}
}

The above smart contract is for Aave V3.

Explanation of the code above:

Line 1: Specifying SPDX license type, which is an addition after Solidity ^0.6.8. Whenever the source code of a smart contract is made available to the public, these licenses can help resolve/avoid copyright issues. If you do not wish to specify any license type, you can use a special value UNLICENSED or simply skip the whole comment (it won't result in an error, just a warning).

Line 2: Declaring the solidity version.

Line 4-6: Importing the necessary Aave V3 smart contract, Aave's lending pool manager contract, and ERC20 OpenZepplin contract from Aave's V3 contract repository.

Line 8-9: Starting the SimpleFlashLoan contract by interfacing Aave's FlashLoanSimpleReceiverBase contract, creating a variable owner of type address, and making it payable.

Line 11-12: Initializing the constructor with _addressProvider as a parameter will be the address of Aave's lending pool.

Line 16-21: Creating a function to borrow loan along with necessary parameters like receiverAddress, which will be the address of our smart contract once deployed, asset will be the address of the token we want to borrow (USDC in this case), amount is the amount of tokens we will be borrowing, and two other parameters which we won't be using but are required for Aave's contract.

Line 23-29: Interacting with Aave's pool to get the loan using the parameters from the previous function.

Line 34-50: Executing the Flash loan by calculating the premium (Interest fee), which is 0.09% of the borrowed amount, approving the ERC20 token with Aave's lending pool, and returning the loan amount.

Deploying The Flash Loan Contract

Compile the contract and ignore the warning you get after compiling the smart contract. Make sure to select 0.8.10 as the Solidity compiler version.Now that our contract is compiled, let's deploy it. We will need Aave's pool provider address to be deployed with the contract. Go to Aave V3 doc's Testnet Addresses page, select Polygon Mumbai, and copy the address of PoolAddressesProvider-Polygon.

How to Make a Flash Loan using Aave | QuickNode (3)

Paste the address near the Deploy button, select Injected Provider in the REMIX ENVIRONMENT, and deploy the contract. Once Deploy is clicked, approve the transaction from the MetaMask pop-up.

How to Make a Flash Loan using Aave | QuickNode (4)

Once deployed, the contract will appear under the Deployed Contracts section, copy the contract address and save it.

How to Make a Flash Loan using Aave | QuickNode (5)

Funding The Flash Loan

We will need some Polygon Mumbai Testnet USDC in our smart contract to pay our Flash loan's interest fee. Go to Aave's faucet, select Polygon Market, connect MetaMask, and get the USDC by clicking Faucet near USDC.

How to Make a Flash Loan using Aave | QuickNode (6)

Then send some USDC (1 in this case) to the smart contract we deployed in the previous step. Copy the smart contract address and send the USDC to the smart contract.

Executing The Flash Loan

Go to Aave V3 doc's Testnet Addresses page, select Polygon Mumbai, and copy the address of USDC reserve.

How to Make a Flash Loan using Aave | QuickNode (7)

Expand the smart contract under the Deployed Contracts section and expand the fn_RequestFlashLoan function button. Paste the USDC reserve’s address in the _token field and enter the amount of USDC to be borrowed (10 in this case) in the _amount field. When entering the number of ERC20 tokens in Solidity, we also need to mention the decimals of that ERC20 token. The decimals of USDC is six, so 10 USDC will be 10000000.

How to Make a Flash Loan using Aave | QuickNode (8)

Click the transact button, then approve the transaction from MetaMask. Copy the transaction hash and search for the transaction on Mumbai Polygonscan. You can see a Flash loan transaction with information about the borrowed and returned amount + interest.

How to Make a Flash Loan using Aave | QuickNode (9)

This is how you do a Flash loan on Aave V3!

Conclusion

Congratulations on performing a flash loan; you borrowed a loan without collateral. In this guide, we learned about flash loans, created and deployed an Aave V3 flash loan contract, borrowed some tokens without collateral, and returned it with an interest fee. Join ourDiscordif you have any questions, or reach out to us viaTwitter.

We ❤️ Feedback!

If you have any feedback or questions on this guide,let us know. We'd love to hear from you!

How to Make a Flash Loan using Aave | QuickNode (2024)

FAQs

How to flash a loan on Aave? ›

An Aave Flash Loan can be thought of in three simple steps:
  1. A user borrows tokens from one of Aave's lending pools.
  2. The parameters for the loan are executed on the Ethereum blockchain.
  3. The user must repay the borrowed amount plus Aave's loan service fee (0.09% as of 2021)

How to do a flash loan step by step? ›

How To Create a Flash Loan on Aave
  1. Step 1: Setup the Development Environment. ...
  2. Step 2: Install MetaMask Extension. ...
  3. Step 3: Create a Smart Contract. ...
  4. Step 4: Fund the Wallet. ...
  5. Step 5: Deploy the Contract. ...
  6. Step 6: Fund the Flash Loan. ...
  7. Step 7: Execute Flash Loan Contract.
Jan 22, 2023

How to use Aave to make money? ›

In order to interact with Aave protocol, you simply supply your preferred asset and amount. After supplying, you will earn passive income based on the market borrowing demand. Additionally, supplying assets allows you to borrow by using your supplied assets as a collateral.

How to take out a flash loan? ›

How do flash loans work?
  1. You apply for a flash loan on a relevant platform (ex. Aave, Uniswap).
  2. You create a logic for the loan through coding. ...
  3. If your loan is approved, the sub-transactions outlined in the step above will be completed in a single blockchain transaction.

How much does AAVE charge for flash loans? ›

Flash loans allow any user to access large uncollateralized loans, but the borrowed assets must be returned plus a fee within a single transaction. The fee is 0.09% of the flash loan volume, which is a source of revenue for the Aave protocol.

What is the flash loan strategy? ›

Arbitrage Opportunities

Through a flash loan, the trader can instantly borrow Ether, buy it at a lower price on Exchange A, sell it at a higher price on Exchange B, and repay the loan, all within the same transaction, pocketing the price difference as profit.

How to borrow money from Aave? ›

To borrow, you deposit 10 ETH into Aave and enable them as collateral. The loan-to-value ratio for borrowing ETH is 80% on Aave. This means you can borrow up to 80% of your collateralized asset's value. So if ETH is worth $4,000, you can borrow $3200 worth of value — with your choice of a stable or variable APR.

How long does a flash loan last? ›

Flash loans are created and paid back instantly - therefore, the borrower never actually takes possession of the borrowed capital. Since the borrow and repay transactions must occur in the same block, there is never actually any period of time during which the borrower needs to “pay back” the loan.

What is an example of a flash loan? ›

Flash loans represent essentially risk-free arbitrage opportunities; for example, if a cryptocurrency is being traded for $1 on one exchange and for $2 on another, a savvy trader can use smart contracts to take out a flash loan of $100 worth of the cryptocurrency on the first exchange, sell it for $200 on the second ...

What is a flash loan hack? ›

In flash loan attacks malicious actors use the temporary uncollateralized liquidity provided by flash loans to manipulate the price of a crypto currency,exploit vulnerabilities in a DeFi smart contract, or steal funds from a protocol.

What happens if a flash loan fails? ›

If the user fails to do so, the entire transaction is reverted, and the lender receives back the original funds without any loss. Profit or Loss: Depending on the success of the executed actions, the user may profit from the borrowed funds.

Is there a limit on flash loans? ›

Provided there's enough liquidity in the pool(s) to conduct your transaction, there's no limit to the amount you can loan in a flash loan.

How do I take out a loan from AAVE? ›

Just deposit your AAVE to your YouHodler wallet, pick one of our three loan plans (custom loan plans available upon request), and then in seconds, you'll see your funds arrive in your fiat or stablecoin wallet. Then when you pay back the loan, you get your AAVE back even if it's increased in value.

How can I clear my loan early? ›

5 Ways To Pay Off A Loan Early
  1. Make bi-weekly payments. Instead of making monthly payments toward your loan, submit half-payments every two weeks. ...
  2. Round up your monthly payments. ...
  3. Make one extra payment each year. ...
  4. Refinance. ...
  5. Boost your income and put all extra money toward the loan.

Does AAVE report to IRS? ›

Yes. Your Aave transactions are taxable and you'll need to pay tax on them. The tax you'll pay all depends on the specific transaction you're making - but you'll pay either Income Tax or Capital Gains Tax. Let's break it down.

How does a flash loan work? ›

Flash loans are uncollateralized loans in which a user borrows funds and returns them in the same transaction. If the user can't repay the loan before the transaction is completed, a smart contract cancels the transaction and returns the money to the lender.

Top Articles
A Digital Diet: The Benefits Of Going Offline | Life Insight | Therapy for LaGrange
Gnosis
Craigslist Livingston Montana
It’s Time to Answer Your Questions About Super Bowl LVII (Published 2023)
Warren Ohio Craigslist
Was ist ein Crawler? | Finde es jetzt raus! | OMT-Lexikon
Beacon Schnider
Sarah F. Tebbens | people.wright.edu
Plus Portals Stscg
Nwi Police Blotter
What Is Njvpdi
Mens Standard 7 Inch Printed Chappy Swim Trunks, Sardines Peachy
Dumb Money
Kinkos Whittier
Dr Manish Patel Mooresville Nc
Nashville Predators Wiki
Yakimacraigslist
Kylie And Stassie Kissing: A Deep Dive Into Their Friendship And Moments
Kp Nurse Scholars
Account Suspended
ELT Concourse Delta: preparing for Module Two
Little Caesars 92Nd And Pecos
Samantha Aufderheide
Craigslist Houses For Rent In Milan Tennessee
Providence Medical Group-West Hills Primary Care
If you have a Keurig, then try these hot cocoa options
Bocca Richboro
Bn9 Weather Radar
Timeline of the September 11 Attacks
55Th And Kedzie Elite Staffing
Inter Miami Vs Fc Dallas Total Sportek
Rural King Credit Card Minimum Credit Score
Productos para el Cuidado del Cabello Después de un Alisado: Tips y Consejos
Roch Hodech Nissan 2023
Gerber Federal Credit
PA lawmakers push to restore Medicaid dental benefits for adults
Skill Boss Guru
3496 W Little League Dr San Bernardino Ca 92407
Www.craigslist.com Waco
Trivago Anaheim California
Lucyave Boutique Reviews
Citroen | Skąd pobrać program do lexia diagbox?
Big Reactors Best Coolant
9:00 A.m. Cdt
Doe mee met ons loyaliteitsprogramma | Victoria Club
Boyfriends Extra Chapter 6
Diario Las Americas Rentas Hialeah
Evil Dead Rise - Everything You Need To Know
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Vt Craiglist
Latest Posts
Article information

Author: Kimberely Baumbach CPA

Last Updated:

Views: 5954

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Kimberely Baumbach CPA

Birthday: 1996-01-14

Address: 8381 Boyce Course, Imeldachester, ND 74681

Phone: +3571286597580

Job: Product Banking Analyst

Hobby: Cosplaying, Inline skating, Amateur radio, Baton twirling, Mountaineering, Flying, Archery

Introduction: My name is Kimberely Baumbach CPA, I am a gorgeous, bright, charming, encouraging, zealous, lively, good person who loves writing and wants to share my knowledge and understanding with you.