Mean Finance
Search…
Executing a Flash Loan
Flash Loans can be divided into three parts:
    1.
    Calling the pair
    2.
    Receiving the loan and doing something with it
    3.
    Returning the loan plus the fee
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/IDCAPairLoanCallee.sol';
5
import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
6
7
// In order to receive the loan in step 2, you need to implement IDCAPairLoanCallee
8
contract MyContract is IDCAPairLoanCallee {
9
10
IDCAPair public immutable pair;
11
12
constructor(IDCAPair _pair) {
13
pair = _pair;
14
}
15
16
function executeLoan(uint256 _amountToBorrowTokenA, uint256 _amountToBorrowTokenB) external {
17
// Step 1, calling the pair and executing the loan
18
pair.loan(_amountToBorrowTokenA, _amountToBorrowTokenB, address(this), '');
19
}
20
21
function DCAPairLoanCall(
22
address _sender, // The loan originator, in this case this same contract
23
IERC20Metadata _tokenA,
24
IERC20Metadata _tokenB,
25
uint256 _amountBorrowedTokenA, // Amount borrowed for token A
26
uint256 _amountBorrowedTokenB, // Amount borrowed for token B
27
uint256 _feeTokenA, // How much to return in fees for token A
28
uint256 _feeTokenB, // How much to return in fees for token B
29
bytes calldata _data // Whatever was sent to `loan`
30
) external {
31
// Step 2, do something with the borrowed tokens
32
...
33
34
// Step 3, return the borrowed tokens + fee
35
_tokenA.transfer(msg.sender, _amountBorrowedTokenA + _feeTokenA);
36
_tokenB.transfer(msg.sender, _amountBorrowedTokenB + _feeTokenB);
37
38
}
39
}
Copied!
Last modified 2mo ago
Copy link