-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDydxFlashLoanDemo.sol
67 lines (54 loc) · 2.33 KB
/
DydxFlashLoanDemo.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "@studydefi/money-legos/dydx/contracts/DydxFlashloanBase.sol";
import "@studydefi/money-legos/dydx/contracts/ICallee.sol";
contract DydxFlashloanDemo is ICallee, DydxFlashloanBase {
struct MyCustomData {
address token;
uint256 repayAmount;
}
// This is the function that will be called postLoan
// i.e. Encode the logic to handle your flashloaned funds here
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
MyCustomData memory mcd = abi.decode(data, (MyCustomData));
uint256 balOfLoanedToken = IERC20(mcd.token).balanceOf(address(this));
// Note that you can ignore the line below
// if your dydx account (this contract in this case)
// has deposited at least ~2 Wei of assets into the account
// to balance out the collaterization ratio
require(
balOfLoanedToken >= mcd.repayAmount,
"Not enough funds to repay dydx loan!"
);
// TODO: Encode your logic here
// E.g. arbitrage, liquidate accounts, etc
}
function initiateFlashLoan(address _solo, address _token, uint256 _amount)
external
{
ISoloMargin solo = ISoloMargin(_solo);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(_solo, _token);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_amount);
IERC20(_token).approve(_solo, repayAmount);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _amount);
operations[1] = _getCallAction(
// Encode MyCustomData for callFunction
abi.encode(MyCustomData({token: _token, repayAmount: repayAmount}))
);
operations[2] = _getDepositAction(marketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
}
}