Flash Loan Attacks - Implications and Attack Avoidance

27 ago 2024

7 Minutes

Ethereum has served as the foundational technology for the creation of a vast decentralized finance (DeFi) market. While it mirrors traditional finance in some respects, DeFi possesses unique characteristics that leverage the technical capabilities of Ethereum and blockchain technology, resulting in numerous innovative advancements. 


DeFi remains the most widely used ecosystem within the blockchain space. As of August 2024, a total of $84 billion is locked within DeFi protocols, down from a peak of nearly $180 billion in November 2021. This substantial amount of capital has enabled protocols and teams to establish companies focused on creating additional protocols aimed at attracting users with innovative features or use cases that generate value.

One of the key innovations introduced by these protocols is Flashloans, a unique feature that cannot be replicated in traditional finance. Flash Loans have gained widespread popularity in DeFi for several reasons.

In this article, the concept of Flash Loans will be introduced to provide readers with an understanding of this innovative feature unique to decentralized finance. The implications of Flash Loans will also be discussed, with particular emphasis on their potential for both beneficial applications and for exploiting vulnerabilities in protocols. Lastly, strategies for mitigating attacks that utilize Flash Loans will be presented.


Table of Contents

  1. What are Flashloans?

  2. Blockchain atomicity 

  3. Flasloan implications - Good usage and attacks.

  4. Consequences and Defense Mechanisms

  5. Conclusion

What are Flashloans?


Flash Loans represent one of the most popular and widely used groundbreaking innovations within the decentralized finance ecosystem. Flashloans offer a mechanism for uncollateralized borrowing that is inherently tied to the atomic nature of blockchain transactions, which is going to be explained later in this article.


Unlike traditional financial systems, where loans typically require significant collateral and undergo lengthy approval processes, Flash Loans allow users to borrow substantial amounts of assets without any upfront security, provided that the loan is repaid within the scope of a single blockchain transaction, so there is no risk of default or no repayment from the borrower side.

Blockchain Atomicity 


A Flash Loans is executed due to the technical possibility of atomicity within blockchain technology. In essence, a Flash Loan enables a borrower to access liquidity for a series of operations that must be completed within a single transaction block. 


Flash Loans are one of the most significant and popular innovations within blockchain technology, especially when compared to centralized finance and the non-decentralized world. This is because obtaining a loan and repaying it at the exact same moment is not feasible in centralized finance—or rather, it is theoretically possible but lacks practical utility.


The Ethereum Virtual Machine (EVM) is a state machine that executes atomic transactions. This means that a series of diverse operations can be executed as a 'package,' but in a specific order, all within the same exact moment. This characteristic is crucial for enabling Flash Loans. A user can borrow several million dollars and execute any desired operations with the loan, under the condition that the same amount is repaid within the same block.


Due to blockchain atomicity, the sequence of borrowing the loan, executing multiple operations, and repaying the loan occurs simultaneously within the same transaction block. This is physically impossible in traditional finance because executing various types of operations with a loan involves significant risks, including the potential loss of funds.


Blockchain atomicity ensures that the balance and repayment of the loan are verified after executing the operations, but before the loan is initialized. This guarantees 100% certainty that the funds will be returned; if the conditions are not met, the loan is not executed, and the transaction is reverted.

A flashloan is executed in the following order, all within the same block:

  • Initiation of the Loan: The borrower requests a Flash Loan from a DeFi protocol, such as Aave or dYdX. At this stage, no collateral is required, which is a significant departure from conventional lending mechanisms.


  • Execution of any operation: Upon receiving the loaned assets, the borrower can execute various financial strategies within the transaction. Common use cases include arbitrage—where a user exploits price discrepancies across different markets—or refinancing positions to reduce exposure or take advantage of more favorable terms. Additionally, Flash Loans can be used for liquidity provision, liquidation of undercollateralized loans, or even more complex operations like collateral swaps.


  • Repayment and Transaction Finalization: The crucial condition of a Flash Loan is that it must be repaid before the conclusion of the transaction. This includes the principal loan amount plus any associated fees. If the borrower profits from their operations within the transaction, they retain the surplus after settling the loan.


  • Reversion in Case of Default: If the borrower fails to repay the loan within the transaction, the entire sequence of operations is reverted. This reversion is automatic and enforced by the blockchain’s consensus mechanism, ensuring that the lender’s funds remain secure and the transaction effectively never occurred.

Flashloan Implications - Good Usage and Attacks


As mentioned earlier in this article, flash loans are widely used within the blockchain ecosystem. Their specific use cases can vary depending on the user's intent, with the only restriction being the requirement to repay the loan within the same block.


There are no restrictions on the types of actions that can be performed. This lack of restrictive conditions can lead to both beneficial uses of the loans as well as uses that negatively impact protocol operations and the user experience. Here are some uses of flashloans:

Arbitrage 


Cross-Exchange Arbitrage
: Traders can exploit price differences of the same asset across different exchanges. For instance, if Bitcoin is priced at $60,000 on Exchange A and $60,500 on Exchange B, a trader can use a flash loan to buy Bitcoin on Exchange A and sell it on Exchange B, making a profit from the price difference.

Intra-Exchange Arbitrage: Some DeFi platforms might have liquidity pools where the price of an asset deviates slightly due to supply and demand. Flash loans can be used to perform arbitrage within the same platform, buying low in one pool and selling high in another.

Source image: https://arxiv.org/abs/2003.03810

Collateral Swaps


Rebalancing Collateral
: Users with existing loans on platforms like Aave or Compound can use flash loans to swap their collateral without needing to repay the entire loan first. For example, if a user has locked up ETH as collateral but prefers to hold DAI, they can use a flash loan to swap the collateral, all within a single transaction.

Debt Position Migration: If a borrower wants to move their debt from one platform to another (perhaps to get better interest rates), flash loans enable this migration without the need for upfront capital.

Liquidation


Self-Liquidation
: A user might use a flash loan to avoid liquidation on a DeFi platform. If a user's collateral value is close to falling below the required threshold, they can take out a flash loan, pay off the debt, reclaim the collateral, and then re-sell or reinvest it, possibly in a less risky manner.

Third-Party Liquidation: Some users take advantage of flash loans to liquidate other users’ undercollateralized loans. They repay the debt, claim the collateral at a discount, and profit from the difference.

Oracle price manipulation


Oracle price manipulation using a flash loan involves exploiting the way a protocol determines the price of an asset, particularly when it uses the spot price from a liquidity pool as its price oracle. Here's a breakdown of how such an attack could work:

1 - Understanding the Setup


Liquidity Pools
: In decentralized finance (DeFi), liquidity pools (such as those on Uniswap or other Automated Market Makers, AMMs) allow users to trade tokens. The price of assets in these pools is determined by the ratio of the two tokens in the pool.

Price Oracles: Some DeFi protocols use the spot price of an asset from a liquidity pool as their oracle to determine the value of assets within their system, which implies a lot of security risks associated with price manipulation.

2 - The Role of Flash Loans


Flash Loans
: Flash loans allow a user to borrow a large amount of capital without collateral, as long as the loan is repaid within the same transaction. This provides the attacker with substantial liquidity to temporarily manipulate markets or prices.

3 - Step-by-Step Process of Oracle Price Manipulation


Flash Loan Acquisition
:

  • The attacker takes out a flash loan in a large amount of one asset (ex: ETH).


Price Manipulation in the Liquidity Pool
:

  • The attacker uses the borrowed ETH to perform a large trade in a liquidity pool that the targeted protocol uses as its price oracle.

  • For example, if the pool contains ETH and DAI, the attacker could use their borrowed ETH to buy a large amount of DAI from the pool. This purchase significantly increases the price of DAI relative to ETH in that pool because the ratio of ETH to DAI in the pool changes drastically.

  • Alternatively, the attacker could sell a large amount of DAI into the pool, decreasing the price of DAI relative to ETH.


Oracle Price Update
:

  • Because the DeFi protocol relies on the spot price from the liquidity pool, the manipulated price in the pool is now reflected as the "market price" by the oracle.

  • If the price of DAI is now artificially high or low, this incorrect price will be used by the protocol for any calculations involving DAI, such as collateral valuation or liquidation thresholds.


Exploiting the Manipulated Price
:

  • Undercollateralized Loan: If the attacker can make the protocol believe that the collateral they posted (e.g., DAI) is worth more than it actually is, they can borrow a larger amount of another asset (e.g., ETH) against this inflated collateral. Once they receive the borrowed ETH, they repay the flash loan.

  • Profitable Liquidation: If the attacker instead causes the price of the collateral (e.g., ETH) to drop, they can trigger liquidations in the protocol. They might be able to purchase the collateral at a discount or earn a liquidation fee.


Reverting the Manipulation
:

  • After the exploitation, the attacker reverses the initial trade to restore the original price in the liquidity pool. This is done by swapping the assets back, bringing the price closer to what it was before the manipulation.

  • The attacker then repays the flash loan in the same transaction.


Profit Extraction
:

  • The attacker keeps the profits generated from the exploit, such as the additional assets borrowed from the protocol or the gains from liquidation, while the rest of the transaction (including the flash loan repayment) is completed within the same block.

Consequences and Defense Mechanisms


Impact on the Protocol
:

  • Such an attack can lead to the protocol losing significant funds, especially if the attacker borrows assets with inflated collateral or causes wrongful liquidations.


Defense Mechanisms
:

  • Multiple Oracles: Relying on multiple sources for price data (e.g., Chainlink oracles, multiple liquidity pools) can mitigate the risk of manipulation.

  • Slippage Limits: Setting slippage limits on trades can prevent massive price swings within a pool, reducing the effectiveness of manipulation.

  • Time-Weighted Average Price (TWAP): Instead of using the spot price, protocols can use a TWAP, which averages the price over a period, making it harder to manipulate within a single transaction. A Time-Weighted Average Price (TWAP) is a pricing mechanism that calculates the average price of an asset over a specified period. Unlike a simple spot price, which reflects the price at a single point in time, TWAP smooths out short-term price fluctuations by considering prices at multiple points over a period, thereby providing a more stable and representative price.


Conclusion


Flash Loans represent a groundbreaking innovation in DeFi, offering immense potential for both creative financial strategies and, unfortunately, malicious exploitation. That is why the security challenges posed by Flash Loans must be met with robust defense mechanisms.

By understanding the complexities and implications of these uncollateralized loans, DeFi protocols can implement effective safeguards, such as using multiple oracles, setting slippage limits, and leveraging Time-Weighted Average Prices (TWAP) to mitigate risks.

At Zokyo, we specialize in ensuring the safety and integrity of your DeFi protocols. Our comprehensive smart contract audits and security assessments are designed to identify vulnerabilities before they can be exploited, giving you the peace of mind that your platform is protected. We can help your protocol remain secure and resilient in this dynamic landscape. Contact us to learn more.


Aviso y Descargo de Responsabilidad de Derechos de Autor

Todos los derechos reservados.

Todo el material que aparece en el sitio web de Zokyo (el “Contenido”) está protegido por derechos de autor según las leyes de derechos de autor de EE. UU. y es propiedad de Zokyo o de la parte acreditada como proveedor del Contenido. No puede copiar, reproducir, distribuir, publicar, mostrar, realizar, modificar, crear trabajos derivados, transmitir o de ninguna manera explotar dicho Contenido, ni puede distribuir ninguna parte de este Contenido a través de ninguna red, incluida una red de área local, venderlo u ofrecerlo para la venta, o usar dicho Contenido para construir cualquier tipo de base de datos. No puede alterar ni quitar ningún aviso de derechos de autor u otro aviso de copias del contenido en el sitio web de Zokyo. Está expresamente prohibido copiar o almacenar cualquier Contenido sin el permiso previo por escrito de Zokyo o el titular de los derechos de autor identificado en el aviso de derechos de autor del contenido individual. Para obtener permiso para usar el Contenido en el sitio web de Zokyo, comuníquese con hello@zokyo.io

Zokyo intenta asegurarse de que el contenido sea preciso y provenga de fuentes confiables, pero no garantiza que sea libre de errores. Zokyo puede agregar, modificar o derogar cualquier política, procedimiento o regulación, y no publicar oportunamente dichos cambios en su sitio web no se interpretará como una renuncia a la aplicación. Zokyo no garantiza que las funciones en su sitio web sean ininterrumpidas, que los defectos se corrijan, o que el sitio web esté libre de virus u otros componentes dañinos. Cualquier enlace a información de terceros en el sitio web de Zokyo se proporciona como cortesía y no constituye un respaldo de esos materiales o del tercero que los proporciona.

Aviso y Descargo de Responsabilidad de Derechos de Autor

Todos los derechos reservados.

Todo el material que aparece en el sitio web de Zokyo (el “Contenido”) está protegido por derechos de autor según las leyes de derechos de autor de EE. UU. y es propiedad de Zokyo o de la parte acreditada como proveedor del Contenido. No puede copiar, reproducir, distribuir, publicar, mostrar, realizar, modificar, crear trabajos derivados, transmitir o de ninguna manera explotar dicho Contenido, ni puede distribuir ninguna parte de este Contenido a través de ninguna red, incluida una red de área local, venderlo u ofrecerlo para la venta, o usar dicho Contenido para construir cualquier tipo de base de datos. No puede alterar ni quitar ningún aviso de derechos de autor u otro aviso de copias del contenido en el sitio web de Zokyo. Está expresamente prohibido copiar o almacenar cualquier Contenido sin el permiso previo por escrito de Zokyo o el titular de los derechos de autor identificado en el aviso de derechos de autor del contenido individual. Para obtener permiso para usar el Contenido en el sitio web de Zokyo, comuníquese con hello@zokyo.io

Zokyo intenta asegurarse de que el contenido sea preciso y provenga de fuentes confiables, pero no garantiza que sea libre de errores. Zokyo puede agregar, modificar o derogar cualquier política, procedimiento o regulación, y no publicar oportunamente dichos cambios en su sitio web no se interpretará como una renuncia a la aplicación. Zokyo no garantiza que las funciones en su sitio web sean ininterrumpidas, que los defectos se corrijan, o que el sitio web esté libre de virus u otros componentes dañinos. Cualquier enlace a información de terceros en el sitio web de Zokyo se proporciona como cortesía y no constituye un respaldo de esos materiales o del tercero que los proporciona.

Aviso y Descargo de Responsabilidad de Derechos de Autor

Todos los derechos reservados.

Todo el material que aparece en el sitio web de Zokyo (el “Contenido”) está protegido por derechos de autor según las leyes de derechos de autor de EE. UU. y es propiedad de Zokyo o de la parte acreditada como proveedor del Contenido. No puede copiar, reproducir, distribuir, publicar, mostrar, realizar, modificar, crear trabajos derivados, transmitir o de ninguna manera explotar dicho Contenido, ni puede distribuir ninguna parte de este Contenido a través de ninguna red, incluida una red de área local, venderlo u ofrecerlo para la venta, o usar dicho Contenido para construir cualquier tipo de base de datos. No puede alterar ni quitar ningún aviso de derechos de autor u otro aviso de copias del contenido en el sitio web de Zokyo. Está expresamente prohibido copiar o almacenar cualquier Contenido sin el permiso previo por escrito de Zokyo o el titular de los derechos de autor identificado en el aviso de derechos de autor del contenido individual. Para obtener permiso para usar el Contenido en el sitio web de Zokyo, comuníquese con hello@zokyo.io

Zokyo intenta asegurarse de que el contenido sea preciso y provenga de fuentes confiables, pero no garantiza que sea libre de errores. Zokyo puede agregar, modificar o derogar cualquier política, procedimiento o regulación, y no publicar oportunamente dichos cambios en su sitio web no se interpretará como una renuncia a la aplicación. Zokyo no garantiza que las funciones en su sitio web sean ininterrumpidas, que los defectos se corrijan, o que el sitio web esté libre de virus u otros componentes dañinos. Cualquier enlace a información de terceros en el sitio web de Zokyo se proporciona como cortesía y no constituye un respaldo de esos materiales o del tercero que los proporciona.