-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathRoutineInvokerLibV1.sol
More file actions
280 lines (232 loc) · 8.53 KB
/
RoutineInvokerLibV1.sol
File metadata and controls
280 lines (232 loc) · 8.53 KB
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
// Neptune Mutual Protocol (https://neptunemutual.com)
// SPDX-License-Identifier: BUSL-1.1
/* solhint-disable ordering */
pragma solidity ^0.8.0;
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IStore.sol";
import "../interfaces/ILendingStrategy.sol";
import "./PriceLibV1.sol";
import "./CoverUtilV1.sol";
library RoutineInvokerLibV1 {
using CoverUtilV1 for IStore;
using PriceLibV1 for IStore;
using ProtoUtilV1 for IStore;
using RegistryLibV1 for IStore;
using StoreKeyUtil for IStore;
using StrategyLibV1 for IStore;
enum Action {
Deposit,
Withdraw
}
function updateStateAndLiquidityInternal(IStore s, bytes32 coverKey) external {
_invoke(s, coverKey);
}
function _invoke(IStore s, bytes32 coverKey) private {
// solhint-disable-next-line
if (s.getLastUpdatedOnInternal(coverKey) + _getUpdateInterval(s) > block.timestamp) {
return;
}
PriceLibV1.setNpmPrice(s);
if (coverKey > 0) {
_updateWithdrawalPeriod(s, coverKey);
_invokeAssetManagement(s, coverKey);
s.setLastUpdatedOnInternal(coverKey);
}
}
function _getUpdateInterval(IStore s) private view returns (uint256) {
return s.getUintByKey(ProtoUtilV1.NS_LIQUIDITY_STATE_UPDATE_INTERVAL);
}
function getWithdrawalInfoInternal(IStore s, bytes32 coverKey)
public
view
returns (
bool isWithdrawalPeriod,
uint256 lendingPeriod,
uint256 withdrawalWindow,
uint256 start,
uint256 end
)
{
(lendingPeriod, withdrawalWindow) = s.getRiskPoolingPeriodsInternal(coverKey);
// Get the withdrawal period of this cover liquidity
start = s.getUintByKey(getNextWithdrawalStartKeyInternal(coverKey));
end = s.getUintByKey(getNextWithdrawalEndKeyInternal(coverKey));
// solhint-disable-next-line
if (block.timestamp >= start && block.timestamp <= end) {
isWithdrawalPeriod = true;
}
}
function _isWithdrawalPeriod(IStore s, bytes32 coverKey) private view returns (bool) {
(bool isWithdrawalPeriod, , , , ) = getWithdrawalInfoInternal(s, coverKey);
return isWithdrawalPeriod;
}
function _updateWithdrawalPeriod(IStore s, bytes32 coverKey) private {
(, uint256 lendingPeriod, uint256 withdrawalWindow, uint256 start, uint256 end) = getWithdrawalInfoInternal(s, coverKey);
// Without a lending period and withdrawal window, nothing can be updated
if (lendingPeriod == 0 || withdrawalWindow == 0) {
return;
}
// The withdrawal period is now over.
// Deposits can be performed again.
// Set the next withdrawal cycle
if (block.timestamp > end) {
// solhint-disable-previous-line
// Next Withdrawal Cycle
// Withdrawals can start after the lending period
start = block.timestamp + lendingPeriod; // solhint-disable
// Withdrawals can be performed until the end of the next withdrawal cycle
end = start + withdrawalWindow;
s.setUintByKey(getNextWithdrawalStartKeyInternal(coverKey), start);
s.setUintByKey(getNextWithdrawalEndKeyInternal(coverKey), end);
setAccrualCompleteInternal(s, coverKey, false);
}
}
function isAccrualCompleteInternal(IStore s, bytes32 coverKey) external view returns (bool) {
return s.getBoolByKey(getAccrualInvocationKeyInternal(coverKey));
}
function setAccrualCompleteInternal(
IStore s,
bytes32 coverKey,
bool flag
) public {
s.setBoolByKey(getAccrualInvocationKeyInternal(coverKey), flag);
}
/**
* @dev Hash key of the "accrual invocation status" for the given cover.
*
* Warning: this function does not validate the cover key supplied.
*
* @param coverKey Enter cover key
*
*/
function getAccrualInvocationKeyInternal(bytes32 coverKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(ProtoUtilV1.NS_ACCRUAL_INVOCATION, coverKey));
}
/**
* @dev Hash key of the "next withdrawal start date" for the given cover.
*
* Warning: this function does not validate the cover key supplied.
*
* @param coverKey Enter cover key
*
*/
function getNextWithdrawalStartKeyInternal(bytes32 coverKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(ProtoUtilV1.NS_LENDING_STRATEGY_WITHDRAWAL_START, coverKey));
}
/**
* @dev Hash key of the "next withdrawal end date" for the given cover.
*
* Warning: this function does not validate the cover key supplied.
*
* @param coverKey Enter cover key
*
*/
function getNextWithdrawalEndKeyInternal(bytes32 coverKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(ProtoUtilV1.NS_LENDING_STRATEGY_WITHDRAWAL_END, coverKey));
}
function mustBeDuringWithdrawalPeriod(IStore s, bytes32 coverKey) external view {
// Get the withdrawal period of this cover liquidity
uint256 start = s.getUintByKey(getNextWithdrawalStartKeyInternal(coverKey));
uint256 end = s.getUintByKey(getNextWithdrawalEndKeyInternal(coverKey));
require(start > 0 && block.timestamp >= start, "Withdrawal period has not started");
require(end > 0 && block.timestamp <= end, "Withdrawal period has already ended");
}
function _executeAndGetAction(
IStore s,
ILendingStrategy,
bytes32 coverKey
) private returns (Action) {
// If the cover is undergoing reporting, withdraw everything
bool isNormal = s.isCoverNormalInternal(coverKey);
if (isNormal != true) {
// Reset the withdrawal window
s.setUintByKey(getNextWithdrawalStartKeyInternal(coverKey), 0);
s.setUintByKey(getNextWithdrawalEndKeyInternal(coverKey), 0);
return Action.Withdraw;
}
if (_isWithdrawalPeriod(s, coverKey) == true) {
return Action.Withdraw;
}
return Action.Deposit;
}
function _canDeposit(
IStore s,
ILendingStrategy strategy,
uint256 totalStrategies,
bytes32 coverKey
) private view returns (uint256) {
IERC20 stablecoin = IERC20(s.getStablecoinAddressInternal());
uint256 totalBalance = s.getStablecoinOwnedByVaultInternal(coverKey);
uint256 maximumAllowed = (totalBalance * s.getMaxLendingRatioInternal()) / ProtoUtilV1.MULTIPLIER;
uint256 allocation = maximumAllowed / totalStrategies;
uint256 weight = strategy.getWeight();
uint256 canDeposit = (allocation * weight) / ProtoUtilV1.MULTIPLIER;
uint256 alreadyDeposited = s.getAmountInStrategyInternal(coverKey, strategy.getName(), address(stablecoin));
if (alreadyDeposited >= canDeposit) {
return 0;
}
return canDeposit - alreadyDeposited;
}
function _invokeAssetManagement(IStore s, bytes32 coverKey) private {
address vault = s.getVaultAddress(coverKey);
_withdrawFromDisabled(s, coverKey, vault);
address[] memory strategies = s.getActiveStrategiesInternal();
for (uint256 i = 0; i < strategies.length; i++) {
ILendingStrategy strategy = ILendingStrategy(strategies[i]);
_executeStrategy(s, strategy, strategies.length, vault, coverKey);
}
}
function _executeStrategy(
IStore s,
ILendingStrategy strategy,
uint256 totalStrategies,
address vault,
bytes32 coverKey
) private {
uint256 canDeposit = _canDeposit(s, strategy, totalStrategies, coverKey);
uint256 balance = IERC20(s.getStablecoinAddressInternal()).balanceOf(vault);
if (canDeposit > balance) {
canDeposit = balance;
}
Action action = _executeAndGetAction(s, strategy, coverKey);
if (action == Action.Deposit && canDeposit == 0) {
return;
}
if (action == Action.Withdraw) {
_withdrawAllFromStrategy(strategy, vault, coverKey);
return;
}
_depositToStrategy(strategy, coverKey, canDeposit);
}
function _depositToStrategy(
ILendingStrategy strategy,
bytes32 coverKey,
uint256 amount
) private {
strategy.deposit(coverKey, amount);
}
function _withdrawAllFromStrategy(
ILendingStrategy strategy,
address vault,
bytes32 coverKey
) private returns (uint256 stablecoinWithdrawn) {
uint256 balance = IERC20(strategy.getDepositCertificate()).balanceOf(vault);
if (balance > 0) {
stablecoinWithdrawn = strategy.withdraw(coverKey);
}
}
function _withdrawFromDisabled(
IStore s,
bytes32 coverKey,
address onBehalfOf
) private {
address[] memory strategies = s.getDisabledStrategiesInternal();
for (uint256 i = 0; i < strategies.length; i++) {
ILendingStrategy strategy = ILendingStrategy(strategies[i]);
uint256 balance = IERC20(strategy.getDepositCertificate()).balanceOf(onBehalfOf);
if (balance > 0) {
strategy.withdraw(coverKey);
}
}
}
}