Mean Finance
Search…
Flash Swaps
Flash Swaps are the most complex way of executing swaps, but at the same time they provide the biggest potential for profit. This is because the user will receive their reward tokens before having to send the required tokens, but at the same time the caller can actually borrow all of the pair's liquidity for free. In that sense, this action can be seen both as a flash swap and a flash loan.
Flash Swaps can be divided into three parts:
    1.
    Calling the pair
    2.
    Receiving the reward and borrowed (if any) tokens, and doing something with it
    3.
    Returning the needed and borrowed (if any) tokens
The caller in step one can be different from the contract in step 2 and 3, but for the purposes of this example, they will all be the same contract.
1
pragma solidity 0.8.6;
2
3
import '@mean-finance/dca-v1/contracts/interfaces/IDCAPair.sol';
4
import '@mean-finance/dca-v1/contracts/interfaces/IDCAPairSwapCallee.sol';
5
import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
6
7
// In order to receive the reward + borrowed tokens in step 2, you need to implement IDCAPairSwapCallee
8
contract MyContract is IDCAPairSwapCallee {
9
10
IDCAPair public immutable pair;
11
12
constructor(IDCAPair _pair) {
13
pair = _pair;
14
}
15
16
function executeSwap(uint256 _amountToBorrowTokenA, uint256 _amountToBorrowTokenB) external {
17
// Step 1, calling the pair and executing the swap
18
// Note: for the flash swap to be executed, the 'bytes' parameters needs to have length > 0.
19
pair.swap(_amountToBorrowTokenA, _amountToBorrowTokenB, address(this), '-');
20
}
21
22
function DCAPairSwapCall(
23
address _sender, // The swap originator, in this case this same contract
24
IERC20Metadata _tokenA,
25
IERC20Metadata _tokenB,
26
uint256 _amountBorrowedTokenA, // How much of token A was borrowed as part of the swap
27
uint256 _amountBorrowedTokenB, // How much of token B was borrowed as part of the swap
28
bool _isRewardTokenA, // Determines which token is reward and which to provide
29
uint256 _rewardAmount, // How much was sent optimistically
30
uint256 _amountToProvide, // How much needs to be sent back to the pair
31
bytes calldata _data // Whatever was sent to `swap`
32
) external {
33
// Step 2, do something with the reward and borrowed tokens
34
...
35
36
// Step 3, return the borrowed and needed tokens
37
_tokenA.transfer(msg.sender, _amountBorrowedTokenA + (_isRewardTokenA ? 0 : _amountToProvide));
38
_tokenB.transfer(msg.sender, _amountBorrowedTokenB + (_isRewardTokenA ? _amountToProvide : 0));
39
}
40
}
Copied!
Last modified 2mo ago
Copy link