Flash Swaps

Flash Swaps

Flash swaps are an integral feature of Capricorn. In fact, under the hood, all swaps are actually flash swaps! This simply means that pair contracts send output tokens to the recipient before enforcing that enough input tokens have been received. This is slightly atypical, as one might expect a pair to ensure it's received payment before delivery. However, because Cube transactions are atomic, we can roll back the entire swap if it turns out that the contract hasn't received enough tokens to make itself whole by the end of the transaction.

To see how this all works, let's start by examining the interface of the swap function:

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

For the sake of example, let's assume that we're dealing with a DAI/WCUBE pair, where DAI is token0 and WCUBE is token1. amount0Out and amount1Out specify the amount of DAI and WCUBE that the msg.sender wants the pair to send to the to address (one of these amounts may be 0). At this point you may be wondering how the contract receives tokens. For a typical (non-flash) swap, it's actually the responsibility of msg.sender to ensure that enough WCUBE or DAI has already been sent to the pair before swap is called (in the context of trading, this is all handled neatly by a router contract). But when executing a flash swap, tokens do not need to be sent to the contract before calling swap. Instead, they must be sent from within a callback function that the pair triggers on the to address.

Last updated