Flash Loans in DeFi Explained: How They Work and What They're Used For
By Jorge Rodriguez — DeFi Protocols
The atomic transaction mechanic that makes flash loans possible and why they cannot leave a protocol with bad debt
How legitimate traders use flash loans for arbitrage, collateral swaps, and self-liquidation
How flash loan attacks actually work and what protocols do to defend against them
Flash Loans in DeFi Explained: How They Work and What They're Used For
Flash loans are the only financial instrument in existence that can make you the largest borrower in DeFi for a few seconds with zero collateral. You borrow $50 million in a single transaction. You execute whatever logic you need. You repay the principal plus a small fee. All within the same block. If repayment fails, the entire transaction reverts as if it never happened. That is not a metaphor or an abstraction. That is the literal on-chain mechanic, enabled by a single property of blockchain transactions: atomicity. This article covers the execution mechanics, the legitimate use cases, how attackers weaponize them, and what defenses have emerged since the first major exploits in 2020. Written for readers who already understand overcollateralized lending on Aave or Compound. No DeFi 101 context.
What Is a Flash Loan? The Atomic Transaction Concept
A flash loan is an uncollateralized loan that must be borrowed and fully repaid within a single blockchain transaction. That single constraint is what makes everything else possible, and it rests on one foundational blockchain property. **Atomicity Is the Core Mechanic** A blockchain transaction is atomic: it either executes completely or it reverts entirely. There is no partial state. If any step in a multi-step transaction fails, every previous step is rolled back. The chain behaves as if none of it occurred. Flash loans exploit this property directly. A lending protocol can send you millions of dollars because the rules of the chain guarantee one outcome: either you return the funds plus a fee before the transaction closes, or the entire transaction reverts. The protocol never actually loses custody. If repayment fails, the loan never happened at the state level. This is what separates flash loans from every other lending instrument. Traditional loans require collateral because lenders cannot enforce repayment in every scenario. On-chain atomicity creates a perfect enforcement mechanism that requires no collateral, no credit check, and no trust. It also explains [why protocols require collateral to avoid bad debt](https://yields.lince.finance/blog/risk-management/bad-debt-defi-lending) in every other lending context: atomicity is the specific property that flash loans exploit to bypass that requirement. **Where Flash Loans Exist** Marble Protocol introduced the concept in 2018. Aave popularized the term and the modern interface with Aave V1 in 2020. Today, flash loan functionality exists across multiple protocols and chains: • Aave V3: the most widely used implementation, available across Ethereum, Polygon, Arbitrum, Optimism, Base, Avalanche, and other chains • Uniswap V2/V3: implements flash loans as "flash swaps" where you borrow one token from a pool and repay in either the borrowed token or its pair asset • Balancer: supports flash loans from its centralized vault reserves • dYdX: an early adopter with flash loan support built into its margin trading infrastructure Flash loans require a custom smart contract to receive funds and execute logic. They are not available through any lending protocol's standard UI for arbitrary use cases.
How Flash Loans Work: Borrow, Execute, Repay -- All in One Transaction
 The execution flow of a flash loan is consistent across protocols. Using Aave V3 as the reference implementation, the sequence unfolds as follows. **Step 1: Initiation** The user, or a bot, calls the `flashLoan()` function on the Aave V3 Pool contract, specifying the asset to borrow, the amount, the address of a receiver contract, and optional params forwarded to the callback. **Step 2: Fund Transfer** Aave transfers the full requested amount to the receiver contract. At this moment, the receiver holds the borrowed capital. **Step 3: Execution Callback** Aave immediately calls `executeOperation()` on the receiver contract. This is where the user's logic runs: arbitrage across two DEXs, a collateral swap, a liquidation, or any other on-chain interaction. The contract can call any other protocol during this window. **Step 4: Repayment Check** Before `executeOperation()` returns, the receiver must approve Aave to pull back principal plus fee. Aave V3's standard fee is 0.05% (5 basis points). For whitelisted protocol integrators, it drops to 9 basis points. Uniswap flash swaps charge the pool's trading fee: 0.05%, 0.3%, or 1% depending on which pool tier is used. **Step 5: Revert if Unpaid** Aave performs a balance check after the callback completes. If funds have not been returned, the entire transaction reverts. Gas is consumed. No funds move. The protocol takes zero credit exposure at any point in the sequence. **Simplified Pseudocode** ```solidity // User deploys this receiver contract contract FlashLoanReceiver { function executeOperation( address asset, uint256 amount, uint256 premium, // = 0.05% of amount address initiator, bytes calldata params ) external returns (bool) { // ---- Your logic runs here ---- // e.g. arbitrage, collateral swap, liquidation // ------------------------------ // Approve repayment: principal + fee uint256 amountOwed = amount + premium; IERC20(asset).approve(address(POOL), amountOwed); return true; } } ``` The full Aave V3 flash loan specification is documented in the [Aave developer documentation](https://docs.aave.com/developers/guides/flash-loans). Uniswap's variant is covered in the [Uniswap V3 flash integration guide](https://docs.uniswap.org/contracts/v3/guides/flash-integrations/overview). **Multicall and Composability Risk** The callback function can chain interactions across multiple protocols in a single transaction: borrow from Aave, swap on Uniswap, deposit in Curve, withdraw, repay. This composability is the source of both the power and the risk surface. [Price oracle reads that happen inside the same block](https://yields.lince.finance/blog/risk-management/oracle-prices-defi-risk) can be manipulated during this callback window, which is the foundation of most flash loan exploits covered in the sections below.
Flash Loan Use Cases: What Legitimate Traders Actually Do With Them
 Flash loans are most commonly associated with attacks, but legitimate use accounts for far more transaction volume. Four use cases dominate. **Arbitrage** This is the original and most common application. The pattern is straightforward: borrow a large amount, buy an asset on DEX A at the lower price, sell it on DEX B at the higher price, repay the flash loan, keep the spread. Flash loans matter here because capital efficiency limits arbitrage profits for most traders. A bot with $5,000 in capital cannot fully close a price gap that requires $2 million in order size to exhaust. With a flash loan, that same bot can borrow the $2 million, execute the trade, repay, and pocket the spread. The only requirement is that the profit exceeds the flash loan fee plus gas. For DeFi users building [capital-efficient strategies that do not require directional exposure](https://yields.lince.finance/blog/yield-strategies/delta-neutral-strategies-defi), understanding flash loan arbitrage activity is useful context for evaluating protocol TVL stability. The [Lince Yield Tracker](https://yields.lince.finance/tracker) surfaces protocol-level metrics across lending and DEX protocols in one place. **Collateral Swaps** Suppose you hold ETH as collateral in an Aave position to borrow USDC, and you want to migrate that collateral to WBTC without closing your position. The manual process requires repaying your debt first to unlock your collateral, a multi-step sequence that exposes you to price movement between transactions. With a flash loan, the entire migration fits in one atomic transaction: • Flash borrow enough USDC to repay the Aave debt • Repay the debt and unlock ETH collateral • Swap ETH for WBTC on a DEX • Deposit WBTC as new collateral in Aave • Borrow USDC again against the new collateral • Repay the flash loan from the new borrow No multi-step exposure. No price risk between transactions. One atomic operation. **Self-Liquidation** When a position approaches its liquidation threshold, the protocol's liquidation bots will step in and claim a penalty. On Aave, standard liquidation bonuses range from 5% to 15% depending on the asset. Self-liquidation lets you capture that penalty yourself. The process: flash borrow stablecoins equal to your debt, repay your own debt, withdraw your unlocked collateral, sell enough to cover the flash loan fee and principal, keep the rest. You avoid the liquidation penalty that would otherwise transfer to an external bot operator. **Liquidation Bots** Liquidation bots are net positive for protocol health: they remove undercollateralized positions before they become bad debt. But running a liquidation bot traditionally requires holding significant capital reserves to execute repayments on demand. Flash loans remove that barrier. A liquidation bot can borrow the exact repayment amount in the same transaction, trigger the liquidation, receive the discounted collateral, sell it, repay the flash loan, and keep the spread. The operator needs code and gas, not capital reserves. This enables a more competitive liquidation market that benefits protocol solvency.
Flash Loan Attack Explained: How Exploits Actually Work
 Flash loans do not create vulnerabilities. They amplify existing ones by eliminating capital constraints. Any attack that was theoretically possible with $50 million in capital becomes trivially executable with a flash loan, because that capital is now available to any developer who can write the right callback function. **The Generic Attack Pattern** Most flash loan attacks follow a consistent four-step template: • Flash borrow a massive amount of liquidity, often tens of millions in ETH, USDC, or another high-liquidity asset • Use that capital to manipulate an on-chain price oracle, typically by dumping large volume into a low-liquidity AMM pool that a target protocol reads for pricing • While the oracle reads a distorted price, interact with the target protocol in a way that profits from the discrepancy: borrow against artificially inflated collateral, drain reserves at a below-market price, or trigger mechanics that depend on the wrong price input • Unwind the manipulated position before the transaction closes, repay the flash loan, exit with the profit The attacker needs zero starting capital. Profit minus gas minus the flash loan fee is the only threshold to clear. If a $197 million exploit requires a single Ethereum transaction costing $50 in gas, the economic incentive structure is unambiguous. **Why Oracle Design Is the Real Vulnerability** The flash loan is the delivery mechanism. [Why oracle design is the most exploited attack surface in DeFi](https://yields.lince.finance/blog/risk-management/oracle-prices-defi-risk) explains what the mechanism targets. Protocols that read spot prices from low-liquidity AMM pools are structurally exploitable with flash loan capital at scale. The oracle has no way to distinguish a legitimate large trade from a manipulation attempt executing within a single transaction. Most flash loan attacks are oracle attacks. The flash loan provides the capital scale that makes oracle manipulation economically viable. For context on [what happens to a protocol after an exploit](https://yields.lince.finance/blog/risk-management/defi-protocol-exploit-aftermath), including the recovery dynamics and downstream contagion, the post-attack pattern is instructive reading before evaluating any protocol with spot price oracle dependencies.
Notable Flash Loan Attacks: bZx, Harvest Finance, and Euler
Three attacks define the evolution of flash loan exploits. Each one exposed a different category of vulnerability and reshaped how auditors and protocol designers think about flash loan risk. **bZx (February 2020): The First** Two attacks in one week, combined losses around $1 million. The attacker flash borrowed 10,000 ETH from dYdX, opened a leveraged short on WBTC through bZx, simultaneously bought WBTC through Uniswap V1 to spike the price, then profited from bZx's stale price read. Attack 2 used Kyber Network as the manipulated price source. Lesson: a single low-liquidity DEX as a price oracle with no time-averaging is a complete security failure. The bZx attacks launched the oracle security conversation that continues today. **Harvest Finance (October 2020): $34 Million** The attacker flash borrowed USDC and USDT, then repeatedly swapped large volumes through Curve's Y pool to distort the USDC price that Harvest vaults used for share pricing. By depositing at the inflated price and withdrawing at the real price, the attacker drained approximately $34 million from FARM vaults. Lesson: vault share pricing that reads spot AMM prices without time-weighted averaging is a replicable attack template. Any vault that values shares from a pool's spot price can be exploited by anyone with capital to move that price within one transaction. **Euler Finance (March 2023): $197 Million** The largest flash loan-adjacent exploit on record at the time. Euler's attack was not a pure oracle manipulation. It targeted a flaw in Euler's internal accounting between eTokens (deposit tokens) and dTokens (debt tokens), combined with a vulnerability in the donation mechanism and liquidation discount logic. The attacker constructed a position that appeared overcollateralized under one accounting path but was deeply undercollateralized under another, then self-liquidated at a discounted rate to extract $197 million from the protocol. Most funds were eventually returned after negotiation. Lesson: composability between internal accounting modules and liquidation mechanics creates non-obvious attack surfaces that individual module audits may miss entirely. Flash loans make any such interaction exploitable at full scale once discovered. For a broader view of how attack vectors extend beyond smart contract bugs, [not all protocol attacks are technical -- governance can also be weaponized](https://yields.lince.finance/blog/risk-management/governance-attacks-defi) covers the governance attack surface in detail.
How DeFi Protocols Defend Against Flash Loan Attacks
The post-2020 DeFi security landscape changed fundamentally after bZx. Five defense mechanisms now form the standard toolkit against flash loan-based exploits. **TWAP Oracles (Time-Weighted Average Price)** Chainlink and Uniswap V3's TWAP both address the core oracle vulnerability. A time-weighted average price aggregates across many blocks, typically 30 minutes or more. A single-block manipulation cannot meaningfully move a 30-minute TWAP regardless of capital deployed. The tradeoff: TWAP oracles lag real prices during fast market moves, which can slow liquidation responses. **Reentrancy Guards** Many flash loan attack patterns require re-entering the victim contract mid-transaction. Standard reentrancy guards (OpenZeppelin `ReentrancyGuard` or equivalent) prevent a contract from being called while its own execution is still in progress, blocking patterns that depend on calling a function while it is still executing. **Read-Only Reentrancy Protections** An attacker can read a contract's intermediate state from a different contract while the first contract's callback is mid-execution. Protocols now explicitly guard against this pattern, where the attacker reads a distorted intermediate state without directly re-entering. **Same-Block Restrictions** Some protocols prevent deposits and withdrawals within the same transaction or block. Euler introduced this post-exploit. It limits flash loan composability but removes the attack surface that requires both deposit and withdraw to happen atomically. **Formal Verification and Oracle-Specific Audit Focus** Post-2020 audits specifically test oracle manipulation vectors under flash loan conditions. MakerDAO's Oracle Security Module (OSM) introduces a 1-hour price feed delay, making it impossible to exploit a price that has not been posted yet. Flash loans operate within seconds, not hours. Before depositing into any protocol, [how to evaluate a protocol's oracle and security setup](https://yields.lince.finance/blog/risk-management/defi-due-diligence-checklist) provides a structured due diligence framework covering oracle type, upgrade keys, and audit history. For a full picture of how [flash loan exploits fit within a broader taxonomy of DeFi yield risks](https://yields.lince.finance/blog/risk-management/defi-yield-risks-explained), the risk landscape extends well beyond oracle manipulation.
Flash Loans on Solana: What Exists and What's Different
Solana's architecture differs from EVM chains in ways that directly affect how flash loans are implemented and how the attack surface compares. **What Exists on Solana** Flash loan functionality is available on several Solana lending protocols: • Solend supports flash loans natively with standard borrow-and-repay-within-one-transaction mechanics • Marginfi exposes flash loan functionality through its SDK for programmatic users and protocol integrators • Kamino includes flash borrow functionality accessible through its SDK The structural principle is identical: borrow, execute arbitrary logic, repay within the transaction. The execution model differs significantly. **Key Architectural Differences from EVM** Solana transactions require all accounts to be declared upfront before execution begins. On EVM, a contract can dynamically discover and call other contracts during execution. On Solana, the full set of accounts must be specified in advance, which limits certain dynamic composability patterns that EVM flash loan strategies rely on. Solana also enforces a compute unit (CU) budget per transaction. Complex multi-step flash loan strategies can exceed this budget and fail at the transaction level, a constraint that does not exist in the same form on Ethereum. Sealevel, Solana's parallel execution runtime, also means several EVM reentrancy patterns simply do not apply. **Flash Loan Attacks on Solana: Lower Historical Frequency** Flash loan attacks on Solana have been less frequent than on EVM chains for three main reasons: • Lower TVL historically reduces the maximum value extractable per attack • Pyth Network's pull-based oracle model publishes prices off-chain and verifies them on-chain at reference time, creating a different manipulation surface than AMM-based on-chain oracles • The account declaration requirement limits certain dynamic attack patterns Pyth's design is the key factor. Because Pyth prices are not derived from on-chain liquidity, executing large trades within a transaction cannot move the Pyth price that other protocols read in that same block. This removes the most common EVM flash loan exploit vector entirely.
FAQ
### Can I use flash loans without writing smart contracts? Generally no. Flash loans require a custom receiver contract that implements the callback function called by the lending protocol during the transaction. Some tools abstract this for specific use cases: Furucombo and DeFi Saver provide UI-level collateral swap tooling that uses flash loans under the hood for defined operations. For arbitrary strategies, writing and deploying the receiver contract is required. ### Can flash loans be used on any token? Only tokens with sufficient liquidity in the lending protocol's reserves. On Aave V3, flash loans are available for all assets supported by the protocol. Token availability varies by protocol and chain. On Solana lending protocols, flash loan availability is limited to assets held in the specific protocol's supply pools. ### Do flash loans cause impermanent loss for LPs? Not directly. Flash loans are repaid in the same transaction, so protocol reserves return to their original state and the flash loan mechanism itself is neutral to LP positions. However, flash loan arbitrage trades do execute real token swaps on AMMs, which move prices and can affect LP positions indirectly. The LP experiences the price movement from the arbitrage trade, not from the flash loan mechanics. ### Are flash loans legal? Flash loans are a standard protocol feature. Using them for arbitrage, collateral swaps, or liquidations is routine DeFi activity across Ethereum, Solana, and other chains. Using them to exploit protocol vulnerabilities is legally and ethically distinct territory: jurisdiction-dependent and not specifically addressed by most regulatory frameworks. Most countries have not issued specific guidance on flash loan exploits as separate from general computer fraud statutes. ### What is the flash loan fee on Aave? Aave V3 charges 0.05% (5 basis points) on standard flash loans. For whitelisted protocol integrators, the fee drops to 9 basis points. Uniswap V3 flash swaps charge the pool's trading fee: 0.05%, 0.3%, or 1% depending on the pool tier the asset is in. Balancer charges 0% on flash loans directly from its vault, though protocols built on Balancer may add their own fee layer. ### What is the difference between a flash loan and a flash swap? A flash loan gives you a borrowed amount of one asset and requires repayment in that same asset plus a fee. A flash swap, which is Uniswap's implementation, allows you to receive one token from a liquidity pair and repay in either that same token or the other token in the pair. Flash swaps are more flexible for certain arbitrage patterns because repayment can be settled in either asset of a trading pair, simplifying strategies that require a token conversion as part of the repayment flow. ### Why do flash loan attacks target oracles specifically? Because oracles are the input that protocols trust for pricing decisions. If a lending protocol reads a spot price from an AMM pool, anyone who can move that spot price within a transaction can feed the protocol a false price. Flash loans provide the capital to move the price far enough to make the exploit profitable. Protocols using time-weighted oracles like Chainlink or Uniswap V3 TWAP are not exploitable this way because a single-block price manipulation does not change the time-weighted average.
Conclusion
Flash loans are one of the most technically elegant mechanisms in DeFi: uncollateralized lending enforced entirely by code and the atomic properties of blockchain transactions. The lending protocol never takes on credit risk. The borrower needs no starting capital. Atomicity enforces repayment with mathematical certainty. That same elegance is what makes them dangerous in adversarial hands. Every capital barrier that protects protocols from large-scale attacks disappears when an attacker can borrow $50 million for the duration of one block at a cost measured in dollars of gas. Every oracle vulnerability, every accounting flaw, and every liquidation mechanic edge case becomes exploitable at full scale once capital is no longer a constraint. Understanding the mechanics, the attack patterns, and the defenses is essential context for evaluating any DeFi protocol's actual risk surface. Use the [Lince Yield Tracker](https://yields.lince.finance/tracker) to track protocol-level yield and security data side by side before committing capital.