This repository has been archived by the owner on May 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FlashLiquidatorBase.sol
349 lines (285 loc) · 11.8 KB
/
FlashLiquidatorBase.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.17;
import {NotionalProxy} from "../../interfaces/notional/NotionalProxy.sol";
import {IStrategyVault} from "../../interfaces/notional/IStrategyVault.sol";
import {WETH9} from "../../interfaces/WETH9.sol";
import {TokenUtils, IERC20} from "../utils/TokenUtils.sol";
import {Constants} from "../global/Constants.sol";
import {
Token,
VaultAccount,
BatchLend,
BalanceActionWithTrades,
TradeActionType,
DepositActionType
} from "../global/Types.sol";
import {BoringOwnable} from "./BoringOwnable.sol";
import {Deployments} from "../global/Deployments.sol";
abstract contract FlashLiquidatorBase is BoringOwnable {
using TokenUtils for IERC20;
uint256 internal constant MAX_CURRENCIES = 3;
NotionalProxy public immutable NOTIONAL;
address public immutable FLASH_LENDER;
enum LiquidationType {
UNKNOWN,
DELEVERAGE_VAULT_ACCOUNT,
LIQUIDATE_CASH_BALANCE
}
struct LiquidationParams {
LiquidationType liquidationType;
uint16 currencyId;
uint16 currencyIndex;
address account;
address vault;
bytes actionData;
}
struct DeleverageVaultAccountParams {
bool useVaultDeleverage;
bytes redeemData;
}
struct LiquidateCashBalanceParams {
uint32 minLendRate;
}
error ErrInvalidCurrencyIndex(uint16 index);
constructor(NotionalProxy notional_, address flashLender_) {
// Make sure we are using the correct Deployments lib
uint256 chainId = 42161;
// assembly { chainId := chainid() }
require(Deployments.CHAIN_ID == chainId);
NOTIONAL = notional_;
FLASH_LENDER = flashLender_;
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
function enableCurrencies(uint16[] calldata currencies) external onlyOwner {
for (uint256 i; i < currencies.length; i++) {
(/* Token memory assetToken */, Token memory underlyingToken) = NOTIONAL.getCurrency(currencies[i]);
if (underlyingToken.tokenAddress == Constants.ETH_ADDRESS) {
IERC20(address(Deployments.WETH)).checkApprove(address(FLASH_LENDER), type(uint256).max);
} else {
IERC20(underlyingToken.tokenAddress).checkApprove(address(FLASH_LENDER), type(uint256).max);
IERC20(underlyingToken.tokenAddress).checkApprove(address(NOTIONAL), type(uint256).max);
}
}
}
/// NOTE: use .call from liquidation bot
function getOptimalDeleveragingParams(
address account, address vault
) external returns (uint16 currencyIndex, int256 maxUnderying) {
_settleAccountIfNeeded(account, vault);
return _getOptimalDeleveragingParams(account, vault);
}
function _settleAccountIfNeeded(address account, address vault) private returns (VaultAccount memory) {
VaultAccount memory vaultAccount = NOTIONAL.getVaultAccount(account, vault);
if (vaultAccount.maturity < block.timestamp) {
NOTIONAL.settleVaultAccount(account, vault);
}
return vaultAccount;
}
function _getOptimalDeleveragingParams(
address account, address vault
) private view returns (uint16 currencyIndex, int256 maxUnderlying) {
(
/* VaultAccountHealthFactors memory h */,
int256[3] memory maxLiquidatorDepositUnderlying,
uint256[3] memory vaultSharesToLiquidator
) = NOTIONAL.getVaultAccountHealthFactors(account, vault);
currencyIndex = vaultSharesToLiquidator[0] < vaultSharesToLiquidator[1] ?
(vaultSharesToLiquidator[1] < vaultSharesToLiquidator[2] ? 2 : 1) :
(vaultSharesToLiquidator[0] < vaultSharesToLiquidator[2] ? 2 : 0);
maxUnderlying = maxLiquidatorDepositUnderlying[currencyIndex];
}
function estimateProfit(
address asset,
uint256 amount,
LiquidationParams calldata params
) external onlyOwner returns (uint256) {
uint256 balance = IERC20(asset).balanceOf(address(this));
_flashLiquidate(asset, amount, false, params);
return IERC20(asset).balanceOf(address(this)) - balance;
}
function flashLiquidate(
address asset,
uint256 amount,
LiquidationParams calldata params
) external {
_flashLiquidate(asset, amount, true, params);
}
function _flashLiquidate(
address asset,
uint256 amount,
bool withdraw,
LiquidationParams calldata params
) internal virtual;
function _deleverageVaultAccount(LiquidationParams memory params) private {
(uint16 currencyIndex, int256 maxUnderlying) = _getOptimalDeleveragingParams(params.account, params.vault);
require(maxUnderlying > 0);
DeleverageVaultAccountParams memory actionParams = abi.decode(params.actionData, (DeleverageVaultAccountParams));
uint256 vaultSharesFromLiquidation;
if (actionParams.useVaultDeleverage) {
(
vaultSharesFromLiquidation, /* */
) = IStrategyVault(params.vault).deleverageAccount{value: address(this).balance}(
params.account,
params.vault,
address(this),
currencyIndex,
maxUnderlying
);
} else {
(
vaultSharesFromLiquidation, /* */
) = NOTIONAL.deleverageAccount{value: address(this).balance}(
params.account,
params.vault,
address(this),
currencyIndex,
maxUnderlying
);
}
if (0 < vaultSharesFromLiquidation) {
NOTIONAL.exitVault(
address(this),
params.vault,
address(this),
vaultSharesFromLiquidation,
0,
0,
actionParams.redeemData
);
}
}
function _liquidateCashBalance(VaultAccount memory vaultAccount, LiquidationParams memory params) private {
LiquidateCashBalanceParams memory actionParams = abi.decode(params.actionData, (LiquidateCashBalanceParams));
require(vaultAccount.maturity != Constants.PRIME_CASH_VAULT_MATURITY);
int256 cashBalance;
if (params.currencyIndex == 0) {
cashBalance = vaultAccount.tempCashBalance;
} else if (params.currencyIndex < MAX_CURRENCIES) {
(/* */, /* */, int256[2] memory accountSecondaryCashHeld) =
NOTIONAL.getVaultAccountSecondaryDebt(params.account, params.vault);
cashBalance = accountSecondaryCashHeld[params.currencyIndex - 1];
} else {
revert ErrInvalidCurrencyIndex(params.currencyIndex);
}
(int256 fCashDeposit, /* */) = NOTIONAL.getfCashRequiredToLiquidateCash(
params.currencyId, vaultAccount.maturity, cashBalance
);
uint256 fCashAmount = _lend(
params.currencyId, vaultAccount.maturity, uint256(fCashDeposit), actionParams.minLendRate
);
require(fCashAmount <= uint256(type(int256).max));
NOTIONAL.liquidateVaultCashBalance(
params.account,
params.vault,
address(this),
params.currencyIndex,
int256(fCashAmount)
);
// Sell residual fCash
int256 fCashResidual = NOTIONAL.getfCashNotional(address(this), params.currencyId, vaultAccount.maturity);
if (0 < fCashResidual) {
require(fCashResidual <= int256(type(int88).max));
_sellfCash(params.currencyId, vaultAccount.maturity, uint88(uint256(fCashResidual)));
} else {
_withdraw(params);
}
}
function handleLiquidation(uint256 fee, bool repay, bytes memory data) internal {
require(msg.sender == address(FLASH_LENDER));
(
address asset,
uint256 amount,
bool withdraw,
LiquidationParams memory params
) = abi.decode(data, (address, uint256, bool, LiquidationParams));
VaultAccount memory vaultAccount = _settleAccountIfNeeded(params.account, params.vault);
if (asset == address(Deployments.WETH)) {
_unwrapETH(amount);
}
if (params.liquidationType == LiquidationType.DELEVERAGE_VAULT_ACCOUNT) {
_deleverageVaultAccount(params);
} else if(params.liquidationType == LiquidationType.LIQUIDATE_CASH_BALANCE) {
_liquidateCashBalance(vaultAccount, params);
} else {
revert();
}
if (asset == address(Deployments.WETH)) {
_wrapETH();
}
if (withdraw) {
_withdrawToOwner(asset, IERC20(asset).balanceOf(address(this)) - amount - fee);
}
if (repay) {
IERC20(asset).transfer(msg.sender, amount + fee);
}
}
function _withdraw(LiquidationParams memory params) private {
(int256 cashBalance, /* */, /* */) = NOTIONAL.getAccountBalance(params.currencyId, address(this));
require(0 <= cashBalance && cashBalance <= int256(uint256(type(uint88).max)));
NOTIONAL.withdraw(params.currencyId, uint88(uint256(cashBalance)), true);
}
function _lend(uint16 currencyId, uint256 maturity, uint256 amount, uint32 minLendRate) private returns (uint256) {
(uint256 fCashAmount, /* */, bytes32 encodedTrade) = NOTIONAL.getfCashLendFromDeposit(
currencyId,
amount,
maturity,
minLendRate,
block.timestamp,
true // useUnderlying is true
);
BalanceActionWithTrades[] memory action = new BalanceActionWithTrades[](1);
action[0].actionType = DepositActionType.DepositUnderlying;
action[0].depositActionAmount = amount;
action[0].currencyId = currencyId;
action[0].withdrawEntireCashBalance = false;
action[0].redeemToUnderlying = false;
bytes32[] memory trades = new bytes32[](1);
trades[0] = encodedTrade;
action[0].trades = trades;
uint256 msgValue;
if (currencyId == Constants.ETH_CURRENCY_ID) {
msgValue = amount;
}
NOTIONAL.batchBalanceAndTradeAction{value: msgValue}(address(this), action);
return fCashAmount;
}
function _sellfCash(uint16 currencyId, uint256 maturity, uint88 amount) internal {
BalanceActionWithTrades[] memory action = new BalanceActionWithTrades[](1);
action[0].actionType = DepositActionType.None;
action[0].depositActionAmount = 0;
action[0].currencyId = currencyId;
action[0].withdrawEntireCashBalance = true;
action[0].redeemToUnderlying = true;
bytes32[] memory trades = new bytes32[](1);
uint256 marketIndex = NOTIONAL.getMarketIndex(currencyId, maturity);
trades[0] = bytes32(
(uint256(TradeActionType.Borrow) << 248) |
(marketIndex << 240) |
(uint256(amount) << 152)
);
action[0].trades = trades;
NOTIONAL.batchBalanceAndTradeAction(address(this), action);
}
function _withdrawToOwner(address token, uint256 amount) private {
if (amount == type(uint256).max) {
amount = IERC20(token).balanceOf(address(this));
}
if (amount > 0) {
IERC20(token).checkTransfer(owner, amount);
}
}
function _wrapETH() private {
Deployments.WETH.deposit{value: address(this).balance}();
}
function _unwrapETH(uint256 amount) private {
Deployments.WETH.withdraw(amount);
}
function withdrawToOwner(address token, uint256 amount) external onlyOwner {
_withdrawToOwner(token, amount);
}
function wrapETH() external onlyOwner {
_wrapETH();
}
receive() external payable {}
}