-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathDelegationManager.sol
1014 lines (886 loc) · 44.1 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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
import "@openzeppelin-upgrades/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin-upgrades/contracts/access/OwnableUpgradeable.sol";
import "@openzeppelin-upgrades/contracts/security/ReentrancyGuardUpgradeable.sol";
import "../mixins/SignatureUtils.sol";
import "../mixins/PermissionControllerMixin.sol";
import "../permissions/Pausable.sol";
import "../libraries/SlashingLib.sol";
import "../libraries/Snapshots.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,
SignatureUtils,
PermissionControllerMixin
{
using SlashingLib for *;
using Snapshots for Snapshots.DefaultZeroHistory;
using EnumerableSet for EnumerableSet.Bytes32Set;
// @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)),
OnlyStrategyManagerOrEigenPodManager()
);
_;
}
modifier onlyEigenPodManager() {
require(msg.sender == address(eigenPodManager), OnlyEigenPodManager());
_;
}
modifier onlyAllocationManager() {
require(msg.sender == address(allocationManager), OnlyAllocationManager());
_;
}
/**
*
* INITIALIZING FUNCTIONS
*
*/
/**
* @dev Initializes the immutable addresses of the strategy mananger, eigenpod manager, and allocation manager.
*/
constructor(
IStrategyManager _strategyManager,
IEigenPodManager _eigenPodManager,
IAllocationManager _allocationManager,
IPauserRegistry _pauserRegistry,
IPermissionController _permissionController,
uint32 _MIN_WITHDRAWAL_DELAY
)
DelegationManagerStorage(_strategyManager, _eigenPodManager, _allocationManager, _MIN_WITHDRAWAL_DELAY)
Pausable(_pauserRegistry)
PermissionControllerMixin(_permissionController)
{
_disableInitializers();
}
function initialize(address initialOwner, uint256 initialPausedStatus) external initializer {
_setPausedStatus(initialPausedStatus);
_transferOwnership(initialOwner);
}
/**
*
* EXTERNAL FUNCTIONS
*
*/
/// @inheritdoc IDelegationManager
function registerAsOperator(
address initDelegationApprover,
uint32 allocationDelay,
string calldata metadataURI
) external {
require(!isDelegated(msg.sender), ActivelyDelegated());
allocationManager.setAllocationDelay(msg.sender, allocationDelay);
_setDelegationApprover(msg.sender, initDelegationApprover);
// delegate from the operator to themselves
_delegate(msg.sender, msg.sender);
emit OperatorRegistered(msg.sender, initDelegationApprover);
emit OperatorMetadataURIUpdated(msg.sender, metadataURI);
}
/// @inheritdoc IDelegationManager
function modifyOperatorDetails(address operator, address newDelegationApprover) external checkCanCall(operator) {
require(isOperator(operator), OperatorNotRegistered());
_setDelegationApprover(operator, newDelegationApprover);
}
/// @inheritdoc IDelegationManager
function updateOperatorMetadataURI(address operator, string calldata metadataURI) external checkCanCall(operator) {
require(isOperator(operator), OperatorNotRegistered());
emit OperatorMetadataURIUpdated(operator, metadataURI);
}
/// @inheritdoc IDelegationManager
function delegateTo(
address operator,
SignatureWithExpiry memory approverSignatureAndExpiry,
bytes32 approverSalt
) public {
require(!isDelegated(msg.sender), ActivelyDelegated());
require(isOperator(operator), OperatorNotRegistered());
// If the operator has a `delegationApprover`, check the provided signature
_checkApproverSignature({
staker: msg.sender,
operator: operator,
signature: approverSignatureAndExpiry,
salt: approverSalt
});
// Delegate msg.sender to the operator
_delegate(msg.sender, operator);
}
/// @inheritdoc IDelegationManager
function undelegate(
address staker
) public returns (bytes32[] memory withdrawalRoots) {
// Check that the `staker` can undelegate
require(isDelegated(staker), NotActivelyDelegated());
require(!isOperator(staker), OperatorsCannotUndelegate());
// If the action is not being initiated by the staker, validate that it is initiated
// by the operator or their delegationApprover.
if (msg.sender != staker) {
address operator = delegatedTo[staker];
require(_checkCanCall(operator) || msg.sender == delegationApprover(operator), CallerCannotUndelegate());
emit StakerForceUndelegated(staker, operator);
}
return _undelegate(staker);
}
/// @inheritdoc IDelegationManager
function redelegate(
address newOperator,
SignatureWithExpiry memory newOperatorApproverSig,
bytes32 approverSalt
) external returns (bytes32[] memory withdrawalRoots) {
withdrawalRoots = undelegate(msg.sender);
// delegateTo uses msg.sender as staker
delegateTo(newOperator, newOperatorApproverSig, approverSalt);
}
/// @inheritdoc IDelegationManager
function queueWithdrawals(
QueuedWithdrawalParams[] calldata params
) external onlyWhenNotPaused(PAUSED_ENTER_WITHDRAWAL_QUEUE) returns (bytes32[] memory) {
bytes32[] memory withdrawalRoots = new bytes32[](params.length);
address operator = delegatedTo[msg.sender];
for (uint256 i = 0; i < params.length; i++) {
require(params[i].strategies.length == params[i].depositShares.length, InputArrayLengthMismatch());
uint256[] memory slashingFactors = _getSlashingFactors(msg.sender, operator, params[i].strategies);
// 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.
// The view function getWithdrawableShares() can be used to check what shares are available for withdrawal.
withdrawalRoots[i] = _removeSharesAndQueueWithdrawal({
staker: msg.sender,
operator: operator,
strategies: params[i].strategies,
depositSharesToWithdraw: params[i].depositShares,
slashingFactors: slashingFactors
});
}
return withdrawalRoots;
}
/// @inheritdoc IDelegationManager
function completeQueuedWithdrawal(
Withdrawal calldata withdrawal,
IERC20[] calldata tokens,
bool receiveAsTokens
) external onlyWhenNotPaused(PAUSED_EXIT_WITHDRAWAL_QUEUE) nonReentrant {
_completeQueuedWithdrawal(withdrawal, tokens, receiveAsTokens);
}
/// @inheritdoc IDelegationManager
function completeQueuedWithdrawals(
Withdrawal[] calldata withdrawals,
IERC20[][] calldata tokens,
bool[] calldata receiveAsTokens
) external onlyWhenNotPaused(PAUSED_EXIT_WITHDRAWAL_QUEUE) nonReentrant {
uint256 n = withdrawals.length;
for (uint256 i; i < n; ++i) {
_completeQueuedWithdrawal(withdrawals[i], tokens[i], receiveAsTokens[i]);
}
}
/// @inheritdoc IDelegationManager
function increaseDelegatedShares(
address staker,
IStrategy strategy,
uint256 prevDepositShares,
uint256 addedShares
) external onlyStrategyManagerOrEigenPodManager {
/// Note: Unlike `decreaseDelegatedShares`, we don't return early if the staker has no operator.
/// This is because `_increaseDelegation` updates the staker's deposit scaling factor, which we
/// need to do even if not delegated.
address operator = delegatedTo[staker];
uint64 maxMagnitude = allocationManager.getMaxMagnitude(operator, strategy);
uint256 slashingFactor = _getSlashingFactor(staker, strategy, maxMagnitude);
// Increase the staker's deposit scaling factor and delegate shares to the operator
_increaseDelegation({
operator: operator,
staker: staker,
strategy: strategy,
prevDepositShares: prevDepositShares,
addedShares: addedShares,
slashingFactor: slashingFactor
});
}
/// @inheritdoc IDelegationManager
function decreaseDelegatedShares(
address staker,
uint256 curDepositShares,
uint64 beaconChainSlashingFactorDecrease
) external onlyEigenPodManager {
if (!isDelegated(staker)) {
return;
}
address operator = delegatedTo[staker];
// Calculate the shares to remove from the operator by calculating difference in shares
// from the newly updated beaconChainSlashingFactor
uint64 maxMagnitude = allocationManager.getMaxMagnitude(operator, beaconChainETHStrategy);
DepositScalingFactor memory dsf = _depositScalingFactor[staker][beaconChainETHStrategy];
uint256 sharesToRemove = dsf.calcWithdrawable({
depositShares: curDepositShares,
slashingFactor: maxMagnitude.mulWad(beaconChainSlashingFactorDecrease)
});
// Decrease the operator's shares
_decreaseDelegation({
operator: operator,
staker: staker,
strategy: beaconChainETHStrategy,
sharesToDecrease: sharesToRemove
});
}
/// @inheritdoc IDelegationManager
function slashOperatorShares(
address operator,
IStrategy strategy,
uint64 prevMaxMagnitude,
uint64 newMaxMagnitude
) external onlyAllocationManager {
/// forgefmt: disable-next-item
uint256 operatorSharesSlashed = SlashingLib.calcSlashedAmount({
operatorShares: operatorShares[operator][strategy],
prevMaxMagnitude: prevMaxMagnitude,
newMaxMagnitude: newMaxMagnitude
});
uint256 scaledSharesSlashedFromQueue = _getSlashableSharesInQueue({
operator: operator,
strategy: strategy,
prevMaxMagnitude: prevMaxMagnitude,
newMaxMagnitude: newMaxMagnitude
});
// Calculate the total deposit shares to burn - slashed operator shares plus still-slashable
// shares sitting in the withdrawal queue.
uint256 totalDepositSharesToBurn = operatorSharesSlashed + scaledSharesSlashedFromQueue;
// Remove shares from operator
_decreaseDelegation({
operator: operator,
staker: address(0), // we treat this as a decrease for the 0-staker (only used for events)
strategy: strategy,
sharesToDecrease: operatorSharesSlashed
});
IShareManager shareManager = _getShareManager(strategy);
// NOTE: for beaconChainETHStrategy, increased burnable shares currently have no mechanism for burning
shareManager.increaseBurnableShares(strategy, totalDepositSharesToBurn);
}
/**
*
* INTERNAL FUNCTIONS
*
*/
/**
* @notice Sets operator parameters in the `_operatorDetails` mapping.
* @param operator The account registered as an operator updating their operatorDetails
* @param newDelegationApprover The new parameters for the operator
*/
function _setDelegationApprover(address operator, address newDelegationApprover) internal {
_operatorDetails[operator].delegationApprover = newDelegationApprover;
emit DelegationApproverUpdated(operator, newDelegationApprover);
}
/**
* @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
* @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
* 3) if applicable, the `operator's` `delegationApprover` signed off on delegation
* Ensures that:
* 1) new delegations are not paused (PAUSED_NEW_DELEGATION)
*/
function _delegate(address staker, address operator) internal onlyWhenNotPaused(PAUSED_NEW_DELEGATION) {
// record the delegation relation between the staker and operator, and emit an event
delegatedTo[staker] = operator;
emit StakerDelegated(staker, operator);
// read staker's deposited shares and strategies to add to operator's shares
// and also update the staker depositScalingFactor for each strategy
(IStrategy[] memory strategies, uint256[] memory depositedShares) = getDepositedShares(staker);
uint256[] memory slashingFactors = _getSlashingFactors(staker, operator, strategies);
for (uint256 i = 0; i < strategies.length; ++i) {
// forgefmt: disable-next-item
_increaseDelegation({
operator: operator,
staker: staker,
strategy: strategies[i],
prevDepositShares: uint256(0),
addedShares: depositedShares[i],
slashingFactor: slashingFactors[i]
});
}
}
/**
* @dev Undelegates `staker` from their operator, queueing a withdrawal for all
* their deposited shares in the process.
* @dev Assumes the following is checked before calling this function:
* 1) the `staker` is currently delegated to an operator
* 2) the `staker` is not an operator themselves
* Ensures that:
* 1) the withdrawal queue is not paused (PAUSED_ENTER_WITHDRAWAL_QUEUE)
*/
function _undelegate(
address staker
) internal onlyWhenNotPaused(PAUSED_ENTER_WITHDRAWAL_QUEUE) returns (bytes32[] memory withdrawalRoots) {
// Undelegate the staker
address operator = delegatedTo[staker];
delegatedTo[staker] = address(0);
emit StakerUndelegated(staker, operator);
// Get all of the staker's deposited strategies/shares. These will be removed from the operator
// and queued for withdrawal.
(IStrategy[] memory strategies, uint256[] memory depositedShares) = getDepositedShares(staker);
if (strategies.length == 0) {
return withdrawalRoots;
}
// For the operator and each of the staker's strategies, get the slashing factors to apply
// when queueing for withdrawal
withdrawalRoots = new bytes32[](strategies.length);
uint256[] memory slashingFactors = _getSlashingFactors(staker, operator, strategies);
// Queue a withdrawal for each strategy independently. This is done for UX reasons.
for (uint256 i = 0; i < strategies.length; i++) {
IStrategy[] memory singleStrategy = new IStrategy[](1);
uint256[] memory singleDepositShares = new uint256[](1);
uint256[] memory singleSlashingFactor = new uint256[](1);
singleStrategy[0] = strategies[i];
singleDepositShares[0] = depositedShares[i];
singleSlashingFactor[0] = slashingFactors[i];
// Remove shares from staker's strategies and place strategies/shares in queue.
// The operator's delegated shares are also reduced.
withdrawalRoots[i] = _removeSharesAndQueueWithdrawal({
staker: staker,
operator: operator,
strategies: singleStrategy,
depositSharesToWithdraw: singleDepositShares,
slashingFactors: singleSlashingFactor
});
}
return withdrawalRoots;
}
/**
* @notice Removes `sharesToWithdraw` in `strategies` from `staker` who is currently delegated to `operator` and queues a withdrawal to the `withdrawer`.
* @param staker The staker queuing a withdrawal
* @param operator The operator the staker is delegated to
* @param strategies The strategies to queue a withdrawal for
* @param depositSharesToWithdraw The amount of deposit shares the staker wishes to withdraw, must be less than staker's depositShares in storage
* @param slashingFactors The corresponding slashing factor for the staker/operator for each strategy
*
* @dev The amount withdrawable by the staker may not actually be the same as the depositShares that are in storage in the StrategyManager/EigenPodManager.
* This is a result of any slashing that has occurred during the time the staker has been delegated to an operator. So the proportional amount that is withdrawn
* out of the amount withdrawable for the staker has to also be decremented from the staker's deposit shares.
* So the amount of depositShares withdrawn out has to be proportionally scaled down depending on the slashing that has occurred.
* Ex. Suppose as a staker, I have 100 depositShares for a strategy thats sitting in the StrategyManager in the `stakerDepositShares` mapping but I actually have been slashed 50%
* and my real withdrawable amount is 50 shares.
* Now when I go to withdraw 40 depositShares, I'm proportionally withdrawing 40% of my withdrawable shares. We calculate below the actual shares withdrawn via the `toShares()` function to
* get 20 shares to queue withdraw. The end state is that I have 60 depositShares and 30 withdrawable shares now, this still accurately reflects a 50% slashing that has occurred on my existing stake.
* @dev depositSharesToWithdraw are converted to sharesToWithdraw using the `toShares` library function. sharesToWithdraw are then divided by the current maxMagnitude of the operator (at queue time)
* and this value is stored in the Withdrawal struct as `scaledShares.
* Upon completion the `scaledShares` are then multiplied by the maxMagnitude of the operator at completion time. This is how we factor in any slashing events
* that occurred during the withdrawal delay period. Shares in a withdrawal are no longer slashable once the withdrawal is completable.
* @dev If the `operator` is indeed an operator, then the operator's delegated shares in the `strategies` are also decreased appropriately.
*/
function _removeSharesAndQueueWithdrawal(
address staker,
address operator,
IStrategy[] memory strategies,
uint256[] memory depositSharesToWithdraw,
uint256[] memory slashingFactors
) internal returns (bytes32) {
require(staker != address(0), InputAddressZero());
require(strategies.length != 0, InputArrayLengthZero());
uint256[] memory scaledShares = new uint256[](strategies.length);
uint256[] memory withdrawableShares = new uint256[](strategies.length);
// 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; ++i) {
IShareManager shareManager = _getShareManager(strategies[i]);
DepositScalingFactor memory dsf = _depositScalingFactor[staker][strategies[i]];
// Calculate how many shares can be withdrawn after factoring in slashing
withdrawableShares[i] = dsf.calcWithdrawable(depositSharesToWithdraw[i], slashingFactors[i]);
// Scale shares for queue withdrawal
scaledShares[i] = dsf.scaleForQueueWithdrawal(depositSharesToWithdraw[i]);
// Remove delegated shares from the operator
if (operator != address(0)) {
// Staker was delegated and remains slashable during the withdrawal delay period
// Cumulative withdrawn scaled shares are updated for the strategy, this is for accounting
// purposes for burning shares if slashed
_addQueuedSlashableShares(operator, strategies[i], scaledShares[i]);
// forgefmt: disable-next-item
_decreaseDelegation({
operator: operator,
staker: staker,
strategy: strategies[i],
sharesToDecrease: withdrawableShares[i]
});
}
// Remove deposit shares from EigenPodManager/StrategyManager
shareManager.removeDepositShares(staker, strategies[i], depositSharesToWithdraw[i]);
}
// Create queue entry and increment withdrawal nonce
uint256 nonce = cumulativeWithdrawalsQueued[staker];
cumulativeWithdrawalsQueued[staker]++;
Withdrawal memory withdrawal = Withdrawal({
staker: staker,
delegatedTo: operator,
withdrawer: staker,
nonce: nonce,
startBlock: uint32(block.number),
strategies: strategies,
scaledShares: scaledShares
});
bytes32 withdrawalRoot = calculateWithdrawalRoot(withdrawal);
pendingWithdrawals[withdrawalRoot] = true;
queuedWithdrawals[withdrawalRoot] = withdrawal;
_stakerQueuedWithdrawalRoots[staker].add(withdrawalRoot);
emit SlashingWithdrawalQueued(withdrawalRoot, withdrawal, withdrawableShares);
return withdrawalRoot;
}
/**
* @dev This function completes a queued withdrawal for a staker.
* This will apply any slashing that has occurred since the the withdrawal was queued by multiplying the withdrawal's
* scaledShares by the operator's maxMagnitude for each strategy. This ensures that any slashing that has occurred
* during the period the withdrawal was queued until its slashableUntil block is applied to the withdrawal amount.
* If receiveAsTokens is true, then these shares will be withdrawn as tokens.
* If receiveAsTokens is false, then they will be redeposited according to the current operator the staker is delegated to,
* and added back to the operator's delegatedShares.
*/
function _completeQueuedWithdrawal(
Withdrawal memory withdrawal,
IERC20[] calldata tokens,
bool receiveAsTokens
) internal {
require(tokens.length == withdrawal.strategies.length, InputArrayLengthMismatch());
require(msg.sender == withdrawal.withdrawer, WithdrawerNotCaller());
bytes32 withdrawalRoot = calculateWithdrawalRoot(withdrawal);
require(pendingWithdrawals[withdrawalRoot], WithdrawalNotQueued());
uint256[] memory prevSlashingFactors;
{
// slashableUntil is block inclusive so we need to check if the current block is strictly greater than the slashableUntil block
// meaning the withdrawal can be completed.
uint32 slashableUntil = withdrawal.startBlock + MIN_WITHDRAWAL_DELAY_BLOCKS;
require(uint32(block.number) > slashableUntil, WithdrawalDelayNotElapsed());
// Given the max magnitudes of the operator the staker was originally delegated to, calculate
// the slashing factors for each of the withdrawal's strategies.
prevSlashingFactors = _getSlashingFactorsAtBlock({
staker: withdrawal.staker,
operator: withdrawal.delegatedTo,
strategies: withdrawal.strategies,
blockNumber: slashableUntil
});
}
// Remove the withdrawal from the queue. Note that for legacy withdrawals, the removals
// from `_stakerQueuedWithdrawalRoots` and `queuedWithdrawals` will no-op.
_stakerQueuedWithdrawalRoots[withdrawal.staker].remove(withdrawalRoot);
delete queuedWithdrawals[withdrawalRoot];
delete pendingWithdrawals[withdrawalRoot];
emit SlashingWithdrawalCompleted(withdrawalRoot);
// Given the max magnitudes of the operator the staker is now delegated to, calculate the current
// slashing factors to apply to each withdrawal if it is received as shares.
address newOperator = delegatedTo[withdrawal.staker];
uint256[] memory newSlashingFactors = _getSlashingFactors(withdrawal.staker, newOperator, withdrawal.strategies);
for (uint256 i = 0; i < withdrawal.strategies.length; i++) {
IShareManager shareManager = _getShareManager(withdrawal.strategies[i]);
// Calculate how much slashing to apply, as well as shares to withdraw
uint256 sharesToWithdraw = SlashingLib.scaleForCompleteWithdrawal({
scaledShares: withdrawal.scaledShares[i],
slashingFactor: prevSlashingFactors[i]
});
if (receiveAsTokens) {
// 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`.
shareManager.withdrawSharesAsTokens({
staker: withdrawal.staker,
strategy: withdrawal.strategies[i],
token: tokens[i],
shares: sharesToWithdraw
});
} else {
// Award shares back in StrategyManager/EigenPodManager.
(uint256 prevDepositShares, uint256 addedShares) = shareManager.addShares({
staker: withdrawal.staker,
strategy: withdrawal.strategies[i],
token: tokens[i],
shares: sharesToWithdraw
});
// Update the staker's deposit scaling factor and delegate shares to their operator
_increaseDelegation({
operator: newOperator,
staker: withdrawal.staker,
strategy: withdrawal.strategies[i],
prevDepositShares: prevDepositShares,
addedShares: addedShares,
slashingFactor: newSlashingFactors[i]
});
}
}
}
/**
* @notice Increases `operator`s depositedShares in `strategy` based on staker's addedDepositShares
* and updates the staker's depositScalingFactor for the strategy.
* @param operator The operator to increase the delegated delegatedShares for
* @param staker The staker to increase the depositScalingFactor for
* @param strategy The strategy to increase the delegated delegatedShares and the depositScalingFactor for
* @param prevDepositShares The number of delegated deposit shares the staker had in the strategy prior to the increase
* @param addedShares The shares added to the staker in the StrategyManager/EigenPodManager
* @param slashingFactor The current slashing factor for the staker/operator/strategy
*/
function _increaseDelegation(
address operator,
address staker,
IStrategy strategy,
uint256 prevDepositShares,
uint256 addedShares,
uint256 slashingFactor
) internal {
// Ensure that the operator has not been fully slashed for a strategy
// and that the staker has not been fully slashed if it is the beaconChainStrategy
// This is to prevent a divWad by 0 when updating the depositScalingFactor
require(slashingFactor != 0, FullySlashed());
// Update the staker's depositScalingFactor. This only results in an update
// if the slashing factor has changed for this strategy.
DepositScalingFactor storage dsf = _depositScalingFactor[staker][strategy];
dsf.update(prevDepositShares, addedShares, slashingFactor);
emit DepositScalingFactorUpdated(staker, strategy, dsf.scalingFactor());
// If the staker is delegated to an operator, update the operator's shares
if (isDelegated(staker)) {
operatorShares[operator][strategy] += addedShares;
emit OperatorSharesIncreased(operator, staker, strategy, addedShares);
}
}
/**
* @notice Decreases `operator`s shares in `strategy` based on staker's removed shares
* @param operator The operator to decrease the delegated delegated shares for
* @param staker The staker to decrease the delegated delegated shares for
* @param strategy The strategy to decrease the delegated delegated shares for
* @param sharesToDecrease The shares to remove from the operator's delegated shares
*/
function _decreaseDelegation(
address operator,
address staker,
IStrategy strategy,
uint256 sharesToDecrease
) internal {
// Decrement operator shares
operatorShares[operator][strategy] -= sharesToDecrease;
emit OperatorSharesDecreased(operator, staker, strategy, sharesToDecrease);
}
/// @dev If `operator` has configured a `delegationApprover`, check that `signature` and `salt`
/// are a valid approval for `staker` delegating to `operator`.
function _checkApproverSignature(
address staker,
address operator,
SignatureWithExpiry memory signature,
bytes32 salt
) internal {
address approver = _operatorDetails[operator].delegationApprover;
if (approver == address(0)) {
return;
}
// Check that the salt hasn't been used previously, then mark the salt as spent
require(!delegationApproverSaltIsSpent[approver][salt], SaltSpent());
delegationApproverSaltIsSpent[approver][salt] = true;
// Validate the signature
_checkIsValidSignatureNow({
signer: approver,
signableDigest: calculateDelegationApprovalDigestHash(staker, operator, approver, salt, signature.expiry),
signature: signature.signature,
expiry: signature.expiry
});
}
/// @dev Calculate the amount of slashing to apply to the staker's shares
function _getSlashingFactor(
address staker,
IStrategy strategy,
uint64 operatorMaxMagnitude
) internal view returns (uint256) {
if (strategy == beaconChainETHStrategy) {
uint64 beaconChainSlashingFactor = eigenPodManager.beaconChainSlashingFactor(staker);
return operatorMaxMagnitude.mulWad(beaconChainSlashingFactor);
}
return operatorMaxMagnitude;
}
/// @dev Calculate the amount of slashing to apply to the staker's shares across multiple strategies
function _getSlashingFactors(
address staker,
address operator,
IStrategy[] memory strategies
) internal view returns (uint256[] memory) {
uint256[] memory slashingFactors = new uint256[](strategies.length);
uint64[] memory maxMagnitudes = allocationManager.getMaxMagnitudes(operator, strategies);
for (uint256 i = 0; i < strategies.length; i++) {
slashingFactors[i] = _getSlashingFactor(staker, strategies[i], maxMagnitudes[i]);
}
return slashingFactors;
}
/// @dev Calculate the amount of slashing to apply to the staker's shares across multiple strategies
/// Note: specifically checks the operator's magnitude at a prior block, used for completing withdrawals
function _getSlashingFactorsAtBlock(
address staker,
address operator,
IStrategy[] memory strategies,
uint32 blockNumber
) internal view returns (uint256[] memory) {
uint256[] memory slashingFactors = new uint256[](strategies.length);
uint64[] memory maxMagnitudes = allocationManager.getMaxMagnitudesAtBlock({
operator: operator,
strategies: strategies,
blockNumber: blockNumber
});
for (uint256 i = 0; i < strategies.length; i++) {
slashingFactors[i] = _getSlashingFactor(staker, strategies[i], maxMagnitudes[i]);
}
return slashingFactors;
}
/**
* @dev Calculate amount of slashable shares that would be slashed from the queued withdrawals from an operator for a strategy
* given the previous maxMagnitude and the new maxMagnitude.
* Note: To get the total amount of slashable shares in the queue withdrawable, set newMaxMagnitude to 0 and prevMaxMagnitude
* is the current maxMagnitude of the operator.
*/
function _getSlashableSharesInQueue(
address operator,
IStrategy strategy,
uint64 prevMaxMagnitude,
uint64 newMaxMagnitude
) internal view returns (uint256) {
// We want ALL shares added to the withdrawal queue in the window [block.number - MIN_WITHDRAWAL_DELAY_BLOCKS, block.number]
//
// To get this, we take the current shares in the withdrawal queue and subtract the number of shares
// that were in the queue before MIN_WITHDRAWAL_DELAY_BLOCKS.
uint256 curQueuedScaledShares = _cumulativeScaledSharesHistory[operator][strategy].latest();
uint256 prevQueuedScaledShares = _cumulativeScaledSharesHistory[operator][strategy].upperLookup({
key: uint32(block.number) - MIN_WITHDRAWAL_DELAY_BLOCKS - 1
});
// The difference between these values is the number of scaled shares that entered the withdrawal queue
// less than or equal to MIN_WITHDRAWAL_DELAY_BLOCKS ago. These shares are still slashable.
uint256 scaledSharesAdded = curQueuedScaledShares - prevQueuedScaledShares;
return SlashingLib.scaleForBurning({
scaledShares: scaledSharesAdded,
prevMaxMagnitude: prevMaxMagnitude,
newMaxMagnitude: newMaxMagnitude
});
}
/// @dev Add to the cumulative withdrawn scaled shares from an operator for a given strategy
function _addQueuedSlashableShares(address operator, IStrategy strategy, uint256 scaledShares) internal {
if (strategy != beaconChainETHStrategy) {
uint256 currCumulativeScaledShares = _cumulativeScaledSharesHistory[operator][strategy].latest();
_cumulativeScaledSharesHistory[operator][strategy].push({
key: uint32(block.number),
value: currCumulativeScaledShares + scaledShares
});
}
}
/// @dev Depending on the strategy used, determine which ShareManager contract to make external calls to
function _getShareManager(
IStrategy strategy
) internal view returns (IShareManager) {
return strategy == beaconChainETHStrategy
? IShareManager(address(eigenPodManager))
: IShareManager(address(strategyManager));
}
/**
*
* VIEW FUNCTIONS
*
*/
/// @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 delegationApprover(
address operator
) public view returns (address) {
return _operatorDetails[operator].delegationApprover;
}
/// @inheritdoc IDelegationManager
function depositScalingFactor(address staker, IStrategy strategy) external view returns (uint256) {
return _depositScalingFactor[staker][strategy].scalingFactor();
}
/// @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 getOperatorsShares(
address[] memory operators,
IStrategy[] memory strategies
) public view returns (uint256[][] memory) {
uint256[][] memory shares = new uint256[][](operators.length);
for (uint256 i = 0; i < operators.length; ++i) {
shares[i] = getOperatorShares(operators[i], strategies);
}
return shares;
}
/// @inheritdoc IDelegationManager
function getSlashableSharesInQueue(address operator, IStrategy strategy) public view returns (uint256) {
uint64 maxMagnitude = allocationManager.getMaxMagnitude(operator, strategy);
// Return amount of slashable scaled shares remaining
return _getSlashableSharesInQueue({
operator: operator,
strategy: strategy,
prevMaxMagnitude: maxMagnitude,
newMaxMagnitude: 0
});
}
/// @inheritdoc IDelegationManager
function getWithdrawableShares(
address staker,
IStrategy[] memory strategies
) public view returns (uint256[] memory withdrawableShares, uint256[] memory depositShares) {
withdrawableShares = new uint256[](strategies.length);
depositShares = new uint256[](strategies.length);
// Get the slashing factors for the staker/operator/strategies
address operator = delegatedTo[staker];
uint256[] memory slashingFactors = _getSlashingFactors(staker, operator, strategies);
for (uint256 i = 0; i < strategies.length; ++i) {
IShareManager shareManager = _getShareManager(strategies[i]);
depositShares[i] = shareManager.stakerDepositShares(staker, strategies[i]);
// Calculate the withdrawable shares based on the slashing factor
DepositScalingFactor memory dsf = _depositScalingFactor[staker][strategies[i]];
withdrawableShares[i] = dsf.calcWithdrawable(depositShares[i], slashingFactors[i]);
}
return (withdrawableShares, depositShares);
}
/// @inheritdoc IDelegationManager
function getDepositedShares(
address staker
) public view returns (IStrategy[] memory, uint256[] memory) {
// Get a list of the staker's deposited strategies/shares in the strategy manager
(IStrategy[] memory tokenStrategies, uint256[] memory tokenDeposits) = strategyManager.getDeposits(staker);
// If the staker has no beacon chain ETH shares, return any shares from the strategy manager
uint256 podOwnerShares = eigenPodManager.stakerDepositShares(staker, beaconChainETHStrategy);
if (podOwnerShares == 0) {
return (tokenStrategies, tokenDeposits);
}
// Allocate extra space for beaconChainETHStrategy and shares
IStrategy[] memory strategies = new IStrategy[](tokenStrategies.length + 1);
uint256[] memory shares = new uint256[](tokenStrategies.length + 1);
strategies[tokenStrategies.length] = beaconChainETHStrategy;
shares[tokenStrategies.length] = podOwnerShares;
// Copy any strategy manager shares to complete array
for (uint256 i = 0; i < tokenStrategies.length; i++) {
strategies[i] = tokenStrategies[i];
shares[i] = tokenDeposits[i];
}
return (strategies, shares);
}
/// @inheritdoc IDelegationManager
function getQueuedWithdrawal(
bytes32 withdrawalRoot
) external view returns (Withdrawal memory) {
return queuedWithdrawals[withdrawalRoot];
}
/// @inheritdoc IDelegationManager
function getQueuedWithdrawals(
address staker
) external view returns (Withdrawal[] memory withdrawals, uint256[][] memory shares) {
bytes32[] memory withdrawalRoots = getQueuedWithdrawalRoots(staker);
uint256 totalQueued = withdrawalRoots.length;
withdrawals = new Withdrawal[](totalQueued);
shares = new uint256[][](totalQueued);
address operator = delegatedTo[staker];
for (uint256 i; i < totalQueued; ++i) {
withdrawals[i] = queuedWithdrawals[withdrawalRoots[i]];
shares[i] = new uint256[](withdrawals[i].strategies.length);
uint32 slashableUntil = withdrawals[i].startBlock + MIN_WITHDRAWAL_DELAY_BLOCKS;
uint256[] memory slashingFactors;
// If slashableUntil block is in the past, read the slashing factors at that block
// Otherwise read the current slashing factors. Note that if the slashableUntil block is the current block
// or in the future then the slashing factors are still subject to change before the withdrawal is completable
// and the shares withdrawn to be less
if (slashableUntil < uint32(block.number)) {
slashingFactors = _getSlashingFactorsAtBlock({
staker: staker,
operator: operator,
strategies: withdrawals[i].strategies,
blockNumber: slashableUntil
});
} else {
slashingFactors =
_getSlashingFactors({staker: staker, operator: operator, strategies: withdrawals[i].strategies});
}
for (uint256 j; j < withdrawals[i].strategies.length; ++j) {
shares[i][j] = SlashingLib.scaleForCompleteWithdrawal({
scaledShares: withdrawals[i].scaledShares[j],
slashingFactor: slashingFactors[j]
});
}
}
}
/// @inheritdoc IDelegationManager
function getQueuedWithdrawalRoots(
address staker
) public view returns (bytes32[] memory) {
return _stakerQueuedWithdrawalRoots[staker].values();
}
/// @inheritdoc IDelegationManager
function convertToDepositShares(
address staker,
IStrategy[] memory strategies,
uint256[] memory withdrawableShares
) external view returns (uint256[] memory) {
// Get the slashing factors for the staker/operator/strategies
address operator = delegatedTo[staker];
uint256[] memory slashingFactors = _getSlashingFactors(staker, operator, strategies);
// Calculate the deposit shares based on the slashing factor
uint256[] memory depositShares = new uint256[](strategies.length);
for (uint256 i = 0; i < strategies.length; ++i) {
DepositScalingFactor memory dsf = _depositScalingFactor[staker][strategies[i]];
depositShares[i] = dsf.calcDepositShares(withdrawableShares[i], slashingFactors[i]);
}
return depositShares;
}
/// @inheritdoc IDelegationManager
function calculateWithdrawalRoot(
Withdrawal memory withdrawal
) public pure returns (bytes32) {
return keccak256(abi.encode(withdrawal));
}
/// @inheritdoc IDelegationManager
function minWithdrawalDelayBlocks() external view returns (uint32) {
return MIN_WITHDRAWAL_DELAY_BLOCKS;
}
/// @inheritdoc IDelegationManager
function calculateDelegationApprovalDigestHash(
address staker,
address operator,
address approver,
bytes32 approverSalt,
uint256 expiry
) public view returns (bytes32) {
/// forgefmt: disable-next-item