Detailed explanation of flash loan technology: Part 1

The bear market is like a touchstone. Which of the core formats of DeFi can go through cycles and develop better? What problems have been exposed in the cycle that are worthy of reference for later generations? SharkTeam Contract Security Series Course [DeFi Security] will discuss and deepen with you. Lesson 2 [Detailed explanation of flash loan technology].

The article is longer and divided into 3 parts, this is part 1:

1. Flash loan principle and application scenarios;

2. Flash loan contract realization and risk prevention.

3. Analysis of flash loan related project agreement.

Introduction to the principle of flash loan

1.1 Concept Description

As the name suggests, a flash loan is to complete the loan and repayment operations in a very short period of time (one block time or one transaction).

In the DeFi field, flash loans provide mortgage-free loan services for financial businesses and are a powerful tool in the DeFi world.

The concept of flash loan was first proposed by the Marble protocol and popularized by Aave, dYdX, Uniswap and other protocols. The first flash loan operation came from the Aave protocol.

1.2 Design principle

The flash loan is to complete the zero-risk loan business through the atomicity of smart contracts, so the flash loan business can only be realized by smart contracts.

To put it simply, in a block transaction, the two operations of borrowing and repayment are completed at the same time, without any need to mortgage any assets, and only need to pay the handling fee.

After borrowing money, users can use the borrowed assets for other operations, such as arbitrage, repayment of mortgage loans, self-liquidation and other operations.

Then at the end of the transaction, the user only needs to return the borrowed money and handling fee in time, otherwise the transaction will be rolled back as if nothing had happened.

What is atomicity?

Atomicity here refers to transactions that are atomic . The atomic transaction is indivisible and cannot be interrupted by any other operation until the transaction is completed. All operations in the transaction are either successfully executed or all failed, and there will not be a situation where one part succeeds and another part fails.

Each transaction in Ethereum is atomic, and each transaction in Ethereum can contain multiple operations, such as:

l Borrowing and repaying money from dYdX;

l Provide ETH on Compound and lend DAI;

l Exchange half of the loaned DAI for USDC on Curve;

l Provide liquidity for DAI/USDC pools on Uniswap, etc.

All of these operations can be done in one transaction at the same time, and if one of them fails, the entire transaction will fail and roll back as if nothing happened.

A single transaction is only limited by the gas fee and the block capacity of Ethereum, so theoretically there can be thousands of operation steps.

1.3 Success Stories

First of all, the most important thing to execute a flash loan is to find a flash loan provider.

Projects such as Aave or dYdX have developed smart contracts that allow DeFi users to borrow different coins from designated pools, provided they are repaid within the same Ethereum transaction.

There is usually a fixed cost to use a flash loan. For example, the Aave contract requires the borrower to return the initial amount + 0.09% of the borrowed amount. The 0.09% fee will be split between depositors and integrators, the former providing funds to borrow and the latter facilitating the use of Aave’s Flash Loan API. A portion of this fee will also be exchanged for AAVE tokens.

Detailed explanation of flash loan technology: Part 1

Detailed explanation of flash loan technology: Part 1

Once the amount is borrowed from the lending pool, it can be used for other arbitrage operations, as long as the loan is repaid quickly at the end of the blockchain where the different steps are located.

Since the loan must be repaid within one transaction, there is no risk that the borrower will not repay the loan. The only risk is the smart contract and platform risk that has always existed.

1.4 Flash loan and flash exchange

Flash Loan and Flash Swap are unique concepts of blockchain. The table below shows some key differences between the two.

Detailed explanation of flash loan technology: Part 1

A Flash Loan must be repaid with the same asset you borrowed: if you borrow Dai, you need to repay the Dai. Interest-earning protocol Aave charges 0.09% for flash loans. It requires at least three operations:

1. Borrow on Aave

2. Exchange on a DEX

3. Carry out an arbitrage trade on another DEX to realize a profit, and finally repay the borrowed and flash loan fees.

Flash Swap allows traders to receive an asset and utilize it elsewhere before paying (or returning) the asset later in the transaction. Lightning Swap has no fixed fees, as it is done on Uniswap, but charges a swap fee. Compared to flash loan, flash exchange can be considered as a “free” loan, because the exchange fee is deducted from the transaction order and we do not have to pay separately. One last difference: we can repay any asset that is exchanged. If we buy Dai with ETH using Lightning Exchange, it can be repaid with either Dai or ETH, which allows us to perform more complex operations.

Both flash swaps and flash loans use Optimistic Transfers , a fascinating technique we’ll cover later.

1.5 Optimistic transfer

Both flash loans and flash exchanges use a technique called “optimistic transfers.” This amazing DeFi innovation enables users to make unsecured loan or exchange transactions, which can be executed as long as the user pays off the loan at the end of the transaction. To better understand the idea, let’s look at some code.

1.5.1 Optimistic transfer in flash loan

This is the code for the LendingPool.sol contract of Aave (V1) . Let’s pay attention to the implementation of the flashLoan function , especially the following methods:

Detailed explanation of flash loan technology: Part 1

In line 878, we can see that the smart contract “optimistically” transfers funds to the user’s contract – it does not check the user’s contract’s balance to ensure the user has enough assets to repay the loan, and just transfers.

how can that be? Wouldn’t users run away with these tokens? Well, if this is the end of the deal, it’s going to be a serious problem. But as you can see, the code is not over yet. Whether or not the user’s contract retains these tokens depends on the successful execution of the next few lines.

After the optimistic transfer, on line 881, we see that the Aave contract then calls the user’s contract with the token’s Optimistic Balance and whatever parameters the user has passed in. These parameters will be whatever the user needs to pass to their contract. The transaction was executed successfully. Now, the transaction workflow is temporarily suspended on the Aave contract and moved to continue execution on the user’s contract, which will execute its logic and hopefully successfully trade.

At line 884, the user’s contract code has been executed, and the workflow now returns to the Aave contract, which checks the value returned by the user’s contract using the require statement. The optimism ends here, now we have to see if the user contract has executed a profitable transaction! If so, the Aave contract will be able to deduct its fees. If the transaction is not profitable, the require statement will fail, which means the entire transaction will fail, and it also means that our previous optimistic transfer doesn’t actually happen.

1.5.2 Optimistic transfer in Lightning Exchange

Let’s take a look at how Uniswap achieves its optimistic transfers. This is from their UniswapV2Pair.sol contract, paying special attention to the swap function:

Detailed explanation of flash loan technology: Part 1

The optimistic transfer occurs in lines 170-171, which is the _safeTransfer method. Uniswap even gives a note of this optimistic transfer to better identify it (by the way, Uniswap provides extensive documentation and tutorials on its protocol contracts ). The next line is the Uniswap contract calling the user’s contract with an optimistic balance.

Again, assume that the transaction workflow suspends execution on the Uniswap contract and carries the optimistically transferred tokens to the user contract to continue execution. Once the user contract is executed, the transaction workflow returns to the Uniswap contract. The Uniswap contract then allocates the new balance of the user contract and attempts to charge a swap fee (lines 180-181).

If the user contract fails to monetize the token, the require statement in section 182 will fail and the entire transaction will be rolled back. This is the key to an optimistic transfer, which is 100% dependent on the success of the transaction. If unsuccessful, the transaction is invalid and will revert to the state it was in before the token transfer. However, if successful, the transfer can be kept optimistic and the user can profit.

2 Flash loan application scenarios

The three most common use cases for flash loans are Arbitrage, Swapping Collateral, and Self-Liquidation.

Detailed explanation of flash loan technology: Part 1

2.1 Arbitrage

Arbitrage, i.e. flash loans, can magnify the profits of successful arbitrage.

Let’s imagine a price difference for the DAI/USDC pool between Uniswap and Curve. You can exchange 1 DAI for 1 USDC on Curve, but on Uniswap you only need 0.99 DAI to buy 1 USDC. Now you can try to perform the following arbitrage:

1. Borrow 100,000 DAI from Aave via a flash loan.

2. Exchange 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 the initial 100,000 DAI + 0.09% Fees = 100,090 DAI

5. Interest 101,010 DAI – 100,090 DAI = 920 DAI

Throughout the arbitrage process, we must take into account the following factors:

Detailed explanation of flash loan technology: Part 1

1. Network Fees : The network fee here refers to the handling fee (such as the gas fee in Ethereum) to be paid when the transaction is written into the blockchain after the blockchain consensus. Multi-step arbitrage transactions can be expensive, so be sure to factor in handling fees when calculating profits.

2. Price Slippage : Be sure to calculate how much price slippage you will encounter when executing an order (hint: it depends on the size of the transaction and the liquidity of the liquidity pool).

3. Frontrunning : There is a good chance that others will find the same opportunity and will try to get one step ahead of you. On top of that, bots monitoring the mempool can spot your profitable arbitrage opportunities and “steal” your profit opportunities by sending the same transaction with a higher gas fee.

2.2 Swapping Collateral

Suppose you borrow DAI from Compound using ETH as collateral. You can exchange collateral from ETH to eg BAT by:

1. Initiate a flash loan to lend DAI

2. Repay the loan in Compound with borrowed DAI

3. Withdraw your ETH

4. Exchange your ETH for BAT on Uniswap

5. Provide BAT as collateral for Compound

6. Lend DAI against your BAT collateral

7. Repay the flash loan from step 1 with borrowed DAI + Fees

Through such a round of operation, you can successfully exchange your collateral from ETH to BAT by paying an additional 0.09% of the loan amount.

2.3 Self-Liquidation

Imagine the following scenario:

You have a loan on Compound that takes out DAI with ETH as collateral. ETH prices are falling and are approaching liquidation levels. You also don’t have or don’t want to deposit more ETH to lower your liquidation level, nor do you have the DAI required to repay the loan. Now, instead of having the MakerDAO contract liquidate your collateral and charge you a liquidation fee, take the following steps:

1. Initiate a flash loan and lend a DAI, the amount is your debt on Compound

2. Repay DAI loan on Compound, withdraw ETH

3. Exchange enough ETH for DAI to repay the flash loan + fees from step 1

4. Take your remaining ETH

After the above steps, self-liquidation can be achieved, avoiding contract liquidation and liquidation fees.

Posted by:CoinYuppie,Reprinted with attribution to:
Coinyuppie is an open information publishing platform, all information provided is not related to the views and positions of coinyuppie, and does not constitute any investment and financial advice. Users are expected to carefully screen and prevent risks.

Like (0)
Donate Buy me a coffee Buy me a coffee
Previous 2022-08-05 10:48
Next 2022-08-05 10:49

Related articles