-
Notifications
You must be signed in to change notification settings - Fork 588
/
Copy pathFlashLoanLogic.sol
270 lines (245 loc) · 10.6 KB
/
FlashLoanLogic.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.10;
import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';
import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {IAToken} from '../../../interfaces/IAToken.sol';
import {IFlashLoanReceiver} from '../../../flashloan/interfaces/IFlashLoanReceiver.sol';
import {IFlashLoanSimpleReceiver} from '../../../flashloan/interfaces/IFlashLoanSimpleReceiver.sol';
import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';
import {UserConfiguration} from '../configuration/UserConfiguration.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {Errors} from '../helpers/Errors.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {DataTypes} from '../types/DataTypes.sol';
import {ValidationLogic} from './ValidationLogic.sol';
import {BorrowLogic} from './BorrowLogic.sol';
import {ReserveLogic} from './ReserveLogic.sol';
/**
* @title FlashLoanLogic library
* @author Aave
* @notice Implements the logic for the flash loans
*/
library FlashLoanLogic {
using ReserveLogic for DataTypes.ReserveCache;
using ReserveLogic for DataTypes.ReserveData;
using GPv2SafeERC20 for IERC20;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeCast for uint256;
// See `IPool` for descriptions
event FlashLoan(
address indexed target,
address initiator,
address indexed asset,
uint256 amount,
DataTypes.InterestRateMode interestRateMode,
uint256 premium,
uint16 indexed referralCode
);
// Helper struct for internal variables used in the `executeFlashLoan` function
struct FlashLoanLocalVars {
IFlashLoanReceiver receiver;
uint256 i;
address currentAsset;
uint256 currentAmount;
uint256[] totalPremiums;
uint256 flashloanPremiumTotal;
uint256 flashloanPremiumToProtocol;
}
/**
* @notice Implements the flashloan feature that allow users to access liquidity of the pool for one transaction
* as long as the amount taken plus fee is returned or debt is opened.
* @dev For authorized flashborrowers the fee is waived
* @dev At the end of the transaction the pool will pull amount borrowed + fee from the receiver,
* if the receiver have not approved the pool the transaction will revert.
* @dev Emits the `FlashLoan()` event
* @param reservesData The state of all the reserves
* @param reservesList The addresses of all the active reserves
* @param eModeCategories The configuration of all the efficiency mode categories
* @param userConfig The user configuration mapping that tracks the supplied/borrowed assets
* @param params The additional parameters needed to execute the flashloan function
*/
function executeFlashLoan(
mapping(address => DataTypes.ReserveData) storage reservesData,
mapping(uint256 => address) storage reservesList,
mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,
DataTypes.UserConfigurationMap storage userConfig,
DataTypes.FlashloanParams memory params
) external {
// The usual action flow (cache -> updateState -> validation -> changeState -> updateRates)
// is altered to (validation -> user payload -> cache -> updateState -> changeState -> updateRates) for flashloans.
// This is done to protect against reentrance and rate manipulation within the user specified payload.
ValidationLogic.validateFlashloan(reservesData, params.assets, params.amounts);
FlashLoanLocalVars memory vars;
vars.totalPremiums = new uint256[](params.assets.length);
vars.receiver = IFlashLoanReceiver(params.receiverAddress);
(vars.flashloanPremiumTotal, vars.flashloanPremiumToProtocol) = params.isAuthorizedFlashBorrower
? (0, 0)
: (params.flashLoanPremiumTotal, params.flashLoanPremiumToProtocol);
for (vars.i = 0; vars.i < params.assets.length; vars.i++) {
vars.currentAmount = params.amounts[vars.i];
vars.totalPremiums[vars.i] = DataTypes.InterestRateMode(params.interestRateModes[vars.i]) ==
DataTypes.InterestRateMode.NONE
? vars.currentAmount.percentMul(vars.flashloanPremiumTotal)
: 0;
IAToken(reservesData[params.assets[vars.i]].aTokenAddress).transferUnderlyingTo(
params.receiverAddress,
vars.currentAmount
);
}
require(
vars.receiver.executeOperation(
params.assets,
params.amounts,
vars.totalPremiums,
msg.sender,
params.params
),
Errors.INVALID_FLASHLOAN_EXECUTOR_RETURN
);
for (vars.i = 0; vars.i < params.assets.length; vars.i++) {
vars.currentAsset = params.assets[vars.i];
vars.currentAmount = params.amounts[vars.i];
if (
DataTypes.InterestRateMode(params.interestRateModes[vars.i]) ==
DataTypes.InterestRateMode.NONE
) {
_handleFlashLoanRepayment(
reservesData[vars.currentAsset],
DataTypes.FlashLoanRepaymentParams({
asset: vars.currentAsset,
receiverAddress: params.receiverAddress,
amount: vars.currentAmount,
totalPremium: vars.totalPremiums[vars.i],
flashLoanPremiumToProtocol: vars.flashloanPremiumToProtocol,
referralCode: params.referralCode
})
);
} else {
// If the user chose to not return the funds, the system checks if there is enough collateral and
// eventually opens a debt position
BorrowLogic.executeBorrow(
reservesData,
reservesList,
eModeCategories,
userConfig,
DataTypes.ExecuteBorrowParams({
asset: vars.currentAsset,
user: msg.sender,
onBehalfOf: params.onBehalfOf,
amount: vars.currentAmount,
interestRateMode: DataTypes.InterestRateMode(params.interestRateModes[vars.i]),
referralCode: params.referralCode,
releaseUnderlying: false,
maxStableRateBorrowSizePercent: params.maxStableRateBorrowSizePercent,
reservesCount: params.reservesCount,
oracle: IPoolAddressesProvider(params.addressesProvider).getPriceOracle(),
userEModeCategory: params.userEModeCategory,
priceOracleSentinel: IPoolAddressesProvider(params.addressesProvider)
.getPriceOracleSentinel()
})
);
// no premium is paid when taking on the flashloan as debt
emit FlashLoan(
params.receiverAddress,
msg.sender,
vars.currentAsset,
vars.currentAmount,
DataTypes.InterestRateMode(params.interestRateModes[vars.i]),
0,
params.referralCode
);
}
}
}
/**
* @notice Implements the simple flashloan feature that allow users to access liquidity of ONE reserve for one
* transaction as long as the amount taken plus fee is returned.
* @dev Does not waive fee for approved flashborrowers nor allow taking on debt instead of repaying to save gas
* @dev At the end of the transaction the pool will pull amount borrowed + fee from the receiver,
* if the receiver have not approved the pool the transaction will revert.
* @dev Emits the `FlashLoan()` event
* @param reserve The state of the flashloaned reserve
* @param params The additional parameters needed to execute the simple flashloan function
*/
function executeFlashLoanSimple(
DataTypes.ReserveData storage reserve,
DataTypes.FlashloanSimpleParams memory params
) external {
// The usual action flow (cache -> updateState -> validation -> changeState -> updateRates)
// is altered to (validation -> user payload -> cache -> updateState -> changeState -> updateRates) for flashloans.
// This is done to protect against reentrance and rate manipulation within the user specified payload.
ValidationLogic.validateFlashloanSimple(reserve);
IFlashLoanSimpleReceiver receiver = IFlashLoanSimpleReceiver(params.receiverAddress);
uint256 totalPremium = params.amount.percentMul(params.flashLoanPremiumTotal);
IAToken(reserve.aTokenAddress).transferUnderlyingTo(params.receiverAddress, params.amount);
require(
receiver.executeOperation(
params.asset,
params.amount,
totalPremium,
msg.sender,
params.params
),
Errors.INVALID_FLASHLOAN_EXECUTOR_RETURN
);
_handleFlashLoanRepayment(
reserve,
DataTypes.FlashLoanRepaymentParams({
asset: params.asset,
receiverAddress: params.receiverAddress,
amount: params.amount,
totalPremium: totalPremium,
flashLoanPremiumToProtocol: params.flashLoanPremiumToProtocol,
referralCode: params.referralCode
})
);
}
/**
* @notice Handles repayment of flashloaned assets + premium
* @dev Will pull the amount + premium from the receiver, so must have approved pool
* @param reserve The state of the flashloaned reserve
* @param params The additional parameters needed to execute the repayment function
*/
function _handleFlashLoanRepayment(
DataTypes.ReserveData storage reserve,
DataTypes.FlashLoanRepaymentParams memory params
) internal {
uint256 premiumToProtocol = params.totalPremium.percentMul(params.flashLoanPremiumToProtocol);
uint256 premiumToLP = params.totalPremium - premiumToProtocol;
uint256 amountPlusPremium = params.amount + params.totalPremium;
DataTypes.ReserveCache memory reserveCache = reserve.cache();
reserve.updateState(reserveCache);
reserveCache.nextLiquidityIndex = reserve.cumulateToLiquidityIndex(
IERC20(reserveCache.aTokenAddress).totalSupply() +
uint256(reserve.accruedToTreasury).rayMul(reserveCache.nextLiquidityIndex),
premiumToLP
);
reserve.accruedToTreasury += premiumToProtocol
.rayDiv(reserveCache.nextLiquidityIndex)
.toUint128();
reserve.updateInterestRates(reserveCache, params.asset, amountPlusPremium, 0);
IERC20(params.asset).safeTransferFrom(
params.receiverAddress,
reserveCache.aTokenAddress,
amountPlusPremium
);
IAToken(reserveCache.aTokenAddress).handleRepayment(
params.receiverAddress,
params.receiverAddress,
amountPlusPremium
);
emit FlashLoan(
params.receiverAddress,
msg.sender,
params.asset,
params.amount,
DataTypes.InterestRateMode(0),
params.totalPremium,
params.referralCode
);
}
}