Flash Swap
A flash swap lets you receive tokens from a DEX liquidity pool before paying for them, as long as payment completes atomically.
Key Takeaways
- A flash swap lets you withdraw tokens from a DEX liquidity pool and use them for any purpose, as long as you return the equivalent value (plus a fee) by the end of the same transaction. If repayment fails, the entire transaction reverts.
- Flash swaps differ from flash loans in their source and repayment flexibility: they draw from trading pools rather than lending pools, and you can repay with either the borrowed token or its pair token in the pool.
- Common use cases include capital-free arbitrage, collateral swaps, and self-liquidation: all executed atomically within a single blockchain transaction.
What Is a Flash Swap?
A flash swap is a feature offered by decentralized exchanges like Uniswap that allows a smart contract to withdraw tokens from a liquidity pool before paying for them. The caller receives the output tokens upfront, executes arbitrary logic with those tokens, and then satisfies the pool's invariant by the end of the transaction. If the caller fails to return sufficient value, the blockchain automatically rolls back every state change, protecting the liquidity providers from any loss.
Flash swaps were introduced by Uniswap V2 as a native feature of its pair contracts. Unlike traditional swaps where input tokens must be sent before output tokens are received, flash swaps reverse this order: output first, input later. This inversion is made possible by atomic composability, the guarantee that all operations within a single Ethereum transaction either succeed together or fail together.
The concept is closely related to flash loans, but with a key distinction. Flash loans draw from dedicated lending pools (such as Aave or dYdX) and must be repaid in the same asset that was borrowed. Flash swaps draw from AMM trading pools and offer a more flexible repayment model: the caller can return the same tokens they withdrew, pay the equivalent value in the paired token, or use any combination of both.
How It Works
Flash swaps exploit the same atomicity property that makes flash loans possible, but they operate through a callback mechanism built into the DEX pair contract rather than through a separate lending protocol.
- A smart contract calls the
swap()function on a Uniswap pair contract, requesting output tokens and passing a non-emptydataparameter (the non-empty data signals a flash swap rather than a standard swap) - The pair contract transfers the requested tokens to the caller immediately, before receiving any input
- The pair contract invokes a callback function (
uniswapV2Call) on the caller's contract, giving it control to execute any logic with the borrowed tokens - Inside the callback, the caller performs its strategy: arbitrage across other DEXs, collateral operations on lending protocols, or any other on-chain activity
- Before the callback returns, the caller must transfer sufficient tokens back to the pair contract to satisfy the constant product invariant (plus the 0.3% fee)
- The pair contract verifies that its reserves (adjusted for fees) meet the invariant. If they do not, the entire transaction reverts
The Callback Mechanism
The callback is the core of what makes flash swaps work. When a Uniswap V2 pair detects a non-empty data parameter in the swap() call, it invokes the IUniswapV2Callee interface on the recipient address:
// The interface your contract must implement
interface IUniswapV2Callee {
function uniswapV2Call(
address sender,
uint amount0,
uint amount1,
bytes calldata data
) external;
}
// Simplified flash swap flow
contract FlashSwapExample is IUniswapV2Callee {
function executeFlashSwap(
address pair,
uint amountOut
) external {
// Request tokens with non-empty data
// to trigger the callback
IUniswapV2Pair(pair).swap(
amountOut, 0, address(this), "flash"
);
}
function uniswapV2Call(
address sender,
uint amount0,
uint amount1,
bytes calldata data
) external {
// 1. Use the borrowed tokens here
// 2. Calculate repayment with 0.3% fee
uint fee = (amount0 * 3) / 997 + 1;
uint repayAmount = amount0 + fee;
// 3. Transfer repayment to the pair
IERC20(token).transfer(msg.sender, repayAmount);
}
}The pair contract checks its reserves after the callback returns. The product of reserves (adjusted for fees) must be at least as large as before the swap. This invariant check is what enforces repayment: if insufficient tokens were returned, the math fails and the transaction reverts.
Fee Structure
Flash swaps on Uniswap V2 carry the same 0.3% fee as regular swaps. The fee is calculated as (amount * 3) / 997 + 1, rounded up to prevent rounding exploits. On Uniswap V3, the fee depends on the pool tier (0.01%, 0.05%, 0.3%, or 1%). These fees go to liquidity providers, compensating them for the temporary use of their capital.
Repayment Flexibility
Unlike flash loans, which require repayment in the same borrowed asset, flash swaps allow repayment in either token of the pair. If you borrow Token A from an A/B pool, you can repay with Token A (effectively a flash loan from the pool) or with Token B (effectively a deferred swap where you receive output first and provide input later). This flexibility is what makes flash swaps particularly powerful for multi-step DeFi strategies.
Flash Swaps vs. Flash Loans
| Feature | Flash Swap | Flash Loan |
|---|---|---|
| Source of liquidity | DEX trading pools (Uniswap, SushiSwap) | Lending pools (Aave, dYdX) |
| Repayment asset | Either token in the pair | Same asset that was borrowed |
| Typical fee | 0.01% to 1% (pool-dependent) | 0% to 0.05% |
| Available assets | Any token with a pool | Only assets in lending markets |
| Callback interface | DEX-specific (uniswapV2Call) | ERC-3156 (onFlashLoan) |
| Collateral required | None | None |
Flash loans are typically cheaper (Aave charges 0.05% vs. Uniswap's 0.3%), making them preferred for straightforward borrow-and-repay scenarios. Flash swaps shine when the strategy involves swapping between token pairs, since the repayment flexibility eliminates extra swap steps and their associated fees.
Use Cases
Capital-Free Arbitrage
The most common use of flash swaps is arbitrage across DEXs without requiring any upfront capital. When the same token pair trades at different prices on two exchanges, a flash swap can capture the spread:
- Flash-swap Token A from Uniswap (receive tokens before paying)
- Sell Token A on SushiSwap at the higher price for Token B
- Return Token B to the Uniswap pool as repayment (plus the 0.3% fee)
- Keep any remaining profit
Because the flash swap allows repayment in either token, the arbitrageur never needs to hold capital in advance. The entire operation is risk-free: if the price difference is insufficient to cover fees and gas, the transaction simply reverts. This is closely related to MEV extraction, where searchers compete to capture these opportunities within block ordering.
Collateral Swaps
Users with active positions on lending protocols can use flash swaps to change their collateral type without closing the position. For example, a user collateralizing a DAI loan with ETH who wants to switch to WBTC collateral can:
- Flash-swap DAI from a Uniswap pool to repay the outstanding loan
- Withdraw the freed ETH collateral from the lending protocol
- Swap ETH for WBTC on a DEX
- Deposit WBTC as new collateral and re-borrow DAI
- Return the borrowed DAI to the Uniswap pool
Without flash swaps, this would require extra capital to temporarily cover the loan, or the user would need to close the position entirely and risk liquidation during the process.
Self-Liquidation
When a lending position approaches its liquidation threshold, the borrower can use a flash swap to close it before incurring the protocol liquidation penalty (typically 5% to 15%). The borrower flash-swaps enough tokens to repay the debt, withdraws the collateral, converts a portion to repay the flash swap fee, and keeps the rest. The flash swap fee (0.3% on Uniswap V2) is far cheaper than most liquidation penalties.
Instant Token Conversions
Flash swaps enable "just-in-time" token conversions for smart contracts that need a specific token for an operation but hold a different one. A contract can flash-swap the required token, complete the operation, and repay with the token it already holds: all in a single transaction without any pre-existing token balance in the required asset.
Evolution: Flash Accounting in Uniswap V4
Uniswap V4 introduced a generalized version of the flash swap concept called flash accounting. Instead of transferring tokens in and out of pools during each operation, V4 tracks internal balance deltas throughout a transaction. Tokens only physically move at the very end, when all debts must net to zero.
This approach extends the "receive first, pay later" principle across multiple pools and operations within a single transaction. It reduces gas costs significantly by eliminating intermediate token transfers and enables more complex multi-hop strategies that would be prohibitively expensive with V2-style flash swaps.
Risks and Considerations
Smart Contract Vulnerabilities
Flash swap callbacks introduce reentrancy risk if not properly guarded. Because the pair contract calls an external function on the borrower's contract before verifying repayment, a malicious or buggy callback can attempt to re-enter the pair contract or interact with other protocols in unintended ways. Contracts must follow the checks-effects-interactions pattern and validate that the callback caller is the expected pair contract.
Oracle Manipulation
Flash swaps (like flash loans) can be used to manipulate on-chain price oracles. An attacker can flash-swap a large amount of tokens, execute a massive trade to distort pool-based price feeds, exploit a protocol that reads those manipulated prices, and repay the flash swap with the extracted value. Protocols defend against this by using time-weighted average price (TWAP) oracles or external oracle networks like Chainlink that cannot be manipulated within a single transaction. See the oracle manipulation glossary entry for a deeper look at this attack vector.
Gas Costs and MEV Competition
Flash swap transactions are complex multi-step operations with higher gas costs than simple swaps. During periods of network congestion, gas fees can exceed the profit from an arbitrage opportunity, making the strategy unprofitable. Additionally, profitable flash swap transactions in the mempool are visible to MEV searchers and block builders, who can front-run or copy the strategy with higher gas bids.
Protocol-Specific Risks
Each DEX implements flash swaps differently. Uniswap V2 uses uniswapV2Call, Uniswap V3 uses uniswapV3SwapCallback, and other protocols have their own callback interfaces. Code written for one protocol does not automatically work on another, and subtle differences in fee calculation or invariant checks can cause unexpected reverts or losses if not carefully handled.
Why It Matters
Flash swaps represent one of the most capital-efficient primitives in DeFi. By allowing anyone to access pool liquidity without upfront capital, they democratize strategies that were previously available only to well-capitalized traders. Arbitrage via flash swaps improves market efficiency by aligning prices across venues, and self-liquidation via flash swaps saves borrowers from punitive liquidation penalties.
However, this same accessibility creates systemic risks. Flash swaps lower the cost of exploiting vulnerable protocols to near zero, requiring the entire DeFi ecosystem to maintain higher security standards. For a broader look at how uncollateralized borrowing mechanisms interact with DeFi security, see the research article on sustainable DeFi revenue models.
Flash swaps only function on blockchains with composable smart contract execution and atomic rollback semantics. They do not exist on Bitcoin's UTXO-based Layer 1, which lacks mid-execution callbacks. Bitcoin-native protocols like Spark use different mechanisms: cryptographic primitives such as HTLCs and threshold signatures to enforce conditionality across separate transactions, rather than relying on intra-transaction revert logic.
This glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.