⚡ Flash Loans & JIT Liquidity: The Good, The Bad, and The Absolutely Broken
GM DeFi nerds! 🤓
Today we're diving into two of the most powerful—and controversial—primitives in DeFi:
Flash Loans — Borrow millions with ZERO collateral (for 13 seconds)
Just-In-Time (JIT) Liquidity — The MEV strategy that's literally killing passive LPs
These mechanisms have facilitated over $2 trillion in transaction volume in 2024 alone. They've democratized arbitrage, improved market efficiency, and also enabled some of the biggest exploits in crypto history.
Let's break down:
⚡ How flash loans actually work (the atomicity magic)
💰 Legitimate use cases (yes, they exist)
🚨 How they weaponize smart contract bugs
🎯 The JIT Paradox (and why it's killing Uniswap LPs)
🔮 What's coming next (AI arbitrageurs, intent-based solutions)
This is gonna be technical. Buckle up. 🚀
⚡ Flash Loan Mechanics: Borrowing Millions with Zero Collateral
Flash loans sound impossible. How can you borrow $100M without collateral or identity verification?
Answer: Atomicity. ⚛️
The Magic of Atomic Transactions
The Ethereum Virtual Machine (EVM) has a critical property: atomicity.
What this means:
A series of operations is indivisible. Either ALL operations succeed, or the ENTIRE transaction is discarded (reverted).
Think of it like this:
You're moving furniture. Either:
✅ ALL furniture makes it to the new house (success)
❌ Everything stays in the old house (revert)
There's NO in-between state where half the furniture is moved. It's all or nothing.
In blockchain terms:
A flash loan moves the blockchain from State A to State B only if the borrowed funds (plus fee) are returned within the same transaction.
If you can't repay? The entire transaction reverts. It's as if the loan never happened. ⏮️
The Technical Lifecycle (Step-by-Step)
Here's how a flash loan actually executes:
Step 1: Initiation
Your smart contract calls the flashLoan() function on a lending pool (Aave, Balancer, etc.).
solidityaave.flashLoan(
receiverAddress,
assets, // [USDC]
amounts, // [$100,000,000]
params
);
Step 2: Optimistic Transfer
The pool transfers the requested assets to you WITHOUT COLLATERAL.
Yes, you now have $100M in your contract. You didn't deposit anything. Wild. 💰
Step 3: Callback (Strategy Execution)
The pool calls a standardized function in YOUR contract:
solidityfunction executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool) {
// YOUR ARBITRAGE LOGIC HERE
// You have $100M for ~13 seconds
// Do whatever you want with it
// Must approve pool to take back funds + fee
IERC20(usdc).approve(address(pool), amountOwed);
return true;
}
Step 4: Verification
The lending pool checks its balance:
If balance >= initial_amount + fee:
Transaction succeeds ✅
Else:
Transaction reverts ❌ (entire transaction undone)
The fee: Typically 0.05% on Aave V3 (so $50,000 on a $100M loan).
The Risk Profile Shift
Traditional lending:
Risk: Credit risk (will the borrower default?)
Mitigation: Collateral, credit checks, legal recourse
Flash loans:
Risk: Smart contract risk (is the code correct?)
Mitigation: Audits, formal verification, bug bounties
The lender is ONLY at risk if the smart contract has a bug that bypasses the repayment check.
No credit risk. No default risk. Just code risk. 🧑‍💻
💰 Legitimate Use Cases (Yes, They're Not All Evil)
Flash loans get a bad rap because of exploits. But they have legitimate, economy-improving use cases.
Use Case 1: Arbitrage and Market Efficiency 📊
The traditional problem:
ETH is trading at $3,000 on Uniswap and $3,020 on SushiSwap. That's a $20 arbitrage opportunity.
But to capture it, you need:
$1M in capital to make it worthwhile
Ability to execute both trades instantly
Gas to execute
Most retail traders don't have this.
The flash loan solution:
1. Flash loan $1M USDC from Aave
2. Buy 333.33 ETH on Uniswap @ $3,000 = $1M
3. Sell 333.33 ETH on SushiSwap @ $3,020 = $1,006,666
4. Repay flash loan: $1M + 0.05% fee = $1,000,500
5. Profit: $6,166 (minus gas)
Zero personal capital required. Just gas costs.
Why this matters:
Arbitrage converges prices across markets. It's how DeFi stays efficient. Flash loans democratize this—you don't need to be a whale to contribute to market efficiency.
Types of arbitrage:
Spatial Arbitrage: Same asset, different exchanges (example above)
Triangular Arbitrage: Cycle through multiple assets
USDC → ETH → WBTC → USDC
Exploit cross-rate mispricing. Flash loans let you do this at massive scale without owning any of the intermediate assets.
Use Case 2: Collateral Swapping 🔄
The problem:
You have a CDP (Collateralized Debt Position) on MakerDAO:
Collateral: 10 WBTC
Debt: 100,000 DAI
You want to swap WBTC collateral for ETH. But you can't just withdraw the WBTC (you'd be undercollateralized).
The flash loan solution:
1. Flash loan 100,000 DAI
2. Repay your entire debt on MakerDAO
3. Withdraw your 10 WBTC
4. Swap WBTC → ETH
5. Deposit ETH as new collateral
6. Borrow 100,000 DAI
7. Repay flash loan
Result: Swapped collateral types in ONE transaction without needing liquid capital to close and reopen the position. 🎯
Use Case 3: Self-Liquidation (Avoiding Penalties) 🛡️
The problem:
Your collateral is dropping. You're about to get liquidated by the protocol, which charges a liquidation penalty (typically 5-15% of your collateral).
The flash loan solution:
1. Flash loan enough to repay your debt
2. Close position at market rates
3. Withdraw your full collateral (no penalty)
4. Sell just enough collateral to repay flash loan
5. Keep the rest
Savings: Avoid 5-15% liquidation penalty. You're liquidating yourself at 0.05% flash loan fee instead.
Use Case 4: Debt Refinancing 🏦
The problem:
You're borrowing USDC on Compound at 8% APY. Aave is offering 3% APY for the same thing.
Normally you'd need to:
Repay Compound (need liquid USDC)
Withdraw collateral
Deposit on Aave
Borrow USDC again
The flash loan solution:
1. Flash loan 100,000 USDC
2. Repay Compound debt
3. Withdraw collateral from Compound
4. Deposit collateral on Aave
5. Borrow 100,000 USDC on Aave (at 3% instead of 8%)
6. Repay flash loan
All in one atomic transaction. You just saved 5% APY without ever needing liquidity. 💰
🚨 The Dark Side: Flash Loan Attacks
Now let's talk about how flash loans weaponize smart contract vulnerabilities.
The ability to access "infinite leverage" instantly amplifies the severity of existing bugs.
Attack Vector: Oracle Manipulation
This is the most common flash loan exploit pattern.
How it works:
Step 1: Find a vulnerable protocol
Protocol uses a DEX (like Uniswap) as its SOLE price oracle. No TWAP, no Chainlink, just spot price.
Step 2: Distortion
1. Flash loan $50M USDC
2. Dump it all into a thinly-traded pool (e.g., USDC/TOKEN)
3. TOKEN price crashes from $100 → $10 (on that DEX only)
Step 3: Exploitation
4. Protocol thinks TOKEN is worth $10 (because it only checks that DEX)
5. Attacker deposits 1,000 TOKEN as "collateral"
6. Protocol values it at $10,000 (real value: $100,000)
7. Attacker borrows $9,000 in USDC against it
8. Repay flash loan ($50M + 0.05% fee)
Step 4: Default
The attacker walks away. The protocol has:
$10,000 worth of TOKEN (collateral)
$9,000 owed in USDC (debt)
But TOKEN is actually worth $100,000
Wait, that's profitable for the protocol?
NO. Because the attacker SOLD the TOKEN to crash the price. Once they repay the flash loan and the DEX pool rebalances, TOKEN returns to $100. But the borrowed USDC is GONE.
The protocol has bad debt. 💀
Real-World Case Studies
bZx Attacks (2020) — The OG Flash Loan Exploit
Manipulated sUSD and WBTC prices
Profit: ~$1M across two separate attacks
First major demonstration of flash loan weaponization
Mango Markets (2022) — "Code Is Law" Isn't a Legal Defense
Attacker: Avraham Eisenberg
The scheme:
Used "flash leverage" to pump MNGO perpetual futures
Borrowed $116M against unrealized gains
Withdrew funds
The legal precedent:
Eisenberg argued "code is law"—the protocol allowed it, therefore it's legal.
The verdict: Convicted of market manipulation and fraud.
The lesson: Just because code ALLOWS something doesn't mean it's legal. DeFi isn't a lawless zone. ⚖️
Euler Finance (2023) — The $197M Hack
The bug: Logic error in donateToReserves function
The exploit:
Flash loan $30M DAI
Deposit it, borrow recursively to create 10x leverage
Call donateToReserves to burn collateral (eDAI) WITHOUT liquidity check
Position now massively underwater
Self-liquidate using second address
Liquidation discount mechanism malfunctions due to extreme underwater margin
Attacker claims protocol assets at massive discount
Drain $197M
The aftermath: $177M eventually returned (largest DeFi recovery in history), $19M kept as "bug bounty"
The lesson: Even audited code can have edge-case bugs. Flash loans turn small bugs into catastrophic exploits. 🐛💥
🎯 MEV and Just-In-Time (JIT) Liquidity
Now let's talk about the OTHER controversial DeFi primitive: JIT Liquidity.
This is an MEV strategy that's literally killing passive Uniswap LPs. Let me explain.
What Is JIT Liquidity?
Just-In-Time liquidity is when a searcher provides liquidity for the duration of a SINGLE BLOCK to capture trading fees from one specific swap.
The three-transaction bundle:
Transaction 1: Mint
Searcher adds concentrated liquidity in a narrow tick range
Positioned exactly where the target swap will execute
Transaction 2: Swap (The Victim)
Large trader swaps 1,000 ETH for USDC
Searcher's liquidity captures ~85% of the trading fees
Passive LPs get ~15%
Transaction 3: Burn
Searcher removes liquidity immediately
Takes fees and principal
Zero ongoing risk
All three transactions happen in the SAME BLOCK. ⚡
The searcher provides liquidity for ~12 seconds, captures the fees, and exits. Rinse and repeat.
The Numbers (Why It Works)
Example swap:
Trader swaps 1,000 ETH (~$3M) on Uniswap V3 USDC/ETH pool (0.05% fee).
Trading fee generated: $3M × 0.05% = $1,500
Without JIT:
Passive LPs split the $1,500 proportionally based on liquidity
With JIT:
JIT liquidity: $8M deployed in narrow range
Passive liquidity: $50M in wide range
JIT captures: ~$1,275 (85%)
Passive LPs get: ~$225 (15%)
JIT searcher net profit: $1,275 - gas costs (~$50) = $1,225 profit for 12 seconds of capital deployment
That's ~0.015% return in one block. Annualized (if you could repeat this every block): ~400,000% APR. 🤯
Obviously unsustainable and not repeatable every block, but you see the edge.
The JIT Paradox (Why This Breaks Everything)
JIT liquidity creates what's called the "JIT Paradox":
For the specific trader:
✅ Better execution (average price improvement of 0.139%)
✅ Lower slippage (more liquidity in the exact range they need)
For passive LPs:
❌ Fee dilution (lose 85% of revenue on high-value swaps)
❌ Cherry-picking (JIT only shows up for PROFITABLE trades)
❌ Adverse selection (passive LPs left with all the unprofitable, toxic flow)
For the ecosystem:
❌ Market hollowing: Starved of fees, passive LPs withdraw
❌ Less "resting" liquidity in the pool
❌ Higher slippage for SMALL retail trades (which don't trigger JIT)
❌ Pool becomes unusable for normal users
The ultimate result:
Uniswap V3 pools become empty except when JIT searchers briefly appear. Retail users get WORSE execution because passive liquidity is gone.
This is a death spiral. 💀
The Centralization Problem (It's a Whale's Game)
JIT requires capital proportional to swap size.
The math:
To capture 85% of fees on a $3M swap, you need ~$8M in liquidity (roughly 269x the fee amount).
Who can deploy $8M for 12 seconds repeatedly?
❌ Retail LPs (don't have the capital)
❌ Small bots (don't have the capital)
✅ One or two massive MEV operations
Historical data:
A single bot (0xa57...6CF) has captured 92% of all JIT profits on Uniswap V3.
One bot. 92% of profits. 🐋
This isn't decentralized. This is maximum centralization with extra steps.
🏦 Protocol Landscape (2026 Update)
Here's where you can actually use these mechanisms:
Flash Loans
Aave V3/V4
Fee: 0.05%
Best for: General arbitrage, debt refinancing
Features: Unified liquidity across all Aave markets
Most popular choice for retail
Balancer V2/V3
Fee: 0% (FREE!)
Best for: High-frequency arbitrage
Features: Uses Transient Storage (EIP-1153) for ultra-efficient execution
Best choice if you're doing massive volume
MakerDAO Flash Mint
Fee: 0.05%
Best for: Borrowing DAI specifically
Features: Can mint up to the global debt ceiling (effectively infinite DAI)
Use when you need DAI, not other assets
Uniswap V3/V4 Flash Swaps
Fee: Pool fee (typically 0.05% or 0.3%)
Best for: Arbitrage within specific trading pairs
Features: Integrated directly into swap mechanism
dYdX V4
Fee: Variable
Best for: Specialized market making on Cosmos app-chain
Features: Different architecture (not EVM)
JIT Liquidity
Where it's happening:
Uniswap V3 (most prevalent)
SushiSwap V3
Any concentrated liquidity AMM
Who's doing it:
Professional MEV searchers
Basically one or two giant bots
Not accessible to retail (capital requirements too high)
🛡️ Defensive Innovations (How Protocols Are Fighting Back)
The DeFi ecosystem isn't just accepting these attacks. Here's how protocols are adapting:
Defense 1: EIP-3156 (Standardization)
What it does:
Standardized the flash loan interface across protocols.
Why it matters:
Before: Every protocol had different function names, parameters, callback structures. Exploits could slip through due to inconsistent implementations.
After: One standard interface. Easier to audit. Better security tooling.
Impact: Reduced implementation bugs, improved composability
Defense 2: TWAP Oracles (No More Spot Price Manipulation)
The old way:
solidityuint256 price = uniswapPool.getPrice(); // Spot price
The problem: Can be manipulated in a single block with flash loans
The new way:
solidityuint256 price = oracle.getTWAP(30 minutes); // Time-weighted average
Why it works:
TWAP averages the price over 30 minutes. You can't manipulate this with a single-block flash loan attack.
Who's using it:
Uniswap V3 oracles
Chainlink Price Feeds
Most modern DeFi protocols
Result: Oracle manipulation attacks have drastically decreased since TWAP adoption. 📉
Defense 3: Uniswap V4 Hooks (Anti-JIT Mechanisms)
The innovation:
Uniswap V4 introduces "hooks"—custom code that runs before/after swaps and liquidity operations.
The anti-JIT hook:
Liquidity Penalty Hook:
Tracks when liquidity was added
If liquidity is removed within 1-5 blocks, confiscate a portion of the fees
Or charge a withdrawal tax
Example:
solidityif (block.number - depositBlock < 5) {
// JIT detected! Confiscate 50% of fees
fees = fees * 0.5;
}
The impact:
Destroys the risk-free nature of JIT. If you can't remove liquidity immediately without penalty, the strategy doesn't work.
Status: Live on Uniswap V4 (optional for pools to enable)
Result: Pools with anti-JIT hooks are seeing passive LP revenue increase by 40-60%. 📈
🤖 Emerging Trends (The Future is Here)
Trend 1: AI Arbitrageurs
The evolution:
2020: Manual flash loan scripts
2022: Automated bots scanning for arb opportunities
2024: Bots with ML models predicting profitable trades
2026: Autonomous AI agents that:
Predict mempool movements
Optimize slippage in sub-millisecond timeframes
Adapt strategies in real-time based on gas prices
Coordinate multi-hop arbitrage across 10+ DEXs
Who's building this:
Flashbots (MEV research)
Professional trading firms
Well-funded MEV operations
The result:
Human traders are being priced out. If you're manually running flash loan arb scripts, you're already too slow.
The edge now belongs to:
AI-powered prediction models
Sub-millisecond execution
Coordination across multiple chains
Trend 2: Intent-Based Solutions (Killing JIT)
The problem JIT created:
Public mempools are transparent. Searchers can see your trade BEFORE it executes and front-run it with JIT liquidity.
The solution:
Intent-based architectures like CoW Swap and UniswapX:
How they work:
You submit an "intent" (e.g., "I want to swap 1,000 ETH for USDC")
Intent goes to PRIVATE solver network (not public mempool)
Solvers compete to fill your order
Best execution wins
Settlement happens on-chain
Why JIT doesn't work here:
Your trade is HIDDEN until execution. Searchers can't see it coming. No time to deploy JIT liquidity.
The result:
✅ Better execution for users
✅ No JIT parasitism
✅ Passive LPs protected
Adoption:
CoW Swap: ~$50B in volume (2024)
UniswapX: Launched 2024, growing fast
The future: Most volume will move to intent-based systems, leaving traditional AMMs for long-tail assets. 🔮
Trend 3: Institutional Adoption (Permissioned Flash Loans)
The evolution:
Flash loans were originally fully permissionless. Anyone could use them.
The new model: Permissioned pools
Aave Arc:
KYC-verified entities only
Institutional flash loans for:
Forex hedging on-chain
Cross-border arbitrage
Compliant treasury management
Why institutions want this:
✅ Capital efficiency (don't need to hold idle capital for arb)
✅ Regulatory compliance (KYC/AML built in)
✅ Lower risk (permissioned participants)
Use cases:
Banks hedging currency exposure
TradFi firms doing on-chain arbitrage
Institutional treasury operations
The irony:
DeFi started as "permissionless finance." Now the biggest growth is in permissioned DeFi that looks a lot like TradFi... but on-chain. 🏦
🧠 The Bigger Picture: What This All Means
Flash loans and JIT liquidity represent a fundamental shift in how financial markets work.
The Decoupling of Capital from Market Participation
Traditional finance:
Need capital to make markets
Need capital to arbitrage
Need capital to provide liquidity
DeFi with flash loans:
Need ZERO capital for arbitrage
Need ZERO capital for certain market-making strategies
Capital access is decoupled from wealth
What this enables:
✅ Democratized market efficiency
✅ Anyone can contribute to price discovery
✅ Markets correct faster
What this breaks:
❌ Security models based on capital requirements
❌ Oracles that assume manipulation is expensive
❌ Protocols that don't account for infinite leverage attacks
The JIT Problem: When Efficiency Kills Sustainability
JIT liquidity is peak capital efficiency:
Deploy capital for 12 seconds
Capture fees
Zero ongoing risk
But it's TOO efficient. It's so efficient that it destroys the ecosystem it depends on.
The paradox:
JIT needs passive liquidity to exist (to have pools with depth). But JIT kills passive liquidity (by stealing all the fees). Eventually, there's no passive liquidity left, and JIT can't function either.
This is a tragedy of the commons. 🌾
Solutions:
Anti-JIT hooks (Uniswap V4)
Intent-based systems (CoW Swap, UniswapX)
Fee structures that favor long-term liquidity
Code Is Law... Until It Isn't
The Mango Markets case established:
Just because smart contract code ALLOWS an action doesn't mean it's LEGAL.
Implications:
Flash loan "exploits" might be prosecuted as fraud
"Code is law" is not a legal defense
DeFi participants are subject to existing financial regulations
The reality:
DeFi exists within legal frameworks. It's not a lawless zone. Developers and users need to understand both code AND law. ⚖️
🎯 Key Takeaways
Flash Loans:
✅ Democratize arbitrage (anyone can participate)
✅ Improve market efficiency (prices converge faster)
✅ Enable advanced strategies (collateral swaps, self-liquidation)
❌ Weaponize smart contract bugs (small bugs → massive exploits)
❌ Require sophisticated defense (TWAP oracles, standardization)
JIT Liquidity:
✅ Improves execution for large traders (0.139% price improvement)
✅ Peak capital efficiency (earn fees with 12 seconds of deployment)
❌ Kills passive LP revenue (85% fee capture)
❌ Creates market hollowing (passive LPs withdraw)
❌ Extremely centralized (one bot = 92% of profits)
The Future:
🤖 AI arbitrageurs replacing human traders
🔒 Intent-based systems neutralizing MEV/JIT
🏛️ Institutional adoption via permissioned pools
🛡️ Protocols adapting with hooks and penalties
🗣️ Discussion Questions
For the DeFi builders and traders:
Have you used flash loans? For what purpose?
If you're a Uni V3 LP, have you noticed the JIT problem eating your fees?
Do you think anti-JIT hooks will work, or will searchers find workarounds?
Should protocols allow flash loans given the exploit risk?
Are intent-based systems the future, or just a temporary solution?
What other defenses could protocols implement against flash loan attacks?
Drop your experiences and thoughts below! 👇
Not financial advice. Flash loans and MEV strategies involve significant technical and financial risk. Smart contract bugs can lead to total loss of funds. Regulatory frameworks are evolving and vary by jurisdiction. Always DYOR and understand the risks before participating. 🙏
8:07
2
1 comment
David Zimmerman
6
⚡ Flash Loans & JIT Liquidity: The Good, The Bad, and The Absolutely Broken
DeFi University
skool.com/defiuniversity
Master DeFi from beginner to advanced. Security-first curriculum, live mentorship, gamified learning. Join us and build DeFi expertise safely.
Leaderboard (30-day)
Powered by