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”.
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 function documented below on the to address. This function is then responsible for returning enough tokens to the pair to satisfy the invariant (accounting for fees).
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Callee.sol';
pragma solidity >=0.5.0;interface IUniswapV2Callee {function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;}