forked from Layr-Labs/eigenlayer-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
User.t.sol
467 lines (363 loc) · 19.1 KB
/
User.t.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.12;
import "forge-std/Test.sol";
import "src/contracts/core/DelegationManager.sol";
import "src/contracts/core/StrategyManager.sol";
import "src/contracts/pods/EigenPodManager.sol";
import "src/contracts/pods/EigenPod.sol";
import "src/contracts/interfaces/IDelegationManager.sol";
import "src/contracts/interfaces/IStrategy.sol";
import "src/test/integration/TimeMachine.t.sol";
import "src/test/integration/mocks/BeaconChainMock.t.sol";
interface IUserDeployer {
function delegationManager() external view returns (DelegationManager);
function strategyManager() external view returns (StrategyManager);
function eigenPodManager() external view returns (EigenPodManager);
function timeMachine() external view returns (TimeMachine);
function beaconChain() external view returns (BeaconChainMock);
}
contract User is Test {
Vm cheats = Vm(HEVM_ADDRESS);
DelegationManager delegationManager;
StrategyManager strategyManager;
EigenPodManager eigenPodManager;
TimeMachine timeMachine;
/// @dev Native restaker state vars
BeaconChainMock beaconChain;
// User's EigenPod and each of their validator indices within that pod
EigenPod public pod;
uint40[] validators;
IStrategy constant BEACONCHAIN_ETH_STRAT = IStrategy(0xbeaC0eeEeeeeEEeEeEEEEeeEEeEeeeEeeEEBEaC0);
IERC20 constant NATIVE_ETH = IERC20(0xbeaC0eeEeeeeEEeEeEEEEeeEEeEeeeEeeEEBEaC0);
uint constant GWEI_TO_WEI = 1e9;
string public NAME;
constructor(string memory name) {
IUserDeployer deployer = IUserDeployer(msg.sender);
delegationManager = deployer.delegationManager();
strategyManager = deployer.strategyManager();
eigenPodManager = deployer.eigenPodManager();
timeMachine = deployer.timeMachine();
beaconChain = deployer.beaconChain();
pod = EigenPod(payable(eigenPodManager.createPod()));
NAME = name;
}
modifier createSnapshot() virtual {
timeMachine.createSnapshot();
_;
}
receive() external payable {}
/**
* DelegationManager methods:
*/
function registerAsOperator() public createSnapshot virtual {
emit log(_name(".registerAsOperator"));
IDelegationManager.OperatorDetails memory details = IDelegationManager.OperatorDetails({
earningsReceiver: address(this),
delegationApprover: address(0),
stakerOptOutWindowBlocks: 0
});
delegationManager.registerAsOperator(details, "metadata");
}
/// @dev For each strategy/token balance, call the relevant deposit method
function depositIntoEigenlayer(IStrategy[] memory strategies, uint[] memory tokenBalances) public createSnapshot virtual {
emit log(_name(".depositIntoEigenlayer"));
for (uint i = 0; i < strategies.length; i++) {
IStrategy strat = strategies[i];
uint tokenBalance = tokenBalances[i];
if (strat == BEACONCHAIN_ETH_STRAT) {
// We're depositing via `eigenPodManager.stake`, which only accepts
// deposits of exactly 32 ether.
require(tokenBalance % 32 ether == 0, "User.depositIntoEigenlayer: balance must be multiple of 32 eth");
// For each multiple of 32 ether, deploy a new validator to the same pod
uint numValidators = tokenBalance / 32 ether;
for (uint j = 0; j < numValidators; j++) {
eigenPodManager.stake{ value: 32 ether }("", "", bytes32(0));
(uint40 newValidatorIndex, CredentialsProofs memory proofs) =
beaconChain.newValidator({
balanceWei: 32 ether,
withdrawalCreds: _podWithdrawalCredentials()
});
validators.push(newValidatorIndex);
pod.verifyWithdrawalCredentials({
oracleTimestamp: proofs.oracleTimestamp,
stateRootProof: proofs.stateRootProof,
validatorIndices: proofs.validatorIndices,
validatorFieldsProofs: proofs.validatorFieldsProofs,
validatorFields: proofs.validatorFields
});
}
} else {
IERC20 underlyingToken = strat.underlyingToken();
underlyingToken.approve(address(strategyManager), tokenBalance);
strategyManager.depositIntoStrategy(strat, underlyingToken, tokenBalance);
}
}
}
function updateBalances(IStrategy[] memory strategies, int[] memory tokenDeltas) public createSnapshot virtual {
emit log(_name(".updateBalances"));
for (uint i = 0; i < strategies.length; i++) {
IStrategy strat = strategies[i];
int delta = tokenDeltas[i];
if (strat == BEACONCHAIN_ETH_STRAT) {
// TODO - right now, we just grab the first validator
uint40 validator = getUpdatableValidator();
BalanceUpdate memory update = beaconChain.updateBalance(validator, delta);
int sharesBefore = eigenPodManager.podOwnerShares(address(this));
pod.verifyBalanceUpdates({
oracleTimestamp: update.oracleTimestamp,
validatorIndices: update.validatorIndices,
stateRootProof: update.stateRootProof,
validatorFieldsProofs: update.validatorFieldsProofs,
validatorFields: update.validatorFields
});
int sharesAfter = eigenPodManager.podOwnerShares(address(this));
emit log_named_int("pod owner shares before: ", sharesBefore);
emit log_named_int("pod owner shares after: ", sharesAfter);
} else {
uint tokens = uint(delta);
IERC20 underlyingToken = strat.underlyingToken();
underlyingToken.approve(address(strategyManager), tokens);
strategyManager.depositIntoStrategy(strat, underlyingToken, tokens);
}
}
}
/// @dev Delegate to the operator without a signature
function delegateTo(User operator) public createSnapshot virtual {
emit log_named_string(_name(".delegateTo: "), operator.NAME());
ISignatureUtils.SignatureWithExpiry memory emptySig;
delegationManager.delegateTo(address(operator), emptySig, bytes32(0));
}
/// @dev Undelegate from operator
function undelegate() public createSnapshot virtual returns(IDelegationManager.Withdrawal[] memory){
emit log(_name(".undelegate"));
IDelegationManager.Withdrawal[] memory expectedWithdrawals = _getExpectedWithdrawalStructsForStaker(address(this));
delegationManager.undelegate(address(this));
for (uint i = 0; i < expectedWithdrawals.length; i++) {
emit log("expecting withdrawal:");
emit log_named_uint("nonce: ", expectedWithdrawals[i].nonce);
emit log_named_address("strat: ", address(expectedWithdrawals[i].strategies[0]));
emit log_named_uint("shares: ", expectedWithdrawals[i].shares[0]);
}
return expectedWithdrawals;
}
/// @dev Force undelegate staker
function forceUndelegate(User staker) public createSnapshot virtual returns(IDelegationManager.Withdrawal[] memory){
emit log_named_string(_name(".forceUndelegate: "), staker.NAME());
IDelegationManager.Withdrawal[] memory expectedWithdrawals = _getExpectedWithdrawalStructsForStaker(address(staker));
delegationManager.undelegate(address(staker));
return expectedWithdrawals;
}
/// @dev Queues a single withdrawal for every share and strategy pair
function queueWithdrawals(
IStrategy[] memory strategies,
uint[] memory shares
) public createSnapshot virtual returns (IDelegationManager.Withdrawal[] memory) {
emit log(_name(".queueWithdrawals"));
address operator = delegationManager.delegatedTo(address(this));
address withdrawer = address(this);
uint nonce = delegationManager.cumulativeWithdrawalsQueued(address(this));
// Create queueWithdrawals params
IDelegationManager.QueuedWithdrawalParams[] memory params = new IDelegationManager.QueuedWithdrawalParams[](1);
params[0] = IDelegationManager.QueuedWithdrawalParams({
strategies: strategies,
shares: shares,
withdrawer: withdrawer
});
// Create Withdrawal struct using same info
IDelegationManager.Withdrawal[] memory withdrawals = new IDelegationManager.Withdrawal[](1);
withdrawals[0] = IDelegationManager.Withdrawal({
staker: address(this),
delegatedTo: operator,
withdrawer: withdrawer,
nonce: nonce,
startBlock: uint32(block.number),
strategies: strategies,
shares: shares
});
bytes32[] memory withdrawalRoots = delegationManager.queueWithdrawals(params);
// Basic sanity check - we do all other checks outside this file
assertEq(withdrawals.length, withdrawalRoots.length, "User.queueWithdrawals: length mismatch");
return (withdrawals);
}
function completeWithdrawalsAsTokens(IDelegationManager.Withdrawal[] memory withdrawals) public createSnapshot virtual returns (IERC20[][] memory) {
emit log(_name(".completeWithdrawalsAsTokens"));
IERC20[][] memory tokens = new IERC20[][](withdrawals.length);
for (uint i = 0; i < withdrawals.length; i++) {
tokens[i] = _completeQueuedWithdrawal(withdrawals[i], true);
}
return tokens;
}
function completeWithdrawalAsTokens(IDelegationManager.Withdrawal memory withdrawal) public createSnapshot virtual returns (IERC20[] memory) {
emit log(_name(".completeWithdrawalAsTokens"));
return _completeQueuedWithdrawal(withdrawal, true);
}
function completeWithdrawalsAsShares(IDelegationManager.Withdrawal[] memory withdrawals) public createSnapshot virtual returns (IERC20[][] memory) {
emit log(_name(".completeWithdrawalsAsShares"));
IERC20[][] memory tokens = new IERC20[][](withdrawals.length);
for (uint i = 0; i < withdrawals.length; i++) {
tokens[i] = _completeQueuedWithdrawal(withdrawals[i], false);
}
return tokens;
}
function completeWithdrawalAsShares(IDelegationManager.Withdrawal memory withdrawal) public createSnapshot virtual returns (IERC20[] memory) {
emit log(_name(".completeWithdrawalAsShares"));
return _completeQueuedWithdrawal(withdrawal, false);
}
function _completeQueuedWithdrawal(
IDelegationManager.Withdrawal memory withdrawal,
bool receiveAsTokens
) internal virtual returns (IERC20[] memory) {
IERC20[] memory tokens = new IERC20[](withdrawal.strategies.length);
for (uint i = 0; i < tokens.length; i++) {
IStrategy strat = withdrawal.strategies[i];
if (strat == BEACONCHAIN_ETH_STRAT) {
tokens[i] = NATIVE_ETH;
// If we're withdrawing as tokens, we need to process a withdrawal proof first
if (receiveAsTokens) {
emit log("exiting validators and processing withdrawals...");
uint numValidators = validators.length;
for (uint j = 0; j < numValidators; j++) {
emit log_named_uint("exiting validator ", j);
uint40 validatorIndex = validators[j];
BeaconWithdrawal memory proofs = beaconChain.exitValidator(validatorIndex);
uint64 withdrawableBefore = pod.withdrawableRestakedExecutionLayerGwei();
pod.verifyAndProcessWithdrawals({
oracleTimestamp: proofs.oracleTimestamp,
stateRootProof: proofs.stateRootProof,
withdrawalProofs: proofs.withdrawalProofs,
validatorFieldsProofs: proofs.validatorFieldsProofs,
validatorFields: proofs.validatorFields,
withdrawalFields: proofs.withdrawalFields
});
uint64 withdrawableAfter = pod.withdrawableRestakedExecutionLayerGwei();
emit log_named_uint("pod withdrawable before: ", withdrawableBefore);
emit log_named_uint("pod withdrawable after: ", withdrawableAfter);
}
}
} else {
tokens[i] = strat.underlyingToken();
}
}
delegationManager.completeQueuedWithdrawal(withdrawal, tokens, 0, receiveAsTokens);
return tokens;
}
function _podWithdrawalCredentials() internal view returns (bytes memory) {
return abi.encodePacked(bytes1(uint8(1)), bytes11(0), address(pod));
}
/// @notice Gets the expected withdrawals to be created when the staker is undelegated via a call to `DelegationManager.undelegate()`
/// @notice Assumes staker and withdrawer are the same and that all strategies and shares are withdrawn
function _getExpectedWithdrawalStructsForStaker(address staker) internal returns (IDelegationManager.Withdrawal[] memory) {
(IStrategy[] memory strategies, uint256[] memory shares)
= delegationManager.getDelegatableShares(staker);
IDelegationManager.Withdrawal[] memory expectedWithdrawals = new IDelegationManager.Withdrawal[](strategies.length);
address delegatedTo = delegationManager.delegatedTo(staker);
uint256 nonce = delegationManager.cumulativeWithdrawalsQueued(staker);
for (uint256 i = 0; i < strategies.length; ++i) {
IStrategy[] memory singleStrategy = new IStrategy[](1);
uint256[] memory singleShares = new uint256[](1);
singleStrategy[0] = strategies[i];
singleShares[0] = shares[i];
expectedWithdrawals[i] = IDelegationManager.Withdrawal({
staker: staker,
delegatedTo: delegatedTo,
withdrawer: staker,
nonce: (nonce + i),
startBlock: uint32(block.number),
strategies: singleStrategy,
shares: singleShares
});
}
return expectedWithdrawals;
}
function _name(string memory s) internal view returns (string memory) {
return string.concat(NAME, s);
}
function getUpdatableValidator() public view returns (uint40) {
return validators[0];
}
}
/// @notice A user contract that calls nonstandard methods (like xBySignature methods)
contract User_AltMethods is User {
mapping(bytes32 => bool) public signedHashes;
constructor(string memory name) User(name) {}
function delegateTo(User operator) public createSnapshot override {
emit log_named_string(_name(".delegateTo: "), operator.NAME());
// Create empty data
ISignatureUtils.SignatureWithExpiry memory emptySig;
uint256 expiry = type(uint256).max;
// Get signature
ISignatureUtils.SignatureWithExpiry memory stakerSignatureAndExpiry;
stakerSignatureAndExpiry.expiry = expiry;
bytes32 digestHash = delegationManager.calculateCurrentStakerDelegationDigestHash(address(this), address(operator), expiry);
stakerSignatureAndExpiry.signature = bytes(abi.encodePacked(digestHash)); // dummy sig data
// Mark hash as signed
signedHashes[digestHash] = true;
// Delegate
delegationManager.delegateToBySignature(address(this), address(operator), stakerSignatureAndExpiry, emptySig, bytes32(0));
// Mark hash as used
signedHashes[digestHash] = false;
}
function depositIntoEigenlayer(IStrategy[] memory strategies, uint[] memory tokenBalances) public createSnapshot override {
emit log(_name(".depositIntoEigenlayer"));
uint256 expiry = type(uint256).max;
for (uint i = 0; i < strategies.length; i++) {
IStrategy strat = strategies[i];
uint tokenBalance = tokenBalances[i];
if (strat == BEACONCHAIN_ETH_STRAT) {
// We're depositing via `eigenPodManager.stake`, which only accepts
// deposits of exactly 32 ether.
require(tokenBalance % 32 ether == 0, "User.depositIntoEigenlayer: balance must be multiple of 32 eth");
// For each multiple of 32 ether, deploy a new validator to the same pod
uint numValidators = tokenBalance / 32 ether;
for (uint j = 0; j < numValidators; j++) {
eigenPodManager.stake{ value: 32 ether }("", "", bytes32(0));
(uint40 newValidatorIndex, CredentialsProofs memory proofs) =
beaconChain.newValidator({
balanceWei: 32 ether,
withdrawalCreds: _podWithdrawalCredentials()
});
validators.push(newValidatorIndex);
pod.verifyWithdrawalCredentials({
oracleTimestamp: proofs.oracleTimestamp,
stateRootProof: proofs.stateRootProof,
validatorIndices: proofs.validatorIndices,
validatorFieldsProofs: proofs.validatorFieldsProofs,
validatorFields: proofs.validatorFields
});
}
} else {
// Approve token
IERC20 underlyingToken = strat.underlyingToken();
underlyingToken.approve(address(strategyManager), tokenBalance);
// Get signature
uint256 nonceBefore = strategyManager.nonces(address(this));
bytes32 structHash = keccak256(
abi.encode(strategyManager.DEPOSIT_TYPEHASH(), strat, underlyingToken, tokenBalance, nonceBefore, expiry)
);
bytes32 digestHash = keccak256(abi.encodePacked("\x19\x01", strategyManager.domainSeparator(), structHash));
bytes memory signature = bytes(abi.encodePacked(digestHash)); // dummy sig data
// Mark hash as signed
signedHashes[digestHash] = true;
// Deposit
strategyManager.depositIntoStrategyWithSignature(
strat,
underlyingToken,
tokenBalance,
address(this),
expiry,
signature
);
// Mark hash as used
signedHashes[digestHash] = false;
}
}
}
bytes4 internal constant MAGIC_VALUE = 0x1626ba7e;
function isValidSignature(bytes32 hash, bytes memory) external view returns (bytes4) {
if(signedHashes[hash]){
return MAGIC_VALUE;
} else {
return 0xffffffff;
}
}
}