Flash Swap
Taking tokens from a pool before paying for them, with the payment enforced in the same transaction.
Basically
A flash swap lets you take tokens from a trading pool before you pay. You must pay within the same transaction, or the whole transaction is undone.
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 draw from trading pools rather than the lending pools used by flash loans. You can repay with either the borrowed token or its pair token in the pool.
- Common uses include capital-free arbitrage, collateral swaps and self-liquidation. Each one runs atomically within a single blockchain transaction.
What Is a Flash Swap?
A flash swap is a feature offered by decentralised 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. Traditional swaps require you to send input tokens before receiving output tokens, but flash swaps reverse this order: output first, input later. Atomic composability makes this possible by guaranteeing that all operations within a single Ethereum transaction either succeed together or fail together.
Flash swaps are 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 let the caller 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 use the same atomicity property that makes flash loans possible. They operate through a callback mechanism built into the DEX pair contract rather than through a separate lending protocol.
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 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 enforces repayment: if insufficient tokens were returned, the maths 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, while Uniswap V3 fees depend 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
Flash swaps allow repayment in either token of the pair, unlike flash loans, which require repayment in the same borrowed asset. 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 makes flash swaps particularly powerful for multi-step DeFi strategies.
Flash Swaps vs. Flash Loans
Flash loans are typically cheaper, with Aave charging 0.05% versus 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.
Capital-Free Arbitrage
The most common use of flash swaps is arbitrage across DEXs without requiring any upfront capital. A flash swap can capture the spread when the same token pair trades at different prices on two exchanges.
The flash swap allows repayment in either token, so 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 collateralising a DAI loan with ETH who wants to switch to WBTC collateral can make the change with a flash swap.
Flash swaps remove the need for extra capital to temporarily cover the loan. Without them, the user would need that capital or would need to close the position entirely and risk liquidation during the process.
Self-Liquidation
A borrower can use a flash swap to close a lending position before it reaches its liquidation threshold and incurs 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 of 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. Everything happens in a single transaction without any pre-existing token balance in the required asset.
Evolution: Flash Accounting in Uniswap V4
Uniswap V4 introduced a generalised 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.
Flash accounting 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. It also enables more complex multi-hop strategies that would be prohibitively expensive with V2-style flash swaps.
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. Profitable flash swap transactions in the mempool are also 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 democratise strategies that were previously available only to well-capitalised 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.
Flash swaps also create systemic risks through this same accessibility. They 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 uncollateralised 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 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.