-
Notifications
You must be signed in to change notification settings - Fork 480
Expand file tree
/
Copy pathDurationVaultStrategy.sol
More file actions
421 lines (361 loc) · 18.3 KB
/
Copy pathDurationVaultStrategy.sol
File metadata and controls
421 lines (361 loc) · 18.3 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
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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
import "./StrategyBase.sol";
import "./DurationVaultStrategyStorage.sol";
import "../interfaces/IDurationVaultStrategy.sol";
import "../interfaces/IDelegationManager.sol";
import "../interfaces/IAllocationManager.sol";
import "../interfaces/IRewardsCoordinator.sol";
import "../interfaces/IStrategyFactory.sol";
import "../libraries/OperatorSetLib.sol";
/// @title Duration-bound EigenLayer vault strategy with configurable deposit caps and windows.
/// @author Layr Labs, Inc.
/// @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
contract DurationVaultStrategy is DurationVaultStrategyStorage, StrategyBase {
using OperatorSetLib for OperatorSet;
/// @notice Delegation manager reference used to register the vault as an operator.
IDelegationManager public immutable override delegationManager;
/// @notice Allocation manager reference used to register/allocate operator sets.
IAllocationManager public immutable override allocationManager;
/// @notice Rewards coordinator reference used to configure operator splits.
IRewardsCoordinator public immutable override rewardsCoordinator;
/// @notice Strategy factory reference used to check token blacklist status.
IStrategyFactory public immutable strategyFactory;
/// @dev Restricts function access to the vault administrator.
modifier onlyVaultAdmin() {
require(msg.sender == vaultAdmin, OnlyVaultAdmin());
_;
}
/// @dev Restricts function access to the vault arbitrator.
modifier onlyArbitrator() {
require(msg.sender == arbitrator, OnlyArbitrator());
_;
}
/// @param _strategyManager The StrategyManager contract.
/// @param _pauserRegistry The PauserRegistry contract.
/// @param _delegationManager The DelegationManager contract for operator registration.
/// @param _allocationManager The AllocationManager contract for operator set allocations.
/// @param _rewardsCoordinator The RewardsCoordinator contract for configuring splits.
/// @param _strategyFactory The StrategyFactory contract for token blacklist checks.
constructor(
IStrategyManager _strategyManager,
IPauserRegistry _pauserRegistry,
IDelegationManager _delegationManager,
IAllocationManager _allocationManager,
IRewardsCoordinator _rewardsCoordinator,
IStrategyFactory _strategyFactory
) StrategyBase(_strategyManager, _pauserRegistry) {
require(
address(_delegationManager) != address(0) && address(_allocationManager) != address(0)
&& address(_rewardsCoordinator) != address(0) && address(_strategyFactory) != address(0),
OperatorIntegrationInvalid()
);
delegationManager = _delegationManager;
allocationManager = _allocationManager;
rewardsCoordinator = _rewardsCoordinator;
strategyFactory = _strategyFactory;
_disableInitializers();
}
/// @notice Initializes the vault configuration.
/// @param config The vault configuration containing admin, duration, caps, and operator set info.
function initialize(
VaultConfig memory config
) public initializer {
require(config.vaultAdmin != address(0), InvalidVaultAdmin());
require(config.arbitrator != address(0), InvalidArbitrator());
require(config.duration != 0 && config.duration <= MAX_DURATION, InvalidDuration());
_setTVLLimits(config.maxPerDeposit, config.stakeCap);
_initializeStrategyBase(config.underlyingToken);
vaultAdmin = config.vaultAdmin;
arbitrator = config.arbitrator;
duration = config.duration;
metadataURI = config.metadataURI;
_configureOperatorIntegration(config);
_state = VaultState.DEPOSITS;
emit VaultInitialized(
vaultAdmin,
arbitrator,
config.underlyingToken,
duration,
config.maxPerDeposit,
config.stakeCap,
metadataURI
);
}
/// @notice Locks the vault, preventing new deposits and withdrawals until maturity.
function lock() external override onlyVaultAdmin {
require(depositsOpen(), VaultAlreadyLocked());
// Verify this strategy is supported by the operator set before allocating.
IStrategy[] memory strategies = allocationManager.getStrategiesInOperatorSet(_operatorSet);
bool supported = false;
for (uint256 i = 0; i < strategies.length; ++i) {
if (strategies[i] == IStrategy(address(this))) {
supported = true;
break;
}
}
require(supported, StrategyNotSupportedByOperatorSet());
uint32 currentTimestamp = uint32(block.timestamp);
lockedAt = currentTimestamp;
unlockAt = currentTimestamp + duration;
_state = VaultState.ALLOCATIONS;
emit VaultLocked(lockedAt, unlockAt);
_allocateFullMagnitude();
}
/// @notice Marks the vault as matured once the configured duration elapses. Callable by anyone.
function markMatured() external override {
if (_state == VaultState.WITHDRAWALS) {
_attemptOperatorCleanup();
return;
}
require(_state == VaultState.ALLOCATIONS, DurationNotElapsed());
require(block.timestamp >= unlockAt, DurationNotElapsed());
_state = VaultState.WITHDRAWALS;
maturedAt = uint32(block.timestamp);
emit VaultMatured(maturedAt);
_attemptOperatorCleanup();
}
/// @notice Advances the vault to withdrawals early, after lock but before duration elapses.
/// @dev Only callable by the configured arbitrator.
function advanceToWithdrawals() external override onlyArbitrator {
if (_state == VaultState.WITHDRAWALS) {
_attemptOperatorCleanup();
return;
}
require(_state == VaultState.ALLOCATIONS, VaultNotLocked());
require(block.timestamp < unlockAt, DurationAlreadyElapsed());
_state = VaultState.WITHDRAWALS;
maturedAt = uint32(block.timestamp);
emit VaultMatured(maturedAt);
emit VaultAdvancedToWithdrawals(msg.sender, maturedAt);
_attemptOperatorCleanup();
}
/// @notice Updates the metadata URI describing the vault.
function updateMetadataURI(
string calldata newMetadataURI
) external override onlyVaultAdmin {
metadataURI = newMetadataURI;
emit MetadataURIUpdated(newMetadataURI);
}
/// @notice Updates the delegation approver used for operator delegation approvals.
function updateDelegationApprover(
address newDelegationApprover
) external override onlyVaultAdmin {
delegationManager.modifyOperatorDetails(address(this), newDelegationApprover);
}
/// @notice Updates the operator metadata URI emitted by the DelegationManager.
function updateOperatorMetadataURI(
string calldata newOperatorMetadataURI
) external override onlyVaultAdmin {
delegationManager.updateOperatorMetadataURI(address(this), newOperatorMetadataURI);
}
/// @notice Sets the claimer for operator rewards accrued to the vault.
function setRewardsClaimer(
address claimer
) external override onlyVaultAdmin {
rewardsCoordinator.setClaimerFor(address(this), claimer);
}
/// @notice Updates the TVL limits for max deposit per transaction and total stake cap.
/// @dev Only callable by the vault admin while deposits are open (before lock).
function updateTVLLimits(
uint256 newMaxPerDeposit,
uint256 newStakeCap
) external override onlyVaultAdmin {
require(depositsOpen(), DepositsLocked());
_setTVLLimits(newMaxPerDeposit, newStakeCap);
}
/// @notice Allows the unpauser to update TVL limits, mirroring `StrategyBaseTVLLimits`.
function setTVLLimits(
uint256 newMaxPerDeposit,
uint256 newMaxTotalDeposits
) external onlyUnpauser {
// Keep vault config changes constrained to the deposits window.
require(depositsOpen(), DepositsLocked());
_setTVLLimits(newMaxPerDeposit, newMaxTotalDeposits);
}
/// @notice Returns the current TVL limits (per-deposit and total stake cap).
/// @dev Helper for tests and parity with `StrategyBaseTVLLimits`.
function getTVLLimits() external view returns (uint256, uint256) {
return (maxPerDeposit, maxTotalDeposits);
}
/// @inheritdoc IDurationVaultStrategy
function unlockTimestamp() public view override returns (uint32) {
return unlockAt;
}
/// @inheritdoc IDurationVaultStrategy
function isLocked() public view override returns (bool) {
return _state != VaultState.DEPOSITS;
}
/// @inheritdoc IDurationVaultStrategy
function isMatured() public view override returns (bool) {
return _state == VaultState.WITHDRAWALS;
}
/// @inheritdoc IDurationVaultStrategy
function state() public view override returns (VaultState) {
return _state;
}
/// @inheritdoc IDurationVaultStrategy
function stakeCap() external view override returns (uint256) {
return maxTotalDeposits;
}
/// @inheritdoc IDurationVaultStrategy
function depositsOpen() public view override returns (bool) {
return _state == VaultState.DEPOSITS;
}
/// @inheritdoc IDurationVaultStrategy
function withdrawalsOpen() public view override returns (bool) {
return _state != VaultState.ALLOCATIONS;
}
/// @inheritdoc IStrategy
function beforeAddShares(
address staker,
uint256 shares
) external view override(IStrategy, StrategyBase) onlyStrategyManager {
require(depositsOpen(), DepositsLocked());
require(!strategyFactory.isBlacklisted(underlyingToken), UnderlyingTokenBlacklisted());
require(delegationManager.delegatedTo(staker) == address(this), MustBeDelegatedToVaultOperator());
// Enforce per-deposit cap using the minted shares as proxy for underlying.
uint256 amountUnderlying = sharesToUnderlyingView(shares);
require(amountUnderlying <= maxPerDeposit, DepositExceedsMaxPerDeposit());
// Enforce total cap using operatorShares (active, non-queued shares).
// At this point, operatorShares hasn't been updated yet, so we add the new shares.
IStrategy[] memory strategies = new IStrategy[](1);
strategies[0] = IStrategy(address(this));
uint256 currentOperatorShares = delegationManager.getOperatorShares(address(this), strategies)[0];
uint256 postDepositUnderlying = sharesToUnderlyingView(currentOperatorShares + shares);
require(postDepositUnderlying <= maxTotalDeposits, BalanceExceedsMaxTotalDeposits());
}
/// @inheritdoc IStrategy
function beforeRemoveShares(
address,
uint256
) external view override(IStrategy, StrategyBase) onlyStrategyManager {
// Queuing withdrawals is blocked during ALLOCATIONS. Withdrawals queued during
// DEPOSITS can complete during ALLOCATIONS since they were queued before lock.
require(_state != VaultState.ALLOCATIONS, WithdrawalsLockedDuringAllocations());
}
/// @notice Sets the maximum deposits (in underlyingToken) that this strategy will hold and accept per deposit.
/// @param newMaxPerDeposit The new maximum deposit amount per transaction.
/// @param newMaxTotalDeposits The new maximum total deposits allowed.
function _setTVLLimits(
uint256 newMaxPerDeposit,
uint256 newMaxTotalDeposits
) internal {
emit MaxPerDepositUpdated(maxPerDeposit, newMaxPerDeposit);
emit MaxTotalDepositsUpdated(maxTotalDeposits, newMaxTotalDeposits);
require(newMaxPerDeposit <= newMaxTotalDeposits, MaxPerDepositExceedsMax());
maxPerDeposit = newMaxPerDeposit;
maxTotalDeposits = newMaxTotalDeposits;
}
/// @inheritdoc IDurationVaultStrategy
function operatorIntegrationConfigured() public pure override returns (bool) {
return true;
}
/// @inheritdoc IDurationVaultStrategy
function operatorSetInfo() external view override returns (address avs, uint32 operatorSetId) {
return (_operatorSet.avs, _operatorSet.id);
}
/// @inheritdoc IDurationVaultStrategy
function operatorSetRegistered() public view override returns (bool) {
return allocationManager.isMemberOfOperatorSet(address(this), _operatorSet);
}
/// @inheritdoc IDurationVaultStrategy
/// @dev Note: This returns true when the vault is in ALLOCATIONS state, but the actual
/// allocation on the AllocationManager may not be active immediately due to the
/// minWithdrawalDelayBlocks() delay between allocation and effect.
function allocationsActive() public view override returns (bool) {
return _state == VaultState.ALLOCATIONS;
}
/// @inheritdoc IStrategy
function explanation() external pure virtual override(IStrategy, StrategyBase) returns (string memory) {
return "Duration-bound vault strategy with configurable deposit caps and lock periods";
}
/// @notice Configures operator integration: registers as operator, registers for operator set, sets splits.
/// @param config The vault configuration containing operator set and delegation settings.
function _configureOperatorIntegration(
VaultConfig memory config
) internal {
require(config.operatorSet.avs != address(0), OperatorIntegrationInvalid());
_operatorSet = config.operatorSet;
// Set allocation delay strictly greater than withdrawal delay to protect pre-lock queued withdrawals.
uint32 minWithdrawal = delegationManager.minWithdrawalDelayBlocks();
uint32 allocationDelay = minWithdrawal + 1;
// apply allocation delay at registration
delegationManager.registerAsOperator(config.delegationApprover, allocationDelay, config.operatorMetadataURI);
IAllocationManager.RegisterParams memory params;
params.avs = config.operatorSet.avs;
params.operatorSetIds = new uint32[](1);
params.operatorSetIds[0] = config.operatorSet.id;
params.data = config.operatorSetRegistrationData;
allocationManager.registerForOperatorSets(address(this), params);
// Set operator splits to 0 (100% of rewards go to stakers).
// Note: rewards can be configured at the AVS-level and operatorSet-level, so we set both.
rewardsCoordinator.setOperatorAVSSplit(address(this), config.operatorSet.avs, 0);
rewardsCoordinator.setOperatorSetSplit(address(this), config.operatorSet, 0);
rewardsCoordinator.setOperatorPISplit(address(this), 0);
}
/// @notice Allocates full magnitude (1 WAD) to the configured operator set.
/// @dev Reverts if there is already a pending allocation modification.
function _allocateFullMagnitude() internal {
// Ensure no pending allocation modification exists for this operator/operatorSet/strategy.
// Pending modifications would cause ModificationAlreadyPending() in AllocationManager.modifyAllocations.
IAllocationManager.Allocation memory alloc =
allocationManager.getAllocation(address(this), _operatorSet, IStrategy(address(this)));
require(alloc.effectBlock == 0, PendingAllocation());
IAllocationManager.AllocateParams[] memory params = new IAllocationManager.AllocateParams[](1);
params[0].operatorSet = _operatorSet;
params[0].strategies = new IStrategy[](1);
params[0].strategies[0] = IStrategy(address(this));
params[0].newMagnitudes = new uint64[](1);
params[0].newMagnitudes[0] = FULL_ALLOCATION;
allocationManager.modifyAllocations(address(this), params);
}
/// @notice Attempts to deallocate all magnitude from the configured operator set.
/// @dev Best-effort: failures are ignored to avoid bricking `markMatured()`.
function _deallocateAll() internal returns (bool) {
IAllocationManager.Allocation memory alloc =
allocationManager.getAllocation(address(this), _operatorSet, IStrategy(address(this)));
if (alloc.currentMagnitude == 0 && alloc.pendingDiff == 0) {
return true;
}
// If an allocation modification is pending, wait until it clears.
if (alloc.effectBlock != 0) {
return false;
}
IAllocationManager.AllocateParams[] memory params = new IAllocationManager.AllocateParams[](1);
params[0].operatorSet = _operatorSet;
params[0].strategies = new IStrategy[](1);
params[0].strategies[0] = IStrategy(address(this));
params[0].newMagnitudes = new uint64[](1);
params[0].newMagnitudes[0] = 0;
// This call is best-effort: failures should not brick `markMatured()` and lock user funds.
// We use a low-level call instead of try/catch to avoid wallet gas-estimation pitfalls.
(bool success,) = address(allocationManager)
.call(abi.encodeWithSelector(IAllocationManagerActions.modifyAllocations.selector, address(this), params));
return success;
}
/// @notice Attempts to deregister the vault from its configured operator set.
/// @dev Best-effort: failures are ignored to avoid bricking `markMatured()`.
function _deregisterFromOperatorSet() internal returns (bool) {
if (!allocationManager.isMemberOfOperatorSet(address(this), _operatorSet)) {
return true;
}
IAllocationManager.DeregisterParams memory params;
params.operator = address(this);
params.avs = _operatorSet.avs;
params.operatorSetIds = new uint32[](1);
params.operatorSetIds[0] = _operatorSet.id;
// This call is best-effort: failures should not brick `markMatured()` and lock user funds.
// We use a low-level call instead of try/catch to avoid wallet gas-estimation pitfalls.
(bool success,) = address(allocationManager)
.call(abi.encodeWithSelector(IAllocationManagerActions.deregisterFromOperatorSets.selector, params));
return success;
}
/// @notice Best-effort cleanup after maturity, with retry tracking.
function _attemptOperatorCleanup() internal {
bool deallocateSuccess = _deallocateAll();
emit DeallocateAttempted(deallocateSuccess);
bool deregisterSuccess = _deregisterFromOperatorSet();
emit DeregisterAttempted(deregisterSuccess);
}
}