This repository has been archived by the owner on Mar 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LMPDebt.sol
451 lines (388 loc) · 19.9 KB
/
LMPDebt.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2023 Tokemak Foundation. All rights reserved.
pragma solidity 0.8.17;
import { Errors } from "src/utils/Errors.sol";
import { IDestinationVault } from "src/interfaces/vault/IDestinationVault.sol";
import { Math } from "openzeppelin-contracts/utils/math/Math.sol";
import { EnumerableSet } from "openzeppelin-contracts/utils/structs/EnumerableSet.sol";
import { IStrategy } from "src/interfaces/strategy/IStrategy.sol";
import { SafeERC20 } from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata as IERC20 } from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ISystemRegistry, IDestinationVaultRegistry } from "src/interfaces/ISystemRegistry.sol";
import { IERC3156FlashBorrower } from "openzeppelin-contracts/interfaces/IERC3156FlashBorrower.sol";
import { LMPStrategy } from "src/strategy/LMPStrategy.sol";
library LMPDebt {
using Math for uint256;
using SafeERC20 for IERC20;
error VaultShutdown();
error WithdrawShareCalcInvalid(uint256 currentShares, uint256 cachedShares);
error RebalanceDestinationsMatch(address destinationVault);
error RebalanceFailed(string message);
struct DestinationInfo {
/// @notice Current underlying and reward value at the destination vault
/// @dev Used for calculating totalDebt of the LMPVault
uint256 currentDebt;
/// @notice Last block timestamp this info was updated
uint256 lastReport;
/// @notice How many shares of the destination vault we owned at last report
uint256 ownedShares;
/// @notice Amount of baseAsset transferred out in service of deployments
/// @dev Used for calculating 'in profit' or not during user withdrawals
uint256 debtBasis;
}
struct RebalanceOutParams {
/// Address that will received the withdrawn underlyer
address receiver;
/// The "out" destination vault
address destinationOut;
/// The amount of tokenOut that will be withdrawn
uint256 amountOut;
/// The underlyer for destinationOut
address tokenOut;
IERC20 _baseAsset;
bool _shutdown;
}
/// @dev In memory struct only for managing vars in rebalances
struct IdleDebtChange {
uint256 debtDecrease;
uint256 debtIncrease;
uint256 idleDecrease;
uint256 idleIncrease;
}
struct FlashRebalanceParams {
uint256 totalIdle;
uint256 totalDebt;
IERC20 baseAsset;
bool shutdown;
}
function rebalance(
DestinationInfo storage destInfoOut,
DestinationInfo storage destInfoIn,
IStrategy.RebalanceParams memory params,
IERC20 baseAsset,
bool shutdown,
uint256 totalIdle,
uint256 totalDebt
) external returns (uint256 idle, uint256 debt) {
LMPDebt.IdleDebtChange memory idleDebtChange;
// make sure there's something to do
if (params.amountIn == 0 && params.amountOut == 0) {
revert Errors.InvalidParams();
}
if (params.destinationIn == params.destinationOut) {
revert RebalanceDestinationsMatch(params.destinationOut);
}
// make sure we have a valid path
{
(bool success, string memory message) = LMPStrategy.verifyRebalance(params);
if (!success) {
revert RebalanceFailed(message);
}
}
// Handle decrease (shares going "Out", cashing in shares and sending underlying back to swapper)
// If the tokenOut is _asset we assume they are taking idle
// which is already in the contract
idleDebtChange = _handleRebalanceOut(
LMPDebt.RebalanceOutParams({
receiver: msg.sender,
destinationOut: params.destinationOut,
amountOut: params.amountOut,
tokenOut: params.tokenOut,
_baseAsset: baseAsset,
_shutdown: shutdown
}),
destInfoOut
);
// Handle increase (shares coming "In", getting underlying from the swapper and trading for new shares)
if (params.amountIn > 0) {
// transfer dv underlying lp from swapper to here
IERC20(params.tokenIn).safeTransferFrom(msg.sender, address(this), params.amountIn);
// deposit to dv (already checked in `verifyRebalance` so no need to check return of deposit)
if (params.tokenIn != address(baseAsset)) {
IDestinationVault dvIn = IDestinationVault(params.destinationIn);
(uint256 debtDecreaseIn, uint256 debtIncreaseIn) =
_handleRebalanceIn(destInfoIn, dvIn, params.tokenIn, params.amountIn);
idleDebtChange.debtDecrease += debtDecreaseIn;
idleDebtChange.debtIncrease += debtIncreaseIn;
} else {
idleDebtChange.idleIncrease += params.amountIn;
}
}
{
idle = totalIdle;
debt = totalDebt;
if (idleDebtChange.idleDecrease > 0 || idleDebtChange.idleIncrease > 0) {
idle = idle + idleDebtChange.idleIncrease - idleDebtChange.idleDecrease;
}
if (idleDebtChange.debtDecrease > 0 || idleDebtChange.debtIncrease > 0) {
debt = debt + idleDebtChange.debtIncrease - idleDebtChange.debtDecrease;
}
}
}
function flashRebalance(
DestinationInfo storage destInfoOut,
DestinationInfo storage destInfoIn,
IERC3156FlashBorrower receiver,
IStrategy.RebalanceParams memory params,
FlashRebalanceParams memory flashParams,
bytes calldata data
) external returns (uint256 idle, uint256 debt) {
LMPDebt.IdleDebtChange memory idleDebtChange;
// make sure there's something to do
if (params.amountIn == 0 && params.amountOut == 0) {
revert Errors.InvalidParams();
}
if (params.destinationIn == params.destinationOut) {
revert RebalanceDestinationsMatch(params.destinationOut);
}
// make sure we have a valid path
{
(bool success, string memory message) = LMPStrategy.verifyRebalance(params);
if (!success) {
revert RebalanceFailed(message);
}
}
// Handle decrease (shares going "Out", cashing in shares and sending underlying back to swapper)
// If the tokenOut is _asset we assume they are taking idle
// which is already in the contract
idleDebtChange = _handleRebalanceOut(
LMPDebt.RebalanceOutParams({
receiver: address(receiver),
destinationOut: params.destinationOut,
amountOut: params.amountOut,
tokenOut: params.tokenOut,
_baseAsset: flashParams.baseAsset,
_shutdown: flashParams.shutdown
}),
destInfoOut
);
// Handle increase (shares coming "In", getting underlying from the swapper and trading for new shares)
if (params.amountIn > 0) {
IDestinationVault dvIn = IDestinationVault(params.destinationIn);
// get "before" counts
uint256 tokenInBalanceBefore = IERC20(params.tokenIn).balanceOf(address(this));
// Give control back to the solver so they can make use of the "out" assets
// and get our "in" asset
bytes32 flashResult = receiver.onFlashLoan(msg.sender, params.tokenIn, params.amountIn, 0, data);
// We assume the solver will send us the assets
uint256 tokenInBalanceAfter = IERC20(params.tokenIn).balanceOf(address(this));
// Make sure the call was successful and verify we have at least the assets we think
// we were getting
if (
flashResult != keccak256("ERC3156FlashBorrower.onFlashLoan")
|| tokenInBalanceAfter < tokenInBalanceBefore + params.amountIn
) {
revert Errors.FlashLoanFailed(params.tokenIn, params.amountIn);
}
if (params.tokenIn != address(flashParams.baseAsset)) {
(uint256 debtDecreaseIn, uint256 debtIncreaseIn) =
_handleRebalanceIn(destInfoIn, dvIn, params.tokenIn, tokenInBalanceAfter);
idleDebtChange.debtDecrease += debtDecreaseIn;
idleDebtChange.debtIncrease += debtIncreaseIn;
} else {
idleDebtChange.idleIncrease += tokenInBalanceAfter - tokenInBalanceBefore;
}
}
{
idle = flashParams.totalIdle;
debt = flashParams.totalDebt;
if (idleDebtChange.idleDecrease > 0 || idleDebtChange.idleIncrease > 0) {
idle = idle + idleDebtChange.idleIncrease - idleDebtChange.idleDecrease;
}
if (idleDebtChange.debtDecrease > 0 || idleDebtChange.debtIncrease > 0) {
debt = debt + idleDebtChange.debtIncrease - idleDebtChange.debtDecrease;
}
}
}
function _calcUserWithdrawSharesToBurn(
DestinationInfo storage destInfo,
IDestinationVault destVault,
uint256 userShares,
uint256 maxAssetsToPull,
uint256 totalVaultShares
) external returns (uint256 sharesToBurn, uint256 totalDebtBurn) {
// Figure out how many shares we can burn from the destination as well
// as what our totalDebt deduction should be (totalDebt being a cached value).
// If the destination vault is currently sitting at a profit, then the user can burn
// all the shares this vault owns. If its at a loss, they can only burn an amount
// proportional to their ownership of this vault. This is so a user doesn't lock in
// a loss for the entire vault during their withdrawal
uint256 currentDvShares = destVault.balanceOf(address(this));
// slither-disable-next-line incorrect-equality
if (currentDvShares == 0) {
return (0, 0);
}
// Calculate the current value of our shares
uint256 currentDvDebtValue = destVault.debtValue(currentDvShares);
// Get the basis for the current deployment
uint256 cachedDebtBasis = destInfo.debtBasis;
// The amount of shares we had at the last debt reporting
uint256 cachedDvShares = destInfo.ownedShares;
// The value of our debt + earned rewards at last debt reporting
uint256 cachedCurrentDebt = destInfo.currentDebt;
// Our current share balance should only ever be lte the last snapshot
// Any update to the deployment should update the snapshot and withdrawals
// can only lower it
if (currentDvShares > cachedDvShares) {
revert WithdrawShareCalcInvalid(currentDvShares, cachedDvShares);
}
// Recalculated what the debtBasis is with the current number of shares
uint256 updatedDebtBasis = cachedDebtBasis.mulDiv(currentDvShares, cachedDvShares, Math.Rounding.Up);
// Neither of these numbers include rewards from the DV
if (currentDvDebtValue < updatedDebtBasis) {
// We are currently sitting at a loss. Limit the value we can pull from
// the destination vault
currentDvDebtValue = currentDvDebtValue.mulDiv(userShares, totalVaultShares, Math.Rounding.Down);
currentDvShares = currentDvShares.mulDiv(userShares, totalVaultShares, Math.Rounding.Down);
}
// Shouldn't pull more than we want
// Or, we're not in profit so we limit the pull
if (currentDvDebtValue < maxAssetsToPull) {
maxAssetsToPull = currentDvDebtValue;
}
// Calculate the portion of shares to burn based on the assets we need to pull
// and the current total debt value. These are destination vault shares.
sharesToBurn = currentDvShares.mulDiv(maxAssetsToPull, currentDvDebtValue, Math.Rounding.Up);
// This is what will be deducted from totalDebt with the withdrawal. The totalDebt number
// is calculated based on the cached values so we need to be sure to reduce it
// proportional to the original cached debt value
totalDebtBurn = cachedCurrentDebt.mulDiv(sharesToBurn, cachedDvShares, Math.Rounding.Up);
}
/// @notice Perform deposit and debt info update for the "in" destination during a rebalance
/// @dev This "in" function performs less validations than its "out" version
/// @param dvIn The "in" destination vault
/// @param tokenIn The underlyer for dvIn
/// @param depositAmount The amount of tokenIn that will be deposited
/// @return debtDecrease The previous amount of debt dvIn accounted for in totalDebt
/// @return debtIncrease The current amount of debt dvIn should account for in totalDebt
function handleRebalanceIn(
DestinationInfo storage destInfo,
IDestinationVault dvIn,
address tokenIn,
uint256 depositAmount
) external returns (uint256 debtDecrease, uint256 debtIncrease) {
(debtDecrease, debtIncrease) = _handleRebalanceIn(destInfo, dvIn, tokenIn, depositAmount);
}
/// @notice Perform deposit and debt info update for the "in" destination during a rebalance
/// @dev This "in" function performs less validations than its "out" version
/// @param dvIn The "in" destination vault
/// @param tokenIn The underlyer for dvIn
/// @param depositAmount The amount of tokenIn that will be deposited
/// @return debtDecrease The previous amount of debt dvIn accounted for in totalDebt
/// @return debtIncrease The current amount of debt dvIn should account for in totalDebt
function _handleRebalanceIn(
DestinationInfo storage destInfo,
IDestinationVault dvIn,
address tokenIn,
uint256 depositAmount
) private returns (uint256 debtDecrease, uint256 debtIncrease) {
IERC20(tokenIn).safeApprove(address(dvIn), depositAmount);
// Snapshot our current shares so we know how much to back out
uint256 originalShareBal = dvIn.balanceOf(address(this));
// deposit to dv
uint256 newShares = dvIn.depositUnderlying(depositAmount);
// Update the debt info snapshot
(debtDecrease, debtIncrease) =
_recalculateDestInfo(destInfo, dvIn, originalShareBal, originalShareBal + newShares, true);
}
/**
* @notice Perform withdraw and debt info update for the "out" destination during a rebalance
* @dev This "out" function performs more validations and handles idle as opposed to "in" which does not
* debtDecrease The previous amount of debt destinationOut accounted for in totalDebt
* debtIncrease The current amount of debt destinationOut should account for in totalDebt
* idleDecrease Amount of baseAsset that was sent from the vault. > 0 only when tokenOut == baseAsset
* idleIncrease Amount of baseAsset that was claimed from Destination Vault
* @param params Rebalance out params
* @param destOutInfo The "out" destination vault info
* @return assetChange debt and idle change data
*/
function handleRebalanceOut(
RebalanceOutParams memory params,
DestinationInfo storage destOutInfo
) external returns (IdleDebtChange memory assetChange) {
(assetChange) = _handleRebalanceOut(params, destOutInfo);
}
/**
* @notice Perform withdraw and debt info update for the "out" destination during a rebalance
* @dev This "out" function performs more validations and handles idle as opposed to "in" which does not
* debtDecrease The previous amount of debt destinationOut accounted for in totalDebt
* debtIncrease The current amount of debt destinationOut should account for in totalDebt
* idleDecrease Amount of baseAsset that was sent from the vault. > 0 only when tokenOut == baseAsset
* idleIncrease Amount of baseAsset that was claimed from Destination Vault
* @param params Rebalance out params
* @param destOutInfo The "out" destination vault info
* @return assetChange debt and idle change data
*/
function _handleRebalanceOut(
RebalanceOutParams memory params,
DestinationInfo storage destOutInfo
) private returns (IdleDebtChange memory assetChange) {
// Handle decrease (shares going "Out", cashing in shares and sending underlying back to swapper)
// If the tokenOut is _asset we assume they are taking idle
// which is already in the contract
if (params.amountOut > 0) {
if (params.tokenOut != address(params._baseAsset)) {
IDestinationVault dvOut = IDestinationVault(params.destinationOut);
// Snapshot our current shares so we know how much to back out
uint256 originalShareBal = dvOut.balanceOf(address(this));
// Burning our shares will claim any pending baseAsset
// rewards and send them to us. Make sure we capture them
// so they can end up in idle
uint256 beforeBaseAssetBal = params._baseAsset.balanceOf(address(this));
// withdraw underlying from dv
// slither-disable-next-line unused-return
dvOut.withdrawUnderlying(params.amountOut, params.receiver);
assetChange.idleIncrease = params._baseAsset.balanceOf(address(this)) - beforeBaseAssetBal;
// Update the debt info snapshot
(assetChange.debtDecrease, assetChange.debtIncrease) = _recalculateDestInfo(
destOutInfo, dvOut, originalShareBal, originalShareBal - params.amountOut, true
);
} else {
// If we are shutdown then the only operations we should be performing are those that get
// the base asset back to the vault. We shouldn't be sending out more
if (params._shutdown) {
revert VaultShutdown();
}
// Working with idle baseAsset which should be in the vault already
// Just send it out
IERC20(params.tokenOut).safeTransfer(params.receiver, params.amountOut);
assetChange.idleDecrease = params.amountOut;
}
}
}
function recalculateDestInfo(
DestinationInfo storage destInfo,
IDestinationVault destVault,
uint256 originalShares,
uint256 currentShares,
bool resetDebtBasis
) external returns (uint256 totalDebtDecrease, uint256 totalDebtIncrease) {
(totalDebtDecrease, totalDebtIncrease) =
_recalculateDestInfo(destInfo, destVault, originalShares, currentShares, resetDebtBasis);
}
function _recalculateDestInfo(
DestinationInfo storage destInfo,
IDestinationVault destVault,
uint256 originalShares,
uint256 currentShares,
bool resetDebtBasis
) private returns (uint256 totalDebtDecrease, uint256 totalDebtIncrease) {
// Figure out what to back out of our totalDebt number.
// We could have had withdraws since the last snapshot which means our
// cached currentDebt number should be decreased based on the remaining shares
// totalDebt is decreased using the same proportion of shares method during withdrawals
// so this should represent whatever is remaining.
// Figure out how much our debt is currently worth
uint256 dvDebtValue = destVault.debtValue(currentShares);
// Calculate what we're backing out based on the original shares
uint256 currentDebt = (destInfo.currentDebt * originalShares) / Math.max(destInfo.ownedShares, 1);
destInfo.currentDebt = dvDebtValue;
destInfo.lastReport = block.timestamp;
destInfo.ownedShares = currentShares;
if (resetDebtBasis) {
destInfo.debtBasis = dvDebtValue;
}
totalDebtDecrease = currentDebt;
totalDebtIncrease = dvDebtValue;
}
}