tl;dr
Flash loans, unique to the DeFi ecosystem, are uncollateralized and instantaneous loans completed within a single transaction on the blockchain. They use smart contracts for execution and are "atomic," meaning the transaction either fully completes or doesn't happen at all, preventing lender loss. Borrowers can access substantial funds without collateral, but must repay within the same transaction block.
Key features include:
Uncollateralized Loans: No collateral needed, differing from traditional and cryptocurrency lending.
Instantaneous Process: Borrowing, using, and repaying occur in seconds within one blockchain transaction.
Smart Contract Execution: Terms are coded into self-executing contracts.
Atomic Transactions: Ensures lender safety by undoing the transaction if not repaid in time.
Flash loans are used for various strategies like arbitrage, liquidity provision, and collateral swapping. The process includes initiating a loan request on a DeFi platform, specifying the loan amount, using the loan (e.g., for arbitrage), and immediate repayment. If repayment fails, the transaction reverts, leaving no trace.
Applications:
Arbitrage: Exploiting price discrepancies across exchanges. Borrowers use flash loans to buy low and sell high instantly.
Liquidity Provision: Temporarily adding liquidity to DeFi protocols, earning transaction fees.
Collateral Swapping: Swapping collateral in a DeFi lending position within a single transaction.
However, flash loans pose risks like market manipulation, smart contract vulnerabilities, and are subject to unregulated legal concerns. They also open doors to attacks, where attackers exploit DeFi vulnerabilities using borrowed funds but without risk due to the atomic nature of the transaction. High-profile attacks have demonstrated the potential for significant losses in the DeFi space.
Notable Attack Examples:
Themis Protocol Attack: Exploited a flawed oracle to inflate token prices, borrowing additional assets based on inflated collateral value.
Conic Finance Exploit: Combined a flash loan, reentrancy, and front-running to manipulate token prices and extract significant ETH.
JPEG’d and Alchemix Exploits: Used arbitrage by manipulating liquidity positions and price discrepancies across DeFi protocols, resulting in substantial ETH profits.
Despite risks, flash loans offer a novel, efficient approach to large-scale, low-cost financial strategies, democratizing access to capital. The future of flash loans involves addressing risks with best practices like concentrated liquidity, trading circuit breakers, and smart contract verification, ensuring continued innovation in DeFi.
Introduction
A Flash Loan is a unique financial instrument that has emerged within the DeFi ecosystem, particularly on lending and borrowing platforms. It's a type of uncollateralized loan that has become popular due to its unique features and the opportunities it offers for arbitrage, market manipulation, and other financial strategies.
Uncollateralized Loan: Unlike traditional loans, flash loans do not require the borrower to provide collateral. This is a significant departure from the norm in both traditional finance and typical cryptocurrency lending.
Instantaneous Process: The entire process of borrowing, utilizing, and repaying the loan occurs within a single transaction on the blockchain. This means that the loan is issued and settled within seconds.
Smart Contract Execution: Flash loans are executed through smart contracts. These are self-executing contracts with the terms of the agreement directly written into code.
Atomic Transactions: The term "atomic" in this context means that the transaction either fully completes or doesn’t happen at all. If the borrowed funds are not returned by the end of the transaction, the entire operation is reversed to undo all actions executed until that point. This ensures that the lender does not lose money.
At its core, a flash loan allows individuals to borrow a substantial amount of assets without any collateral, but with the stipulation that the loan must be repaid within the same transaction block. This feature makes flash loans vastly different from traditional loans, where collateral, credit checks, and extended repayment periods are the norms.
The mechanics of a flash loan are facilitated by smart contracts, which are self-executing contracts with the terms of the agreement directly written into lines of code. In the case of flash loans, the smart contract automates the entire process:
loan issuance,
utilization of the loan for a specific purpose, and
repayment.
All these steps occur within one transaction on the blockchain, which typically completes in a matter of seconds.
Here's how a flash loan typically works
Step 1: Initiating the Flash Loan Request
User Interaction: A user (borrower) initiates a flash loan by interacting with a DeFi platform that offers flash loan services, such as Aave, dYdX, or Uniswap.
Smart Contract Call: The user creates a transaction that calls a smart contract on the DeFi platform. This contract is programmed to handle flash loan requests.
Step 2: Issuing the Loan
Loan Amount Specification: In the transaction, the borrower specifies the amount of cryptocurrency (like Ethereum's ETH) they wish to borrow.
No Collateral Requirement: Unlike traditional loans, flash loans do not require the borrower to provide any collateral. This is a key feature that distinguishes flash loans from other lending types.
Step 3: Using the Loan
Execution of Operations: Once the loan is issued, the borrowed funds are available to the borrower within the same transaction. The borrower can use these funds for various purposes such as arbitrage, liquidity provision, or debt refinancing.
Arbitrage Example: The borrower might use the loan to buy a cryptocurrency on one exchange where it's priced lower and sell it on another exchange where it's priced higher.
Other Uses: Similarly, the loan can be used to swap collateral in a lending position or to take advantage of price differences in decentralized exchanges.
Step 4: Repaying the Loan
Immediate Repayment Requirement: The loan must be repaid in full, along with any associated fees, by the end of the transaction block in which it was issued.
Transaction Completion: The repayment is typically the last action in the transaction sequence. If the borrower successfully repays the loan within the same transaction, the transaction is completed and confirmed on the blockchain.
Step 5: Automatic Transaction Reversion (If Necessary)
Atomicity Principle: If the borrower fails to repay the loan in full by the end of the transaction block, the atomic nature of the blockchain transaction ensures that the entire operation is automatically reversed.
No Trace Left: In the case of a failed repayment, the blockchain's state is reverted to its status before the flash loan was issued, as if the transaction never happened. This protects the lender from loss.
If the borrower fails to repay the loan within this very short timeframe, the smart contract automatically reverses the entire transaction, as if it never happened. This feature is known as atomicity, ensuring the loan is all-or-nothing: either the entire process completes successfully, or it’s as though the transaction never occurred.
Atomicity in the context of flash loans is a crucial concept that fundamentally shapes how these loans function.
Atomicity refers to the "all-or-nothing" execution of transactions on blockchain platforms like Ethereum. An atomic transaction means that either all of the operations in the transaction succeed and are committed to the blockchain, or if there is any failure, the entire transaction fails or rolls back as if it never occurred.
In practical terms, atomicity creates a link between all the steps that occur within a blockchain transaction - connecting the borrowing of assets to their repayment in a flash loan. Unless the assets borrowed via a flash loan are returned by the end of the transaction, none of the borrowing or intermediate steps are executed.
This atomic linkage is critical for flash loans for two reasons:
Firstly, atomicity eliminates default risk for lenders. If borrowed assets are not repaid by the end of the transaction, the loan effectively never happened since intermediate steps undo. So lenders can offer flash loans without collateral - there is no risk scenario where their capital is not returned.
Secondly, borrowers can execute trades, arbitrage opportunities and complex strategies with the assurance that profits made will remain if the loan is repaid. If the transaction fails at any point, it reverts with no impact. This "try without risk" environment further enables innovation with flash loans.
Flash loans do not currently exist in traditional finance (TradFi) primarily due to the lack of atomicity in transactions.
The key innovation that enables flash loans is the atomic nature of transactions on blockchains like Ethereum. Atomicity automatically rolls back transactions if certain conditions are not met, eliminating counterparty default risk for lenders.
There is no structural reason why flash loans could not be offered in automated trading systems in traditional finance. However, the systems lack native atomicity. Without atomicity, uncollateralized flash loan-like products cannot be securely enabled in TradFi.
The closest existing products in traditional finance to flash loans are as follows:
Intraday trading lines: Allows traders to borrow funds from brokerages solely for intraday trading purposes. However, strict limits are places on these lines and traders still need to be vetted and approved. So they are not accessible permissionless like flash loans.
Exchange-provided leverage: Some centralized crypto exchanges offer leverage for intraday trading without needing collateral. But leverage amount is limited and loans are not instantly repaid like flash loans.
Very soon, TradFi “might” need to integrate atomic transactions in some form before DeFi leaves it behind.
Conceptually, there is no reason atomic transactions cannot be implemented in automated trading systems of banks, hedge funds, brokerages, etc.
Technologically, these systems are advanced enough to encode logic that rolls back failed transactions.
Legally, terms can be added that define transactions as indivisible units with failure triggers leading to reversals. Financially, the gains from frictionless arbitrage, trading, and access to capital outweigh the default risks, which are eliminated anyway.
Flash loans have primarily been leveraged for several key applications, with arbitrage being the most prominent.
#1. Arbitrage
Arbitrage using flash loans in DeFi is a sophisticated financial strategy that exploits price discrepancies across different cryptocurrency exchanges or trading platforms. Flash loans, with their unique characteristics, have become a powerful tool for conducting arbitrage operations.
Here's how we can understand a bit more:
Arbitrage involves buying and selling an asset simultaneously in different markets to profit from price discrepancies. In a perfectly efficient market, such opportunities are rare and quickly resolved, but in the fragmented and rapidly evolving world of cryptocurrencies, these discrepancies are more common. Typically, arbitrage requires significant capital and swift execution. Traders need enough funds to purchase assets at a lower price in one market and sell them at a higher price in another.
Instant Capital Access: Flash loans allow individuals to borrow large amounts of cryptocurrency instantly, without collateral. This capability is crucial for arbitrage as it provides the necessary capital to purchase assets in markets where they are undervalued.
Collateral-Free Operation: Unlike traditional loans, flash loans do not require collateral, which is a significant advantage for individuals or small traders who might not have sufficient assets to use as collateral.
Process of Arbitrage Using Flash Loans
Identifying Price Discrepancies: The trader identifies a cryptocurrency that is priced differently on two exchanges. For example, ETH might be cheaper on Exchange A and more expensive on Exchange B.
Obtaining a Flash Loan: The trader takes out a flash loan in the cryptocurrency (e.g., ETH).
Executing Trades: They use the borrowed funds to buy the cryptocurrency on Exchange A at a lower price and then immediately sell it on Exchange B at a higher price.
Repaying the Loan: The trader then repays the flash loan and the associated fees, all within the same transaction block on the blockchain.
Profit Realization: If successful, the trader keeps the profit, which is the difference between the buy and sell prices minus any transaction and loan fees.
Benefits of Flash Loan Arbitrage
Leveraging Large Capital: Flash loans democratize access to significant capital, allowing individual traders to execute large-scale arbitrage trades.
Speed and Efficiency: Because blockchain transactions can be executed quickly, flash loan arbitrage can capitalize on fleeting arbitrage opportunities that would be inaccessible or too risky with traditional funding methods.
No Upfront Capital Requirement: Traders can engage in arbitrage without having their capital, reducing barriers to entry.
Risks and Considerations
Market Volatility: Cryptocurrency prices can be highly volatile. A slight delay or change in price during the transaction can turn a potential profit into a loss.
Smart Contract Risks: The process involves interacting with complex smart contracts. Any flaws or vulnerabilities in these contracts could lead to financial loss.
Transaction Fees: The costs associated with executing these transactions, including gas fees on networks like Ethereum and flash loan fees, can significantly impact profitability.
#2. Liquidity Provision
Liquidity provision using flash loans is an intricate and strategic application within DeFi. It's a process that leverages the unique characteristics of flash loans to enhance liquidity in various DeFi protocols.
Liquidity refers to the availability of liquid assets (like cryptocurrencies) in a market or protocol. High liquidity ensures smooth and efficient trading, as it reduces the spread between buy and sell prices and allows for large transactions without significant price impact. Many DeFi platforms operate on a liquidity pool model, where users (liquidity providers) pool their assets to facilitate trading, lending, and other financial activities. These pools earn transaction fees for the liquidity providers.
Flash Loans and Liquidity Provision
Flash loans provide immediate access to significant capital without upfront collateral. This feature can be leveraged to provide liquidity to a market or protocol temporarily. By injecting liquidity into a DeFi protocol, flash loans can help stabilize prices, especially in moments of high volatility or when large trades might otherwise significantly impact the market. In multi-asset pools, the balance between different assets can become skewed. Flash loans enable users to quickly adjust the pool's composition, maintaining the necessary balance and ensuring the pool's smooth operation.
Profit Motive and Market Impact
Earning Fees: By providing liquidity, even temporarily, users can earn fees from trades executed within the pool. The profitability of such strategies depends on the fees outweighing the cost of the flash loan.
Improving Market Efficiency: These activities contribute to the overall health and efficiency of the DeFi ecosystem. By ensuring adequate liquidity, flash loans help maintain tighter bid-ask spreads, reduce slippage, and increase market stability.
Opportunistic Trading: Users can capitalize on temporary market conditions, such as high demand for liquidity, without needing to commit their capital long-term.
Process of Liquidity Provision Using Flash Loans
Obtaining a Flash Loan: A user takes out a flash loan, borrowing a substantial amount of assets (like ETH or stablecoins).
Contributing to Liquidity Pools: The borrowed funds are then added to a liquidity pool on a DeFi platform. This action can be for various purposes, such as to balance out the pool, take advantage of high transaction fees, or to facilitate large trades.
Executing Transactions: While the funds are in the liquidity pool, they may be used in trades or other financial operations, earning transaction fees in the process.
Repaying the Flash Loan: Before the transaction block ends, the user withdraws the funds from the liquidity pool and repays the flash loan, including any associated fees.
Risks and Considerations
Market Dynamics: Liquidity provision strategies require an understanding of market conditions. Misjudging these can lead to losses, especially if the costs of the flash loan exceed the earnings from transaction fees.
Smart Contract Risks: Flash loans and liquidity provision involve interacting with smart contracts, which can have vulnerabilities or unforeseen behaviors.
Transaction Costs: Gas fees for executing these transactions on a blockchain like Ethereum can be substantial, particularly during times of network congestion.
Applications
Arbitrage: Users can exploit price differences for an asset across different exchanges. They borrow funds, buy the asset where it’s cheaper, sell it where it’s more expensive, and pocket the difference.
Collateral Swaps: Flash loans can be used to swap collateral in a borrowing position without needing to close and reopen it.
Self-Liquidation: In a scenario where a user’s collateral is about to be liquidated, they can use a flash loan to pay off part of their debt and adjust their position.
Debt Refinancing: Users can refinance debts in DeFi platforms by borrowing from one protocol to pay off another, potentially at a better rate.
Risks and Controversies
The complexity of smart contracts can lead to vulnerabilities. There have been instances where attackers exploited these to drain funds from DeFi platforms.
Flash loans can be used to artificially manipulate market prices, leading to unfair trading advantages or even destabilizing certain tokens.
The unregulated nature of flash loans raises questions about legality and compliance, especially concerning market manipulation and money laundering.
#3. Collateral Swapping
Collateral swapping using flash loans is an advanced financial strategy within DeFi, offering unique benefits and opportunities for traders and investors.
As we all know, in DeFi, collateral is often used to secure loans. Users lock in assets (like cryptocurrencies) as collateral to borrow other assets or stablecoins. Given the volatility of many crypto assets, the value of collateral can fluctuate significantly, affecting the borrower's position.
Collateral swapping involves exchanging the current collateral securing a loan for another type of asset. This is often done to manage risk or take advantage of market conditions. The main goals are to
maintain the health of the loan position (avoid liquidation),
benefit from favorable market conditions, or
switch to a more stable or appreciating asset.
Integration with Flash Loans
Instant Liquidity: Flash loans provide the liquidity necessary to perform a collateral swap in a single transaction. Without flash loans, swapping collateral might require additional capital or complex multi-step transactions.
How It Works: A user takes out a flash loan in the currency they need to repay their existing loan. They then use this amount to pay off the original loan, freeing up their collateral. Subsequently, they use the released collateral to obtain a new loan, secured by different, more desirable collateral, and finally use part of the new loan to repay the flash loan.
How does it work:
Obtain Flash Loan: The borrower takes a flash loan in the same currency as their existing debt.
Repay Original Loan: The flash loan is used to immediately pay off the existing loan.
Release Original Collateral: The original collateral is released back to the borrower.
Initiate New Loan with New Collateral: The borrower then uses the released collateral to open a new loan, this time placing a different asset as collateral.
Repay Flash Loan: Finally, the borrower repays the flash loan, including any associated fees, in the same transaction.
Risks and Considerations
Market Volatility: Sudden market shifts can affect the efficiency and safety of the swap.
Transaction Costs: Gas fees and flash loan fees must be considered, as they can affect the profitability or feasibility of the swap.
Technical Complexity: Requires an understanding of smart contracts and DeFi protocols.
Flash Loan Attacks
Having discussed how flash loans work and the crucial role atomicity plays in enabling these uncollateralized, instantly repaid loans unique to DeFi, we now examine the darker side - flash loan attacks.
As we covered earlier, the permissionless and low-risk nature of flash loans allows any user to borrow large sums of assets instantly. This can be put to productive use through arbitrage, self-liquidation, and other complex financial strategies. However, by choreographing manipulative transactions across multiple DeFi protocols, borrowed funds from flash loans can also be weaponized to exploit vulnerabilities in those platforms for profit. The composability of openly interconnected DeFi systems, while powerful, exposes risks of disruption when manipulated nefariously.
Such malicious exploitations conducted using funds from flash loans are referred to as flash loan attacks. Attackers typically borrow assets, use those to pump token prices on DEXs, drain lending pools via inflated prices, perform swaps to profit from price discrepancies across protocols - extracting value at the cost of legitimate users.
If structured correctly to repay flash loans, while ensuring profits flow into the attacker's wallet, millions can be made by gaming the connected DeFi ecosystem with flash-borrowed assets. And if execution fails at any step, atomicity ensures reversal as if the attack never occurred.
By providing large, uncollateralized capital that can be repaid instantly if used unsuccessfully in exploits, flash loans effectively remove risk for attackers while introducing new attack vectors into DeFi. Hence the need for securing systems against flash loan risks, using concentrated liquidity, trading halt triggers and other failsafes.
Now that we have set the context of how flash loans can turn exploitative via attacks, next we dive deeper into the mechanisms and motivations of flash loan attacks threatening the burgeoning DeFi space.
Here's a detailed breakdown of how a flash loan attack typically happens:
Step 1: Preparation and Target Identification: The attacker first identifies a vulnerability in a DeFi protocol. This could be a weakness in smart contract code, a price oracle flaw, or a design issue in the protocol’s economic model. The attacker then devises a strategy that typically involves a series of interlinked operations, all of which must be executed within a single transaction block.
Step 2: Obtaining a Flash Loan: The attacker takes out a flash loan, borrowing a huge sum of cryptocurrency. Flash loans are unique in that they require no collateral and are issued instantly, but must be repaid within the same transaction block. This step is crucial because it allows the attacker to execute large-scale manipulations without any initial capital.
Step 3: Executing the Attack: The attacker uses the borrowed funds to manipulate market conditions or exploit protocol vulnerabilities. Common methods include:
Price Oracle Manipulation: Using the flash loan to buy up a significant amount of a particular cryptocurrency on a DeFi platform, artificially inflating its price. This manipulated price is then reported to the protocol’s price oracle.
Liquidity Pool Imbalance: Injecting or removing funds from a liquidity pool to create imbalances and exploit the pool’s mechanics.
Pump and Dump: Temporarily pumping the price of an asset to sell it at an inflated price in another market or protocol.
Complex Transactions: The attack often involves complex and automated transactions that exploit these vulnerabilities or manipulations for financial gain.
Step 4: Repaying the Flash Loan: Before the end of the transaction block, the attacker repays the flash loan, including any associated fees. This step is critical because if the loan is not repaid, the entire transaction, including all the manipulative actions, is reversed due to the atomic nature of blockchain transactions. If the attack is successful, the attacker extracts the profits from their manipulative actions. This could involve transferring tokens, extracting value from a protocol, or other forms of financial gain.
Step 5: Transaction Finalization: Once the flash loan is repaid and the profits are secured, the transaction is finalized and recorded on the blockchain. The rapid and complex nature of these transactions often leaves little time for intervention.
In 2023 alone, there were at least 4 high-profile Flash Loan attacks that drained several protocols of Millions of Dollars.
#1. Themis Protocol
On June 27th, 2023, due to a flawed oracle exploited to inflate the price of a Balancer LP token. The flash loan attack on Themis Protocol showcases a sophisticated exploitation of flash loans and a flawed oracle system.
Here's how it unfolded:
Step 1: Initiating the Flash Loan
Borrowing Funds: The hacker starts the attack by initiating a flash loan from Aave V3 and two Uniswap V3 pools. They borrow a significant amount of WETH (40,000 units) without needing to provide any collateral, which is a key feature of flash loans.
Step 2: Borrowing from Themis Protocol
Using WETH as Collateral: The hacker then uses a portion of the borrowed WETH (220 units) as collateral to borrow various other cryptocurrencies from Themis Protocol, including DAI, USDC, USDT, ARB, and WBTC.
Step 3: Manipulating the Oracle
Creating a New Contract: The hacker sets up a new contract and conducts several operations within it:
They supply 55 WETH to a Balancer pool and receive 54.665 LP (Liquidity Provider) tokens in return.
These BLP tokens are then deposited into Themis Protocol.
Due to a flawed oracle in Themis Protocol, which relied on an inflated price feed from Uniswap for ETH/USDT, the BLP tokens are overvalued.
Inflating Token Value: The hacker further manipulates the market by swapping 39,725 WETH for 2,423 wstETH. This swap affects the price of BLP tokens in the Balancer pool, inflating their perceived value due to the oracle’s flawed pricing.
Exploiting Themis Protocol: Leveraging this inflated valuation, the hacker borrows an additional 317.62 WETH from Themis Protocol, exploiting the discrepancy between the real and oracle-reported value of BLP tokens.
Step 4: Reversing the Swap
Restoring Original Price: To cover their tracks, the hacker then counter-swaps 2,423 wstETH back for approximately 39,724.94 WETH. This action effectively reverses the earlier swap's impact on the BLP tokens’ price in the Balancer pool, returning it to its original value.
Step 5: Repaying the Loan and Securing Profit
Repaying the Flash Loan: With the transaction block still ongoing, the hacker repays the original flash loan of 40,000 WETH to Aave V3 and Uniswap V3.
Walking Away with Profit: The remaining WETH, along with the other tokens initially borrowed using the inflated BLP tokens as collateral, constitute the hacker’s profit from the attack.
This flash loan attack demonstrates the critical importance of reliable oracle systems in DeFi protocols. The hacker's ability to exploit the flawed oracle for price manipulation, combined with the capital access provided by flash loans, enabled them to execute a complex and profitable attack against Themis Protocol. It highlights the vulnerabilities in DeFi ecosystems, particularly concerning Oracle reliability and the systemic risks posed by flash loans when combined with other DeFi components. The majority of exploited tokens were sent to Tornado Cash.
#2: Conic Finance
On July 21, 2023, Conic Finance was exploited for 17k ETH worth over $3.3M at the time.
The Conic Finance exploit was a multi-faceted attack that combined a flash loan, reentrancy, and front-running to manipulate token prices and extract a large amount of ETH from the protocol.
Here's a step-by-step explanation of how the exploit unfolded:
Step 1: Flash Loan Acquisition
Borrowing Funds: The attacker took out a flash loan from AAVE, borrowing $20k worth of ETH without collateral.
Step 2: Token Contract Interaction
Token Approval: Using Etherscan, the attacker interacted with the rETH-f and WETH token contracts, calling the approve function on both. This granted the OmnipoolRouterV2 contract permission to spend tokens on the attacker's behalf, with the approval amount set to the maximum (2^256 - 1).
Step 3: Overflow Exploitation
Triggering Overflow: The approval of an extremely high amount allowed the attacker to trigger an integer overflow in the OmnipoolRouterV2 contract when it performed calculations using these values.
Step 4: Price Manipulation via Oracle Exploit
Inflating rETH-f Price: The attacker manipulated the returned rETH-f price by interacting with the GenericOracleV2 contract. By depositing ETH and rETH into Uniswap v2, they altered the token ratio in the liquidity pool, thus inflating the price.
Step 5: Front-Running Technique
Executing Front-Running: The attacker used a front-running technique, submitting their transaction with a higher gas fee to ensure it was included before others in the same block, capitalizing on the manipulated price.
Step 6: Depositing as Liquidity
Inflating Liquidity Value: They deposited ETH and rETH-f tokens into the OmnipoolRouterV2 contract as liquidity, further inflating the rETH-f price.
Step 7: Executing Swaps
Swapping Tokens: The attacker swapped ETH for rETH-f and then back to WETH using the inflated rETH-f prices, resulting in them receiving more WETH than they should have.
Step 8: Repeated Price Checks
Read-Only Reentrancy: By repeatedly calling the getUSDPrice function, the attacker took advantage of read-only reentrancy to consistently get an inflated price for the rETH-f token.
Step 9: Finalizing the Attack
Draining the Protocol: The attacker completed the attack by swapping the rETH-f back to WETH, using the inflated price to obtain a larger amount of WETH.
Profiting: They then repaid the flash loan and kept the excess WETH as profit, totaling 1,701 WETH, which was worth over $3.3M at the time.
The Conic Finance exploit was a sophisticated attack that combined various DeFi attack vectors. The attacker leveraged the features of a flash loan for capital, exploited a token contract's overflow vulnerability, manipulated a DeFi protocol's price oracle via front-running, and used reentrancy to repeatedly confirm the inflated price. This resulted in an erroneous calculation of token worth, allowing the attacker to extract a substantial profit.
#3: JPEG’d
On July 30, 2023, JPEG’d was exploited for over $11M. A classic Flash loan + Arbitrage attack.
This exploit was a sophisticated example of using flash loans for arbitrage, specifically targeting inefficiencies between token prices present across DeFi protocols.
Here’s how it unfolded:
Step 1: Obtaining Flash Loan
The exploiter starts by taking a significant flash loan of 80,000 WETH from the Balancer platform.
Step 2: Providing Liquidity
The exploiter then provides 32,431 WETH as liquidity to the Curve finance pool, receiving pETH-ETH LP (Liquidity Provider) tokens in return.
They further contribute more WETH to Curve, creating an additional 82,182 LP tokens.
Step 3: Withdrawing and Burning LP Tokens
The exploiter removes a portion of the liquidity from Curve, withdrawing 3,740 pETH in the process.
They proceed to burn the initial 32,431 Curve LP tokens, effectively removing that section of liquidity.
By burning more Curve LP tokens, the exploiter withdraws an additional 1,184 pETH.
Step 4: Exploiting Price Discrepancies
Arbitrage on JPEG'd Protocol: Taking advantage of the price differential between pETH and WETH on the JPEG'd protocol, the exploiter conducts a swap.
Executing the Swap: They exchange 4,924 pETH for 4,285 WETH using JPEG'd's exchange mechanism.
Step 5: Repaying the Loan and Profiting
The exploiter repays the 80,000 WETH flash loan back to Balancer, completing the obligations of the flash loan.
After repaying the flash loan, the exploiter retains 6,106 WETH, which is approximately valued at $11 million, as profit from the arbitrage exploit.
This multi-step process showcases how the exploiter used the flash loan for arbitrage by manipulating liquidity positions and taking advantage of price discrepancies across different DeFi protocols to realize a profit. Each step is calculated to optimize the return on the flash loan before repaying it, ensuring the exploiter can retain a substantial amount of ETH as profit.
Such exploits demonstrate the importance of closely monitoring price mechanisms and liquidity provisions within DeFi protocols to prevent potential vulnerabilities from being exploited.
#4: Alchemix
On the same day the JPEG’d exploit happened, Alchemix was exploited of with the same attack. But the exploit was deeper with ~$13M.
The Alchemix exploit was a sophisticated attack that used a flash loan combined with arbitrage to take advantage of unguarded protocol mechanics.
Here's how it unfolded:
Step 1: Initiating the Flash Loan
The attacker began by taking out a flash loan of 40,000 WETH from the Balancer platform. Flash loans allow borrowing without collateral as long as the loan is repaid within the same transaction.
Step 2: Liquidity Provision and Token Minting
The attacker provided a portion of the flash-loaned WETH as liquidity to the alETH/ETH Curve pool, minting 19,895 alETH-ETH LP tokens.
They then added more WETH to the Curve pool, minting an additional 34,277 alETH-ETH LP tokens.
Step 3: Withdrawing Liquidity and Burning LP Tokens
The attacker removed some of the liquidity from the pool, withdrawing 4,821 alETH in the process.
The initial 19,895 alETH-ETH LP tokens were then burned, effectively removing that portion of the liquidity.
An additional 15,910 alETH-ETH LP tokens were burned to remove the rest of the liquidity.
Step 4: Exploiting Price Discrepancies
Manipulating Exchange Rates: By providing and removing liquidity, the attacker manipulated the exchange rates within the Curve pool. This created a price discrepancy between assets.
Arbitrage: Using the manipulated rates, the attacker engaged in arbitrage trades that allowed them to swap assets at an advantageous rate, effectively obtaining more assets than they should have.
Step 5: Repaying the Flash Loan
After the arbitrage, the attacker repaid the original flash loan of 40,000 WETH to Balancer.
Step 6: Profiting from the Attack
The result of these maneuvers was a profit of 7,258 WETH, approximately valued at $13.6 million, which was then transferred to the attacker’s wallet.
Vulnerabilities Exploited
Lack of Slippage Protection: The Alchemix contract did not have mechanisms to ensure that the exchange rates used in swaps reflected fair market prices. There was no validation on the amounts being swapped or protection against excessive slippage.
Manipulable Exchange Function: The contract’s function to exchange assets did not prevent the exchange from happening at manipulated or unfair prices. The attacker was able to exploit this vulnerability to swap tokens at an inflated rate.
Direct Interface with WETH Contract: The contract interacted directly with the WETH contract, which enabled the attacker to take out flash loans in WETH and perform the exploit.
This detailed account of the Alchemix exploit shows how the attacker cleverly used the flash loan to manipulate liquidity and exchange rates, performed arbitrage across DeFi protocols, and withdrew a significant profit, all within a single transaction.
Conclusion
Flash loans represent a truly novel lending instrument brought about by the game-changing atomic construct made possible only through decentralized blockchain architectures. By fundamentally linking borrowing and repayment into one indivisible transaction, they enable uncollateralized, large-scale loans without exposing the lender to default risks.
The growing adoption of flash loans for arbitrage, liquidity provision, and collateral swaps, showcases how participants can execute complex financial strategies at a low cost that earlier carried prohibitive capital requirements or coordination overheads. As flash loans become widely accessible, more promising applications can democratize access and generate efficiencies through automated, transparent capital flow.
However, as with most technological leaps, flash loans also introduce new risks—the exploitation through attacks being the most palpable among them so far. By orchestrating deliberate manipulation of pricing oracles, liquidity parameters or economic designs across connected DeFi protocols, flash-borrowed capital can be weaponized without recourse. The composability and permissionlessness, while stimulating innovation, expose vulnerabilities that get accentuated by flash loans.
As the space evolves, best practices around concentrated liquidity, trading circuit breakers, formal verification of smart contract code, along with orderly monitoring are necessary countermeasures. Nevertheless, it is inevitable that our understanding of flash loans and mitigating risks will mature alongside discoveries of new exploits. And that is also why this space must stay committed to transparency, knowledge sharing and developing sophisticated models of risks—much like TradFi evolved with derivates.
By firmly keeping sight of their promised potential, while prudently addressing the downside risks, DeFi’s incredible pace of creativity can be maintained. And it is flash loans today that showcase this duality within DeFi in stark relief. The foundations seem shaky but the horizons excitingly clear. And for turning that promise into responsible reality, technical literacy will be as important as economic vision.
Find L2IV at l2iterative.com and on Twitter @l2iterative
Author: Arhat Bhagwatkar, Research Analyst, L2IV (@0xArhat)
References
Towards A First Step to Understand Flash Loan and Its Applications in DeFi Ecosystem
Themis Protocol: Transaction, Post Mortem
Conic Finance Exploit: Transaction, Post Mortem
JPEG’d Exploit: Transaction, Post Mortem
Alchemix Exploit: Transaction, Post Mortem
Disclaimer: This content is provided for informational purposes only and should not be relied upon as legal, business, investment, or tax advice. You should consult your own advisors as to those matters. References to any securities or digital assets are for illustrative purposes only, and do not constitute an investment recommendation or offer to provide investment advisory services.