MultiversX Tracker is Live!

What are Flash Loans and How Do They Work?

CEX.IO

Cryptocoins Exchanges / CEX.IO 321 Views

Introduced in 2018 by open source bank, Marble, and eventually implemented in early 2020 by Aave, flash loans are a type of decentralized and uncollateralized lending product. These loans acquaint an innovative and impactful method to decentralized finance (DeFi) users of near instantaneous trade and arbitrage opportunities. The digital engine that powers these loans make such opportunities possible, as a product like this can’t exist without blockchain-based infrastructure backing it. Much like traditional DeFi loans, flash loans include a lender, who offers a loan, and a borrower, who owes debt to the lender, however, they have the distinct properties of being instantaneous and uncollateralized which differentiates their capabilities, use cases, and function.

Instant – Traditional bank loans, and DeFi loans, play out over the course of hours, days, months, or even years. Flash loans, on the other hand, are instantaneous as lending, borrowing, and payback procedures are executed in a single transaction. To accomplish this, the borrower must perform instant trades with the loaned capital before the transaction ends (transaction hash), which typically takes only a couple seconds. Additional smart contracts outside the scope of the contract between the borrower and the lender are needed to complete this process, which are bundled together with the loan and executed simultaneously in a single transaction.

Uncollateralized – Overcollateralization is the key feature of traditional DeFi loans that allows them to be efficient on the fronts of accessibility and volatility risk, which benefits both lenders and borrowers in different ways. Flash loans are unsecured, meaning they don’t require any collateral. Instead, it leverages the single instantaneous transaction mechanism to ensure that borrowers are protected and will get their assets back. 

Structure of Flash Loans and Impact on Risk

Lenders bear risk with traditional bank loans and DeFi loans alike, as they are the ones sacrificing assets that are transferred to the borrower. To offset risk for lenders, these loans use interest rates and overcollateralization; this ensures that lenders are protected and compensated for the risks they take related to the borrower’s ability to pay back the loan (default risk) and their own ability to pay down their obligations while acting as a lender (illiquidity risk). As it relates to protecting lenders from risk with flash loans, there is no collateral involved and there is no time for the loan to accrue interest. Instead, the notion of ‘atomicity’ connected to the instantaneous execution of the loan protects lenders from any risks associated with the borrower defaulting or their own liquidity. Atomicity means that all components of a transaction can be completed, or it won’t be executed at all. This mechanism protects DeFi lenders of flash loans to ensure that they will get their assets back despite the loan being uncollateralized. In this case, if the borrower can’t pay back the loan it simply won’t execute, thus flash loans bear no risk and no opportunity cost for lenders. Additionally, flash loan borrowers pay a fee, typically between .1% to .35% of the loan size, which is used to incentivise lenders.

&

loan_contract

&

Borrowers also face the risk that they won’t be able to pay a loan back when it’s due. Future circumstances are unpredictable and can land borrowers in a position where they are insolvent; this progressively becomes the case as the life of a loan increases. Similarly to how they protect lenders, the concept of atomicity and the shortened timeline of flash loans protects borrowers from the risk that they won’t be able to pay off their debt. This same mechanism is what allows borrowers to take out a loan without sacrifice.

Who Uses Flash Loans and Why?

The requirement that the loan must be distributed and paid back in a single transaction hinders expansive use of flash loans and favors their use by sophisticated borrowers. Nonetheless, users have discovered unique ways of leveraging these loans by applying them to arbitraging, speculating, and swapping assets, among a number of other niche uses.

Arbitrage – The primary use case for flash loans is arbitraging to exploit price differences in assets across decentralized exchanges. Leveraging flash loans in this case allows users to take out a loan in order to buy an asset on one exchange to sell it on another; the loan, plus the fee, is then paid back and the borrower keeps the difference as profit. Using flash loans as an arbitrage tool leads to efficiency in the decentralized market for cryptocurrencies. By allowing anyone in the world to arbitrage at minimal cost and no risk, flash loans allow prices across various disparate, decentralized markets to intersect with each other and lower spreads. This process requires additional contracts to execute the swap, which looks as such:

arbitrage_contracts
  1. A borrower takes out a flash loan for 1,000,000 USDT
  2. The borrower takes the USDT to Dex A and converts it to ETH @ $4,000 USDT/coin (250 ETH)
  3. The borrower then takes the 250 ETH to Dex B where it is converted back into USDT @ $4,020/coin (1,005,000 USDT)
  4. The borrower pays back the loan and keeps the residual balance as profit

Speculating – The uncollateralized component of flash loans has made them attractive for market speculators. The fact that borrowers can receive assets without giving anything up in return has allowed speculators to get creative with how the volatility of the market can be exploited. Though the highly short term nature of flash loans makes it difficult, some users have found ways to speculate on coins and earn profit instantaneously without sacrifice or risk.

Collateral – Traditional DeFi loans allow for several types of assets to substitute each other as collateral during the life of a loan, called multi-collateral deposits. Flash loans have an intersection with traditional DeFi loans in that they allow users to efficiently adjust their collateral without having to close and reopen a loan using new collateral, or unnecessarily sacrifice additional assets and resources. Instead, if it is believed that one form of collateral is going to overperform the other, users can simply borrow then swap for the new collateral using a flash loan and use the old collateral to pay the loan off. Applying flash loans to this use allows users to generate stronger returns with marginal compromise and keep trading positions open. Below is a simplified visualization of how this dynamic works:

defi_loan

The infantility of the product juxtaposed against the rapidly expanding DeFi ecosystem suggests that the capabilities of flash loans are just beginning to scratch the surface. As users become more comfortable using them and as the architecture around them becomes more refined, flash loans will begin to have an even greater impact on how decentralized finance is shaped.

&

Flash Loan Attacks

Flash loans as a concept and as a piece of infrastructure are still a work in progress, which has attracted attackers to protocols offering them. There is a distinct difference between a flash loan ‘attack’ and ‘hacking’ a protocol. Those who are successful in obtaining assets through flash loan attacks aren’t breaking into the protocol to gain unauthorized access to funds (hacking); instead they are exploiting the underlying vulnerabilities in the terms of the smart contracts that govern the loans. Attackers find these vulnerabilities left by developers and use them to withdraw funds, meaning they make use of the toolkit present in the smart contract from the beginning, rather than accessing funds under a smart contract by breaching it.

What Makes Flash Loan Attacks Attractive?

Flash loans have become attractive to those who exploit them because of the low risk, low cost, and necessary swapping component that is required to execute them. 

Low Risk – Attacking a flash loan comes at little to no risk whether the attacker is successful or not. The relationship between attacker and protocol is anonymous, so it’s impossible to identify the culprit beyond their address if they are successful in executing the loan and extracting funds. While it helps to identify the attacking user’s address in that it can be noted where the stolen funds are moving, it doesn’t allow for the attacker to be held responsible or stop them from committing another attack.

Low Cost – Flash loans require minimal, if any, upfront capital to be sacrificed by attackers because the loans are uncollateralized. Carrying out these attacks at little to no monetary cost adds incentive and broadens the pool of potential attackers.

Swapping – Multiple smart contracts and protocols are lumped together to form and execute flash loans. This opens up the door for a greater chance of errors left by developers or components that can be exploited/manipulated by attackers. 

Types of Flash Loan Attacks and Case Studies

Price Manipulation Attacks

Manipulating the values of a loan’s underlying asset is a popular method of attacking flash loans. Using this process, attackers will simultaneously use the loaned assets to short sell an asset on one platform then borrow the shorted asset to sell it and crash the price on a corresponding exchange. This kind of attack is most successful on exchanges and platforms that leverage a single oracle or price feed.

DyDx, Fulcrum (built on bZx), and Compound were leveraged to conduct a scheme like the one outlined above when an attacker walked away with nearly $400,000 USD in profit. DyDx originated the flash loan of 10,000 WETH (wrapped Ethereum), which equated to ~$3m USD after fees at the time. Wrapped Ethereum is an ETH pegged token that allows it to be exchanged for other ERC-20 tokens, like WBTC (wrapped bitcoin), which are widely used in DeFi and DeFi loans. After obtaining the 10,000 WETH loan, the attacker had the resources necessary to short the asset of their choosing then borrow for the same asset to crash the price.

flash_loans_flow

The attacker first took half of the loaned assets, 5,000 WETH, to Fulcrum, a margin trading platform, where they opened up a position to short the price of WBTC. They then took the other 5,000 WETH to Compound, a DeFi lending protocol, where they borrowed the 112 WBTC that was used to crash its price. Fulcrum exclusively used Uniswap’s, a decentralized exchange, price feeds, which allowed the attacker to sell on the exchange to profit off the short position. After closing the short and selling the WBTC back into WETH on Uniswap, the attacker paid back their obligation to the lender and walked away with the profit.

Quick back of the napkin math shows the scalability of these attacks and how similar ones have allowed attackers to capture millions in profits. Using this particular attack as an example: When the attacker shorted 112 WBTC they were effectively borrowing 112 WBTC from other entities in order to sell them; this loan has to be paid back when the position is closed. The price of BTC at the time was roughly $10,000 USD, which gave the attacker $1,120,000 USD. Thus, they only owed $1,008,000 to close the position when the price of BTC dropped to $9,000 USD on Uniswap. This left the attacker with $112,000 USD in profit in addition to the remaining balance after borrowing WBTC and selling it back into WETH on Uniswap.

Reentrancy Attacks

A reentrancy exploit is a sophisticated flash loan attack that allows an attacker’s contract to be called on again and again before the accounting of the original loan has been settled; meaning an attacker can repeatedly receive assets from a protocol’s smart contract without it, or the protocol, being able to identify what is happening. In some instances, a smart contract created by a protocol will want to call an external contract’s (attackers contract) procedures to execute; such as a “safe transfer from” condition which allows attackers to withdraw a protocol’s assets. Reentrance attacks occur when the smart contracts created by a protocol for flash loans execute a hidden call function set up in an attackers contract that allows them to extract the liquidity behind the protocol. The framework of the flash loan merely serves as a medium that intensifies the damage, as there is no maximum amount that can be issued per loan. These attacks are highly destructive for protocols and protocol LP’s and often leave attackers with profits in the hundreds of millions of dollars. However, this is a type of attack that is avoidable by auditing a smart contract’s code and execution.

reentrance_attack

This was the unfortunate case for CREAM finance and its liquidity providers when the protocol lost $260m USD in funds in two attacks, one of which made off with ~$130m USD in profit. The majority of the funds were washed through Ren’s bitcoin bridge, as is the frequent case with attacks like this. The attack consisted of 68 different assets and used over 9 ETH in gas, leaving most of CREAM’s ETH-based liquidity pools completely empty. The only assets left included $40m USD in a cream pool that made up only 13% of the protocol’s total liquidity prior to the attack. A ‘copycat’ attack identical to this one followed, but was less influential. The impact of reentrancy attacks has the capability to reach beyond the targeted protocol and onto others tied to it, however, this was not the case in this particular instance. CREAM is partnered with Yearn Finance after a merger between the two platforms in 2020; Yearn and its products were unaffected by the attack.

Staying Protected

Since DeFi is unregulated, all responsibility for keeping smart contract funds secure lies with the protocol creators and users who deposit their assets in said protocols. It’s important that both borrowers and lenders take the steps necessary to ensure they are using a robust protocol that will best protect them from losing funds. There are two primary ways users can go about this:

  • Check for technical audit – Protocols have the option to get the smart contracts that govern its operations audited by third parties. This information is widely available because projects who have done their due diligence are eager to share. Typically this information is displayed on the protocol’s website, but can also be found by simply searching for it on the internet. This is a non-technical option that gives users assurance that their funds are safe in a given protocol.
  • Independently check the smart contract’s code – The more technical users have the ability to check the code that makes up the smart contract themselves, which is one of the benefits of the transparency aspect of the technology. The downside, however, is that the user must have the technical wherewithal to understand how code works and how the contract may be structured. Few users have this capability, although anyone can access the smart contracts that outline a given flash loan.

Protocols have several options to ensure their platforms are best protected from attack at all times:

  • Get audited – Simply auditing their smart contracts can prevent protocols from devastating damage. Developers and protocols should continue to audit their programs as new capabilities and contracts are introduced or new methods of exploitation are forged by attackers.
  • Use decentralized price oracles – Many of the targeted protocols of flash loans relied on the price feeds of the decentralized exchanges attackers used to swap assets themselves, or a single oracle, as opposed to using a decentralized oracle solution. The feeds produced by decentralized exchanges focus on its singular underlying market which makes them easily manipulable. Decentralized oracles offer a full-bodied solution that greatly mitigates the risk of a loan incorporating manipulated data points.
  • Hackathons – These are competitive events held by protocols that allow attackers to identify weak points of a program and its smart contracts in a controlled environment. The winners of the events are compensated accordingly, which directs incentive to not conduct attacks maliciously. Hackathons also double over as community building events that forge strong relationships between members and managers.
  • Integrate early response tools – There are tools available that allow protocols to identify and subdue attacks as or before they occur. In March of 2021 the OpenZeppelin Defender platform launched Sentinels to mitigate attacks and exploits in DeFi. This program allows protocols to recognize unusual activity with their smart contracts which allows them to quickly respond to attacks.

As the decentralized finance market grows and flash loans increase in popularity, the number of attempts to attack DeFi protocols should only be expected to grow. This is a natural and unavoidable process that is dictated by the realities of how the world works. There will be a cryptographic arms race with protocols trying to face threats by building up their defenses and attackers trying to find more sophisticated methods of attack, which ultimately leads to a more robust system of operations. Users gain more awareness of the situation as this arms race unfolds, further mitigating the chances of attacks becoming widespread.

Closing Comments and Discussion Questions

It’s clear flash loans have demand in and positive impacts on the DeFi ecosystem; in 2020 Aave alone issued $2b USD in loans which prompted other players to offer similar products. The question becomes, do the benefits outweigh the risks? This query is predicated on an individual’s subjective notion of whether or not flash loan attacks are the result of protocols and users not doing their due diligence, or if it is believed that there is a deeper rooted issue at hand.


Get BONUS $200 for FREE!

You can get bonuses upto $100 FREE BONUS when you:
💰 Install these recommended apps:
💲 SocialGood - 100% Crypto Back on Everyday Shopping
💲 xPortal - The DeFi For The Next Billion
💲 CryptoTab Browser - Lightweight, fast, and ready to mine!
💰 Register on these recommended exchanges:
🟡 Binance🟡 Bitfinex🟡 Bitmart🟡 Bittrex🟡 Bitget
🟡 CoinEx🟡 Crypto.com🟡 Gate.io🟡 Huobi🟡 Kucoin.



Comments