Flash Loan Basics and Applications

Author

Reads 614

Rolled Money, Credit Cards on the Table
Credit: pexels.com, Rolled Money, Credit Cards on the Table

Flash loans are a type of loan that can be obtained in a matter of seconds, with the loan being repaid before any interest is even charged.

They typically involve a lender providing a short-term loan to a borrower, who then uses the funds to execute a transaction, such as buying or selling an asset, and repays the loan immediately.

One of the key characteristics of flash loans is that they don't require collateral, making them accessible to a wider range of borrowers.

Flash loans are often used by traders and investors to take advantage of market opportunities that might not be available otherwise, such as buying or selling assets at a favorable price.

Curious to learn more? Check out: Front Flash

What Is a Flash Loan?

Flash loans are unsecured loans where a borrower must repay their entire loan back to a lender in the same transaction. They're unique financial products found only in the DeFi world because smart contracts can force a user to pay the loan back immediately.

Credit: youtube.com, What are Flash Loans? (Animated) Borrow MILLIONS Instantly in Crypto

In traditional finance, there's no such primitive that exists. DeFi protocols like Aave and DyDx support flash loans, and some people believe MakerDAO and Uniswap support them too, but technically, they're "flash mints", which are very similar.

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.

Flash loans are available in the DeFi world, where smart contracts can enforce repayment. This is not possible in traditional finance.

Consider reading: Green Lending

Execution Flow

In a flash loan, the execution flow is surprisingly straightforward. Here's what happens in just one transaction:

Your contract calls the Pool contract, requesting a Flash Loan of a certain amount(s) of reserve(s) using flashLoanSimple() or flashLoan(). This is the starting point of the flash loan process.

The Pool contract then transfers the requested amounts of the reserves to your contract, and calls executeOperation() on the receiver contract. This is where the magic happens, and your contract receives the flash loaned amount(s).

Credit: youtube.com, What are Flash Loans? (Animated) Borrow MILLIONS Instantly in Crypto

Your contract, now holding the flash loaned amount(s), executes any arbitrary operation in its code. This is the moment when you can perform any operation you want, without actually having to pay for it.

All of the above happens in 1 transaction (hence in a single ethereum block). This is what makes flash loans so powerful and fast.

Applications and Uses

Flash loans are a powerful tool in DeFi, and they have a wide range of applications.

Aave Flash Loans are already being used for liquidity switch features, and other examples include arbitrage between assets without needing to have the principal amount to execute the arbitrage.

Arbitrage is a common use case for flash loans, where users can take a flash loan in BNB, immediately swap it for another asset on a DEX, and then immediately swap the obtained asset for BNB on another DEX where the asset's ratio is higher, and repay the loan + interest, keeping the difference.

Credit: youtube.com, Flash Loans Simplified: What Are They, Use Case, And Can You Make Money?

To use a flash loan, you need to find a smart contract that is flash loan compatible and has liquidity in it, such as Aave, dydx, or others, and build a receiver contract to execute whatever you want during the flash loan.

The most common use cases for flash loans include arbitrage, liquidation, collateral swaps, and other MEV opportunities.

Here are some specific examples of how flash loans are used:

  • Arbitrage between assets
  • Liquidating borrow positions without having to repay the debt of the positions
  • Collateral swaps

These use cases can be broken down into the following steps:

1. Find a flash loan compatible smart contract with liquidity

2. Build a receiver contract to execute the desired action

3. Repay the loan amount at the end

By following these steps, users can take advantage of flash loans to gain leverage and capital for various opportunities in DeFi.

Setting Up and Funding

To set up a flash loan, your contract must conform to the IFlashLoanSimpleReceiver or IFlashLoanReceiver interface by implementing the executeOperation() function.

Your contract also needs to give allowance to the Pool to pull funds to pay back the flash loan amount plus premiums.

Credit: youtube.com, Flash Loan Arbitrage | Aave Flash Loan Tutorial

First, you'll need to fund your smart contract with Polygon Mumbai Testnet USDC to pay the interest fee for the flash loan.

To get the USDC, go to Aave's faucet, select Polygon Market, and connect your MetaMask wallet.

Once you've connected, click the Faucet near USDC to receive the USDC.

Send some USDC (1 in this case) to the smart contract you deployed earlier, copying the contract address first.

This will fund your contract with the necessary USDC to cover the flash loan's interest fee.

On a similar theme: Fund Finance Loans

Security Considerations

Flash loans are a double-edged sword in the DeFi world, making it easier for less well-capitalized users to exploit vulnerabilities that traditionally only rich users could.

A common attack vector involving flash loans is a "price oracle manipulation" attack, where a protocol uses an exchange's liquidity to determine the price of an asset, and a flash loan crashes the price.

Using a decentralized exchange to get pricing information is a common mistake that can leave protocols vulnerable to attacks.

Credit: youtube.com, Understanding Flash Loan Attacks by The Blockchain Security Monk

Typically, defending against such attacks is as simple as not using a decentralized exchange to get your pricing information.

About $500 million worth of assets were stolen from DeFi platforms between 2020 and 2021, with flash loan attacks being a major contributor.

Here are some key takeaways to help protect yourself from flash loan attacks:

  • Use on-chain centralized price oracles, such as a single DEX, at your own risk.
  • Be aware of the potential for price oracle manipulation attacks.
  • Consider using oracles like Chainlink, which are powered by a decentralized network of oracles.

Protocols that rely solely on a single DEX as their price feed are particularly vulnerable to attacks carried out using flash loan vulnerabilities.

An oracle like Chainlink, however, is powered by a decentralized network of oracles, so while an attacker can carry out a single flash loan transaction, it still won’t affect the price feed as the exchange gets pricing data from multiple sources.

Smart Contract and Functions

Smart contracts are the backbone of flash loans, allowing us to read and write data to the blockchain by executing deterministic programs. They can be written in Solidity, a programming language used for EVM-based chains like Polygon.

Credit: youtube.com, FLASH LOAN ATTACK: Use the Deployer Router flaw and the Smart Contract 2024 [FULL TUTORIAL]

To create a smart contract for flash loans, we need to declare the Solidity version and import necessary contracts from Aave's V3 repository. The SimpleFlashLoan contract is started by interfacing Aave's FlashLoanSimpleReceiverBase contract, creating a variable owner, and making it payable.

Here are the main functions used in flash loan smart contracts:

Deploying the Contract

To deploy the contract, compile it and ignore the warning you get after compiling the smart contract. Make sure to select 0.8.10 as the Solidity compiler version.

The contract needs Aave's pool provider address to be deployed with it. Go to Aave V3 doc's Testnet Addresses page, select Polygon Mumbai, and copy the address of PoolAddressesProvider-Polygon.

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.

The contract will appear under the Deployed Contracts section once deployed. Copy the contract address and save it.

You might enjoy: Investment Loan Contract

Smart Contract

Credit: youtube.com, What are Smart Contracts in Crypto? (4 Examples + Animated)

Solidity is the programming language used to write smart contracts on Polygon Mumbai Testnet, which is an EVM-based chain. It's a deterministic program that allows us to read and write data to the blockchain.

Solidity files end in the .sol extension, and we can use it to create smart contracts like the Flash Loan Smart Contract. This contract allows us to take a Flash loan for USDC on Polygon Mumbai Testnet.

The contract starts by declaring the solidity version, importing necessary Aave V3 smart contract, Aave's lending pool manager contract, and ERC20 OpenZepplin contract from Aave's V3 contract repository. It then starts the SimpleFlashLoan contract by interfacing Aave's FlashLoanSimpleReceiverBase contract and making it payable.

Here are some key functions in a smart contract:

  • flashBorrow(address token, uint256 amount) - function that starts the flash loans flow.
  • onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) - the callback function called by flashLoan(). Use it to implement anything you want to do with the borrowed BNB tokens.

The onFlashLoan() function must return the CALLBACK_SUCCESS hash, as shown in the extract from the flashBorrower stub.

Credit: youtube.com, Smart contracts for beginners, explained (in 6 minutes) | Cryptopedia

To interact with SwapPool, an EOA calls flashBorrow(token, amount) on a borrowing contract flashBorrower.sol, and then the flashBorrower approves, in advance, SwapPool to access an amount of BNB equal to the loan + fee. The flashBorrower then calls the flashLoan(receiver, token, amount, data) function on SwapPool, which mints a specified amount to the flashBorrower.

SwapPool has several functions, including:

  • maxFlashLoan(address token) - returns “max” if token is a supported asset. Used in checking if the desired loan amount is lower than the max permitted amount.
  • flashFee(address token, uint256 amount) - applies “toll” on amount and returns if token is a supported asset.
  • flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) - mints token amount to receiver with extra data (if any), and expects a return equal to CALLBACK_SUCCESS.

Parameters/Constants

In a smart contract, parameters and constants are crucial elements that define the contract's behavior. The initiator address is the address of the flashBorrower smart contract deployed by an external account (EOA).

The token address is the address of the BNB ERC-20 token that the EOA flash-loans. The amount of the flash loan is a critical parameter, represented by a uint256 data type.

A technical service fee is paid for the flash loan, which is also represented by a uint256 data type. This fee is paid by the flashBorrower.

The data parameter is a rudimentary non-used parameter left unchanged to avoid altering the onflashLoan() signature.

Here are the parameters/constants in a concise table:

Frequently Asked Questions

What happens if you don't pay back a flash loan?

If you don't repay a flash loan, the transaction is reversed, and any profits or losses are cancelled. This is because flash loans rely on temporary collateral lending, which is returned once the loan is repaid

How is a flash loan different from a traditional loan?

A flash loan is different from a traditional loan as it's approved instantly, with the loan agreement fulfilled during the transaction. This expedited process is made possible by smart contracts, setting it apart from traditional lending methods.

Who provides flash loans?

Flash loans are provided by platforms such as Aave, Uniswap, dYdX, and MakerDAO, which offer instant, interest-free loans for traders and developers

How much is the fee of a flash loan?

The fee for a flash loan is 0.07% in Aave V2 and 0.05% in Aave V3. This fee is added to the borrowed amount and must be repaid in the same transaction.

Vanessa Schmidt

Lead Writer

Vanessa Schmidt is a seasoned writer with a passion for crafting informative and engaging content. With a keen eye for detail and a knack for research, she has established herself as a trusted voice in the world of personal finance. Her expertise has led to the creation of articles on a wide range of topics, including Wells Fargo credit card information, where she provides readers with valuable insights and practical advice.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.