-
Notifications
You must be signed in to change notification settings - Fork 346
/
DelegationManager.sol
853 lines (758 loc) · 36.4 KB
/
DelegationManager.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.12;
import "@openzeppelin-upgrades/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin-upgrades/contracts/access/OwnableUpgradeable.sol";
import "@openzeppelin-upgrades/contracts/security/ReentrancyGuardUpgradeable.sol";
import "../permissions/Pausable.sol";
import "../libraries/EIP1271SignatureUtils.sol";
import "./DelegationManagerStorage.sol";
/**
* @title DelegationManager
* @author Layr Labs, Inc.
* @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
* @notice This is the contract for delegation in EigenLayer. The main functionalities of this contract are
* - enabling anyone to register as an operator in EigenLayer
* - allowing operators to specify parameters related to stakers who delegate to them
* - enabling any staker to delegate its stake to the operator of its choice (a given staker can only delegate to a single operator at a time)
* - enabling a staker to undelegate its assets from the operator it is delegated to (performed as part of the withdrawal process, initiated through the StrategyManager)
*/
contract DelegationManager is
Initializable,
OwnableUpgradeable,
Pausable,
DelegationManagerStorage,
ReentrancyGuardUpgradeable
{
// @dev Index for flag that pauses new delegations when set
uint8 internal constant PAUSED_NEW_DELEGATION = 0;
// @dev Index for flag that pauses queuing new withdrawals when set.
uint8 internal constant PAUSED_ENTER_WITHDRAWAL_QUEUE = 1;
// @dev Index for flag that pauses completing existing withdrawals when set.
uint8 internal constant PAUSED_EXIT_WITHDRAWAL_QUEUE = 2;
// @dev Chain ID at the time of contract deployment
uint256 internal immutable ORIGINAL_CHAIN_ID;
// @dev Maximum Value for `stakerOptOutWindowBlocks`. Approximately equivalent to 6 months in blocks.
uint256 public constant MAX_STAKER_OPT_OUT_WINDOW_BLOCKS = (180 days) / 12;
/// @notice Canonical, virtual beacon chain ETH strategy
IStrategy public constant beaconChainETHStrategy = IStrategy(0xbeaC0eeEeeeeEEeEeEEEEeeEEeEeeeEeeEEBEaC0);
// @notice Simple permission for functions that are only callable by the StrategyManager contract OR by the EigenPodManagerContract
modifier onlyStrategyManagerOrEigenPodManager() {
require(
msg.sender == address(strategyManager) || msg.sender == address(eigenPodManager),
"DelegationManager: onlyStrategyManagerOrEigenPodManager"
);
_;
}
/**
*
* INITIALIZING FUNCTIONS
*
*/
/**
* @dev Initializes the immutable addresses of the strategy mananger and slasher.
*/
constructor(
IStrategyManager _strategyManager,
ISlasher _slasher,
IEigenPodManager _eigenPodManager
) DelegationManagerStorage(_strategyManager, _slasher, _eigenPodManager) {
_disableInitializers();
ORIGINAL_CHAIN_ID = block.chainid;
}
/**
* @dev Initializes the addresses of the initial owner, pauser registry, and paused status.
* minWithdrawalDelayBlocks is set only once here
*/
function initialize(
address initialOwner,
IPauserRegistry _pauserRegistry,
uint256 initialPausedStatus,
uint256 _minWithdrawalDelayBlocks,
IStrategy[] calldata _strategies,
uint256[] calldata _withdrawalDelayBlocks
) external initializer {
_initializePauser(_pauserRegistry, initialPausedStatus);
_DOMAIN_SEPARATOR = _calculateDomainSeparator();
_transferOwnership(initialOwner);
_setMinWithdrawalDelayBlocks(_minWithdrawalDelayBlocks);
_setStrategyWithdrawalDelayBlocks(_strategies, _withdrawalDelayBlocks);
}
/**
*
* EXTERNAL FUNCTIONS
*
*/
/// @inheritdoc IDelegationManager
function registerAsOperator(
OperatorDetails calldata registeringOperatorDetails,
string calldata metadataURI
) external {
require(!isDelegated(msg.sender), "DelegationManager.registerAsOperator: caller is already actively delegated");
_setOperatorDetails(msg.sender, registeringOperatorDetails);
SignatureWithExpiry memory emptySignatureAndExpiry;
// delegate from the operator to themselves
_delegate(msg.sender, msg.sender, emptySignatureAndExpiry, bytes32(0));
// emit events
emit OperatorRegistered(msg.sender, registeringOperatorDetails);
emit OperatorMetadataURIUpdated(msg.sender, metadataURI);
}
/// @inheritdoc IDelegationManager
function modifyOperatorDetails(OperatorDetails calldata newOperatorDetails) external {
require(isOperator(msg.sender), "DelegationManager.modifyOperatorDetails: caller must be an operator");
_setOperatorDetails(msg.sender, newOperatorDetails);
}
/// @inheritdoc IDelegationManager
function updateOperatorMetadataURI(string calldata metadataURI) external {
require(isOperator(msg.sender), "DelegationManager.updateOperatorMetadataURI: caller must be an operator");
emit OperatorMetadataURIUpdated(msg.sender, metadataURI);
}
/// @inheritdoc IDelegationManager
function delegateTo(
address operator,
SignatureWithExpiry memory approverSignatureAndExpiry,
bytes32 approverSalt
) external {
require(!isDelegated(msg.sender), "DelegationManager.delegateTo: staker is already actively delegated");
require(isOperator(operator), "DelegationManager.delegateTo: operator is not registered in EigenLayer");
// go through the internal delegation flow, checking the `approverSignatureAndExpiry` if applicable
_delegate(msg.sender, operator, approverSignatureAndExpiry, approverSalt);
}
/// @inheritdoc IDelegationManager
function delegateToBySignature(
address staker,
address operator,
SignatureWithExpiry memory stakerSignatureAndExpiry,
SignatureWithExpiry memory approverSignatureAndExpiry,
bytes32 approverSalt
) external {
// check the signature expiry
require(
stakerSignatureAndExpiry.expiry >= block.timestamp,
"DelegationManager.delegateToBySignature: staker signature expired"
);
require(!isDelegated(staker), "DelegationManager.delegateToBySignature: staker is already actively delegated");
require(
isOperator(operator), "DelegationManager.delegateToBySignature: operator is not registered in EigenLayer"
);
// calculate the digest hash, then increment `staker`'s nonce
uint256 currentStakerNonce = stakerNonce[staker];
bytes32 stakerDigestHash =
calculateStakerDelegationDigestHash(staker, currentStakerNonce, operator, stakerSignatureAndExpiry.expiry);
unchecked {
stakerNonce[staker] = currentStakerNonce + 1;
}
// actually check that the signature is valid
EIP1271SignatureUtils.checkSignature_EIP1271(staker, stakerDigestHash, stakerSignatureAndExpiry.signature);
// go through the internal delegation flow, checking the `approverSignatureAndExpiry` if applicable
_delegate(staker, operator, approverSignatureAndExpiry, approverSalt);
}
/// @inheritdoc IDelegationManager
function undelegate(address staker)
external
onlyWhenNotPaused(PAUSED_ENTER_WITHDRAWAL_QUEUE)
returns (bytes32[] memory withdrawalRoots)
{
require(isDelegated(staker), "DelegationManager.undelegate: staker must be delegated to undelegate");
require(!isOperator(staker), "DelegationManager.undelegate: operators cannot be undelegated");
require(staker != address(0), "DelegationManager.undelegate: cannot undelegate zero address");
address operator = delegatedTo[staker];
require(
msg.sender == staker || msg.sender == operator
|| msg.sender == _operatorDetails[operator].delegationApprover,
"DelegationManager.undelegate: caller cannot undelegate staker"
);
// Gather strategies and shares to remove from staker/operator during undelegation
// Undelegation removes ALL currently-active strategies and shares
(IStrategy[] memory strategies, uint256[] memory shares) = getDelegatableShares(staker);
// emit an event if this action was not initiated by the staker themselves
if (msg.sender != staker) {
emit StakerForceUndelegated(staker, operator);
}
// undelegate the staker
emit StakerUndelegated(staker, operator);
delegatedTo[staker] = address(0);
// if no delegatable shares, return an empty array, and don't queue a withdrawal
if (strategies.length == 0) {
withdrawalRoots = new bytes32[](0);
} else {
withdrawalRoots = new bytes32[](strategies.length);
for (uint256 i = 0; i < strategies.length; i++) {
IStrategy[] memory singleStrategy = new IStrategy[](1);
uint256[] memory singleShare = new uint256[](1);
singleStrategy[0] = strategies[i];
singleShare[0] = shares[i];
withdrawalRoots[i] = _removeSharesAndQueueWithdrawal({
staker: staker,
operator: operator,
withdrawer: staker,
strategies: singleStrategy,
shares: singleShare
});
}
}
return withdrawalRoots;
}
/// @inheritdoc IDelegationManager
function queueWithdrawals(QueuedWithdrawalParams[] calldata queuedWithdrawalParams)
external
onlyWhenNotPaused(PAUSED_ENTER_WITHDRAWAL_QUEUE)
returns (bytes32[] memory)
{
bytes32[] memory withdrawalRoots = new bytes32[](queuedWithdrawalParams.length);
address operator = delegatedTo[msg.sender];
for (uint256 i = 0; i < queuedWithdrawalParams.length; i++) {
require(
queuedWithdrawalParams[i].strategies.length == queuedWithdrawalParams[i].shares.length,
"DelegationManager.queueWithdrawal: input length mismatch"
);
require(
queuedWithdrawalParams[i].withdrawer == msg.sender,
"DelegationManager.queueWithdrawal: withdrawer must be staker"
);
// Remove shares from staker's strategies and place strategies/shares in queue.
// If the staker is delegated to an operator, the operator's delegated shares are also reduced
// NOTE: This will fail if the staker doesn't have the shares implied by the input parameters
withdrawalRoots[i] = _removeSharesAndQueueWithdrawal({
staker: msg.sender,
operator: operator,
withdrawer: queuedWithdrawalParams[i].withdrawer,
strategies: queuedWithdrawalParams[i].strategies,
shares: queuedWithdrawalParams[i].shares
});
}
return withdrawalRoots;
}
/// @inheritdoc IDelegationManager
function completeQueuedWithdrawal(
Withdrawal calldata withdrawal,
IERC20[] calldata tokens,
uint256 middlewareTimesIndex,
bool receiveAsTokens
) external onlyWhenNotPaused(PAUSED_EXIT_WITHDRAWAL_QUEUE) nonReentrant {
_completeQueuedWithdrawal(withdrawal, tokens, middlewareTimesIndex, receiveAsTokens);
}
/// @inheritdoc IDelegationManager
function completeQueuedWithdrawals(
Withdrawal[] calldata withdrawals,
IERC20[][] calldata tokens,
uint256[] calldata middlewareTimesIndexes,
bool[] calldata receiveAsTokens
) external onlyWhenNotPaused(PAUSED_EXIT_WITHDRAWAL_QUEUE) nonReentrant {
for (uint256 i = 0; i < withdrawals.length; ++i) {
_completeQueuedWithdrawal(withdrawals[i], tokens[i], middlewareTimesIndexes[i], receiveAsTokens[i]);
}
}
/// @inheritdoc IDelegationManager
function increaseDelegatedShares(
address staker,
IStrategy strategy,
uint256 shares
) external onlyStrategyManagerOrEigenPodManager {
// if the staker is delegated to an operator
if (isDelegated(staker)) {
address operator = delegatedTo[staker];
// add strategy shares to delegate's shares
_increaseOperatorShares({operator: operator, staker: staker, strategy: strategy, shares: shares});
}
}
/// @inheritdoc IDelegationManager
function decreaseDelegatedShares(
address staker,
IStrategy strategy,
uint256 shares
) external onlyStrategyManagerOrEigenPodManager {
// if the staker is delegated to an operator
if (isDelegated(staker)) {
address operator = delegatedTo[staker];
// forgefmt: disable-next-item
// subtract strategy shares from delegate's shares
_decreaseOperatorShares({
operator: operator,
staker: staker,
strategy: strategy,
shares: shares
});
}
}
/// @inheritdoc IDelegationManager
function setMinWithdrawalDelayBlocks(uint256 newMinWithdrawalDelayBlocks) external onlyOwner {
_setMinWithdrawalDelayBlocks(newMinWithdrawalDelayBlocks);
}
/// @inheritdoc IDelegationManager
function setStrategyWithdrawalDelayBlocks(
IStrategy[] calldata strategies,
uint256[] calldata withdrawalDelayBlocks
) external onlyOwner {
_setStrategyWithdrawalDelayBlocks(strategies, withdrawalDelayBlocks);
}
/**
*
* INTERNAL FUNCTIONS
*
*/
/**
* @notice Sets operator parameters in the `_operatorDetails` mapping.
* @param operator The account registered as an operator updating their operatorDetails
* @param newOperatorDetails The new parameters for the operator
*/
function _setOperatorDetails(address operator, OperatorDetails calldata newOperatorDetails) internal {
require(
newOperatorDetails.stakerOptOutWindowBlocks <= MAX_STAKER_OPT_OUT_WINDOW_BLOCKS,
"DelegationManager._setOperatorDetails: stakerOptOutWindowBlocks cannot be > MAX_STAKER_OPT_OUT_WINDOW_BLOCKS"
);
require(
newOperatorDetails.stakerOptOutWindowBlocks >= _operatorDetails[operator].stakerOptOutWindowBlocks,
"DelegationManager._setOperatorDetails: stakerOptOutWindowBlocks cannot be decreased"
);
_operatorDetails[operator] = newOperatorDetails;
emit OperatorDetailsModified(msg.sender, newOperatorDetails);
}
/**
* @notice Delegates *from* a `staker` *to* an `operator`.
* @param staker The address to delegate *from* -- this address is delegating control of its own assets.
* @param operator The address to delegate *to* -- this address is being given power to place the `staker`'s assets at risk on services
* @param approverSignatureAndExpiry Verifies the operator approves of this delegation
* @param approverSalt Is a salt used to help guarantee signature uniqueness. Each salt can only be used once by a given approver.
* @dev Assumes the following is checked before calling this function:
* 1) the `staker` is not already delegated to an operator
* 2) the `operator` has indeed registered as an operator in EigenLayer
* Ensures that:
* 1) if applicable, that the approver signature is valid and non-expired
* 2) new delegations are not paused (PAUSED_NEW_DELEGATION)
*/
function _delegate(
address staker,
address operator,
SignatureWithExpiry memory approverSignatureAndExpiry,
bytes32 approverSalt
) internal onlyWhenNotPaused(PAUSED_NEW_DELEGATION) {
// fetch the operator's `delegationApprover` address and store it in memory in case we need to use it multiple times
address _delegationApprover = _operatorDetails[operator].delegationApprover;
/**
* Check the `_delegationApprover`'s signature, if applicable.
* If the `_delegationApprover` is the zero address, then the operator allows all stakers to delegate to them and this verification is skipped.
* If the `_delegationApprover` or the `operator` themselves is the caller, then approval is assumed and signature verification is skipped as well.
*/
if (_delegationApprover != address(0) && msg.sender != _delegationApprover && msg.sender != operator) {
// check the signature expiry
require(
approverSignatureAndExpiry.expiry >= block.timestamp,
"DelegationManager._delegate: approver signature expired"
);
// check that the salt hasn't been used previously, then mark the salt as spent
require(
!delegationApproverSaltIsSpent[_delegationApprover][approverSalt],
"DelegationManager._delegate: approverSalt already spent"
);
delegationApproverSaltIsSpent[_delegationApprover][approverSalt] = true;
// forgefmt: disable-next-item
// calculate the digest hash
bytes32 approverDigestHash = calculateDelegationApprovalDigestHash(
staker,
operator,
_delegationApprover,
approverSalt,
approverSignatureAndExpiry.expiry
);
// forgefmt: disable-next-item
// actually check that the signature is valid
EIP1271SignatureUtils.checkSignature_EIP1271(
_delegationApprover,
approverDigestHash,
approverSignatureAndExpiry.signature
);
}
// record the delegation relation between the staker and operator, and emit an event
delegatedTo[staker] = operator;
emit StakerDelegated(staker, operator);
(IStrategy[] memory strategies, uint256[] memory shares) = getDelegatableShares(staker);
for (uint256 i = 0; i < strategies.length;) {
// forgefmt: disable-next-item
_increaseOperatorShares({
operator: operator,
staker: staker,
strategy: strategies[i],
shares: shares[i]
});
unchecked {
++i;
}
}
}
/**
* @dev commented-out param (middlewareTimesIndex) is the index in the operator that the staker who triggered the withdrawal was delegated to's middleware times array
* This param is intended to be passed on to the Slasher contract, but is unused in the M2 release of these contracts, and is thus commented-out.
*/
function _completeQueuedWithdrawal(
Withdrawal calldata withdrawal,
IERC20[] calldata tokens,
uint256, /*middlewareTimesIndex*/
bool receiveAsTokens
) internal {
bytes32 withdrawalRoot = calculateWithdrawalRoot(withdrawal);
require(
pendingWithdrawals[withdrawalRoot], "DelegationManager._completeQueuedWithdrawal: action is not in queue"
);
require(
withdrawal.startBlock + minWithdrawalDelayBlocks <= block.number,
"DelegationManager._completeQueuedWithdrawal: minWithdrawalDelayBlocks period has not yet passed"
);
require(
msg.sender == withdrawal.withdrawer,
"DelegationManager._completeQueuedWithdrawal: only withdrawer can complete action"
);
if (receiveAsTokens) {
require(
tokens.length == withdrawal.strategies.length,
"DelegationManager._completeQueuedWithdrawal: input length mismatch"
);
}
// Remove `withdrawalRoot` from pending roots
delete pendingWithdrawals[withdrawalRoot];
if (receiveAsTokens) {
// Finalize action by converting shares to tokens for each strategy, or
// by re-awarding shares in each strategy.
for (uint256 i = 0; i < withdrawal.strategies.length;) {
require(
withdrawal.startBlock + strategyWithdrawalDelayBlocks[withdrawal.strategies[i]] <= block.number,
"DelegationManager._completeQueuedWithdrawal: withdrawalDelayBlocks period has not yet passed for this strategy"
);
_withdrawSharesAsTokens({
staker: withdrawal.staker,
withdrawer: msg.sender,
strategy: withdrawal.strategies[i],
shares: withdrawal.shares[i],
token: tokens[i]
});
unchecked {
++i;
}
}
} else {
// Award shares back in StrategyManager/EigenPodManager.
// If withdrawer is delegated, increase the shares delegated to the operator.
address currentOperator = delegatedTo[msg.sender];
for (uint256 i = 0; i < withdrawal.strategies.length;) {
require(
withdrawal.startBlock + strategyWithdrawalDelayBlocks[withdrawal.strategies[i]] <= block.number,
"DelegationManager._completeQueuedWithdrawal: withdrawalDelayBlocks period has not yet passed for this strategy"
);
/**
* When awarding podOwnerShares in EigenPodManager, we need to be sure to only give them back to the original podOwner.
* Other strategy shares can + will be awarded to the withdrawer.
*/
if (withdrawal.strategies[i] == beaconChainETHStrategy) {
address staker = withdrawal.staker;
/**
* Update shares amount depending upon the returned value.
* The return value will be lower than the input value in the case where the staker has an existing share deficit
*/
uint256 increaseInDelegateableShares =
eigenPodManager.addShares({podOwner: staker, shares: withdrawal.shares[i]});
address podOwnerOperator = delegatedTo[staker];
// Similar to `isDelegated` logic
if (podOwnerOperator != address(0)) {
_increaseOperatorShares({
operator: podOwnerOperator,
// the 'staker' here is the address receiving new shares
staker: staker,
strategy: withdrawal.strategies[i],
shares: increaseInDelegateableShares
});
}
} else {
strategyManager.addShares(msg.sender, tokens[i], withdrawal.strategies[i], withdrawal.shares[i]);
// Similar to `isDelegated` logic
if (currentOperator != address(0)) {
_increaseOperatorShares({
operator: currentOperator,
// the 'staker' here is the address receiving new shares
staker: msg.sender,
strategy: withdrawal.strategies[i],
shares: withdrawal.shares[i]
});
}
}
unchecked {
++i;
}
}
}
emit WithdrawalCompleted(withdrawalRoot);
}
// @notice Increases `operator`s delegated shares in `strategy` by `shares` and emits an `OperatorSharesIncreased` event
function _increaseOperatorShares(address operator, address staker, IStrategy strategy, uint256 shares) internal {
operatorShares[operator][strategy] += shares;
emit OperatorSharesIncreased(operator, staker, strategy, shares);
}
// @notice Decreases `operator`s delegated shares in `strategy` by `shares` and emits an `OperatorSharesDecreased` event
function _decreaseOperatorShares(address operator, address staker, IStrategy strategy, uint256 shares) internal {
// This will revert on underflow, so no check needed
operatorShares[operator][strategy] -= shares;
emit OperatorSharesDecreased(operator, staker, strategy, shares);
}
/**
* @notice Removes `shares` in `strategies` from `staker` who is currently delegated to `operator` and queues a withdrawal to the `withdrawer`.
* @dev If the `operator` is indeed an operator, then the operator's delegated shares in the `strategies` are also decreased appropriately.
* @dev If `withdrawer` is not the same address as `staker`, then thirdPartyTransfersForbidden[strategy] must be set to false in the StrategyManager.
*/
function _removeSharesAndQueueWithdrawal(
address staker,
address operator,
address withdrawer,
IStrategy[] memory strategies,
uint256[] memory shares
) internal returns (bytes32) {
require(
staker != address(0), "DelegationManager._removeSharesAndQueueWithdrawal: staker cannot be zero address"
);
require(strategies.length != 0, "DelegationManager._removeSharesAndQueueWithdrawal: strategies cannot be empty");
// Remove shares from staker and operator
// Each of these operations fail if we attempt to remove more shares than exist
for (uint256 i = 0; i < strategies.length;) {
// Similar to `isDelegated` logic
if (operator != address(0)) {
// forgefmt: disable-next-item
_decreaseOperatorShares({
operator: operator,
staker: staker,
strategy: strategies[i],
shares: shares[i]
});
}
// Remove active shares from EigenPodManager/StrategyManager
if (strategies[i] == beaconChainETHStrategy) {
/**
* This call will revert if it would reduce the Staker's virtual beacon chain ETH shares below zero.
* This behavior prevents a Staker from queuing a withdrawal which improperly removes excessive
* shares from the operator to whom the staker is delegated.
* It will also revert if the share amount being withdrawn is not a whole Gwei amount.
*/
eigenPodManager.removeShares(staker, shares[i]);
} else {
require(
staker == withdrawer || !strategyManager.thirdPartyTransfersForbidden(strategies[i]),
"DelegationManager._removeSharesAndQueueWithdrawal: withdrawer must be same address as staker if thirdPartyTransfersForbidden are set"
);
// this call will revert if `shares[i]` exceeds the Staker's current shares in `strategies[i]`
strategyManager.removeShares(staker, strategies[i], shares[i]);
}
unchecked {
++i;
}
}
// Create queue entry and increment withdrawal nonce
uint256 nonce = cumulativeWithdrawalsQueued[staker];
cumulativeWithdrawalsQueued[staker]++;
Withdrawal memory withdrawal = Withdrawal({
staker: staker,
delegatedTo: operator,
withdrawer: withdrawer,
nonce: nonce,
startBlock: uint32(block.number),
strategies: strategies,
shares: shares
});
bytes32 withdrawalRoot = calculateWithdrawalRoot(withdrawal);
// Place withdrawal in queue
pendingWithdrawals[withdrawalRoot] = true;
emit WithdrawalQueued(withdrawalRoot, withdrawal);
return withdrawalRoot;
}
/**
* @notice Withdraws `shares` in `strategy` to `withdrawer`. If the shares are virtual beaconChainETH shares, then a call is ultimately forwarded to the
* `staker`s EigenPod; otherwise a call is ultimately forwarded to the `strategy` with info on the `token`.
*/
function _withdrawSharesAsTokens(
address staker,
address withdrawer,
IStrategy strategy,
uint256 shares,
IERC20 token
) internal {
if (strategy == beaconChainETHStrategy) {
eigenPodManager.withdrawSharesAsTokens({podOwner: staker, destination: withdrawer, shares: shares});
} else {
strategyManager.withdrawSharesAsTokens(withdrawer, strategy, shares, token);
}
}
function _setMinWithdrawalDelayBlocks(uint256 _minWithdrawalDelayBlocks) internal {
require(
_minWithdrawalDelayBlocks <= MAX_WITHDRAWAL_DELAY_BLOCKS,
"DelegationManager._setMinWithdrawalDelayBlocks: _minWithdrawalDelayBlocks cannot be > MAX_WITHDRAWAL_DELAY_BLOCKS"
);
emit MinWithdrawalDelayBlocksSet(minWithdrawalDelayBlocks, _minWithdrawalDelayBlocks);
minWithdrawalDelayBlocks = _minWithdrawalDelayBlocks;
}
/**
* @notice Sets the withdrawal delay blocks for each strategy in `_strategies` to `_withdrawalDelayBlocks`.
* gets called when initializing contract or by calling `setStrategyWithdrawalDelayBlocks`
*/
function _setStrategyWithdrawalDelayBlocks(
IStrategy[] calldata _strategies,
uint256[] calldata _withdrawalDelayBlocks
) internal {
require(
_strategies.length == _withdrawalDelayBlocks.length,
"DelegationManager._setStrategyWithdrawalDelayBlocks: input length mismatch"
);
uint256 numStrats = _strategies.length;
for (uint256 i = 0; i < numStrats; ++i) {
IStrategy strategy = _strategies[i];
uint256 prevStrategyWithdrawalDelayBlocks = strategyWithdrawalDelayBlocks[strategy];
uint256 newStrategyWithdrawalDelayBlocks = _withdrawalDelayBlocks[i];
require(
newStrategyWithdrawalDelayBlocks <= MAX_WITHDRAWAL_DELAY_BLOCKS,
"DelegationManager._setStrategyWithdrawalDelayBlocks: _withdrawalDelayBlocks cannot be > MAX_WITHDRAWAL_DELAY_BLOCKS"
);
// set the new withdrawal delay blocks
strategyWithdrawalDelayBlocks[strategy] = newStrategyWithdrawalDelayBlocks;
emit StrategyWithdrawalDelayBlocksSet(
strategy, prevStrategyWithdrawalDelayBlocks, newStrategyWithdrawalDelayBlocks
);
}
}
/**
*
* VIEW FUNCTIONS
*
*/
/// @inheritdoc IDelegationManager
function domainSeparator() public view returns (bytes32) {
if (block.chainid == ORIGINAL_CHAIN_ID) {
return _DOMAIN_SEPARATOR;
} else {
return _calculateDomainSeparator();
}
}
/// @inheritdoc IDelegationManager
function isDelegated(address staker) public view returns (bool) {
return (delegatedTo[staker] != address(0));
}
/// @inheritdoc IDelegationManager
function isOperator(address operator) public view returns (bool) {
return operator != address(0) && delegatedTo[operator] == operator;
}
/// @inheritdoc IDelegationManager
function operatorDetails(address operator) external view returns (OperatorDetails memory) {
return _operatorDetails[operator];
}
/// @inheritdoc IDelegationManager
function delegationApprover(address operator) external view returns (address) {
return _operatorDetails[operator].delegationApprover;
}
/// @inheritdoc IDelegationManager
function stakerOptOutWindowBlocks(address operator) external view returns (uint256) {
return _operatorDetails[operator].stakerOptOutWindowBlocks;
}
/// @inheritdoc IDelegationManager
function getOperatorShares(
address operator,
IStrategy[] memory strategies
) public view returns (uint256[] memory) {
uint256[] memory shares = new uint256[](strategies.length);
for (uint256 i = 0; i < strategies.length; ++i) {
shares[i] = operatorShares[operator][strategies[i]];
}
return shares;
}
/// @inheritdoc IDelegationManager
function getDelegatableShares(address staker) public view returns (IStrategy[] memory, uint256[] memory) {
// Get currently active shares and strategies for `staker`
int256 podShares = eigenPodManager.podOwnerShares(staker);
(IStrategy[] memory strategyManagerStrats, uint256[] memory strategyManagerShares) =
strategyManager.getDeposits(staker);
// Has no shares in EigenPodManager, but potentially some in StrategyManager
if (podShares <= 0) {
return (strategyManagerStrats, strategyManagerShares);
}
IStrategy[] memory strategies;
uint256[] memory shares;
if (strategyManagerStrats.length == 0) {
// Has shares in EigenPodManager, but not in StrategyManager
strategies = new IStrategy[](1);
shares = new uint256[](1);
strategies[0] = beaconChainETHStrategy;
shares[0] = uint256(podShares);
} else {
// Has shares in both
// 1. Allocate return arrays
strategies = new IStrategy[](strategyManagerStrats.length + 1);
shares = new uint256[](strategies.length);
// 2. Place StrategyManager strats/shares in return arrays
for (uint256 i = 0; i < strategyManagerStrats.length;) {
strategies[i] = strategyManagerStrats[i];
shares[i] = strategyManagerShares[i];
unchecked {
++i;
}
}
// 3. Place EigenPodManager strat/shares in return arrays
strategies[strategies.length - 1] = beaconChainETHStrategy;
shares[strategies.length - 1] = uint256(podShares);
}
return (strategies, shares);
}
/// @inheritdoc IDelegationManager
function getWithdrawalDelay(IStrategy[] calldata strategies) public view returns (uint256) {
uint256 withdrawalDelay = minWithdrawalDelayBlocks;
for (uint256 i = 0; i < strategies.length; ++i) {
uint256 currWithdrawalDelay = strategyWithdrawalDelayBlocks[strategies[i]];
if (currWithdrawalDelay > withdrawalDelay) {
withdrawalDelay = currWithdrawalDelay;
}
}
return withdrawalDelay;
}
/// @inheritdoc IDelegationManager
function calculateWithdrawalRoot(Withdrawal memory withdrawal) public pure returns (bytes32) {
return keccak256(abi.encode(withdrawal));
}
/// @inheritdoc IDelegationManager
function calculateCurrentStakerDelegationDigestHash(
address staker,
address operator,
uint256 expiry
) external view returns (bytes32) {
// fetch the staker's current nonce
uint256 currentStakerNonce = stakerNonce[staker];
// calculate the digest hash
return calculateStakerDelegationDigestHash(staker, currentStakerNonce, operator, expiry);
}
/// @inheritdoc IDelegationManager
function calculateStakerDelegationDigestHash(
address staker,
uint256 _stakerNonce,
address operator,
uint256 expiry
) public view returns (bytes32) {
// calculate the struct hash
bytes32 stakerStructHash =
keccak256(abi.encode(STAKER_DELEGATION_TYPEHASH, staker, operator, _stakerNonce, expiry));
// calculate the digest hash
bytes32 stakerDigestHash = keccak256(abi.encodePacked("\x19\x01", domainSeparator(), stakerStructHash));
return stakerDigestHash;
}
/// @inheritdoc IDelegationManager
function calculateDelegationApprovalDigestHash(
address staker,
address operator,
address _delegationApprover,
bytes32 approverSalt,
uint256 expiry
) public view returns (bytes32) {
// calculate the struct hash
bytes32 approverStructHash = keccak256(
abi.encode(DELEGATION_APPROVAL_TYPEHASH, _delegationApprover, staker, operator, approverSalt, expiry)
);
// calculate the digest hash
bytes32 approverDigestHash = keccak256(abi.encodePacked("\x19\x01", domainSeparator(), approverStructHash));
return approverDigestHash;
}
/**
* @dev Recalculates the domain separator when the chainid changes due to a fork.
*/
function _calculateDomainSeparator() internal view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("EigenLayer")), block.chainid, address(this)));
}
}