Flash Swaps

In Uniswap V2 swaps are executed “optimistically”, meaning that if desired, tokens can be requested and sent to an address before payment for said tokens is collected, as long as payment occurs by the end of the atomic transaction. See the whitepaper for more details on these so-called “flash swaps”.

Example

ExampleFlashSwap.sol

Discussion

Flash swaps must be repayed from within a callback function that’s triggered by the pair executing the swap. Recall the interface of the swap function:

function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;

In a typical swap, payment of token0 for token1 or vice versa must be completed before the swap function is called (see Sending Tokens), and data.length must be 0. In a flash swap, prepayment need not occur if data.length is > 0, indicating that the pair should call the following function on the to address:

function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;

This function is then responsible for returning enough tokens to the pair to satisfy the invariant (accounting for fees).

This site is a work in progress. Found an issue?