-
Notifications
You must be signed in to change notification settings - Fork 186
/
Lido.sol
765 lines (658 loc) · 31.1 KB
/
Lido.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
// SPDX-FileCopyrightText: 2020 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
/* See contracts/COMPILERS.md */
pragma solidity 0.4.24;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "@aragon/os/contracts/lib/math/SafeMath64.sol";
import "@aragon/os/contracts/common/IsContract.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "./interfaces/ILido.sol";
import "./interfaces/INodeOperatorsRegistry.sol";
import "./interfaces/IDepositContract.sol";
import "./StETH.sol";
/**
* @title Liquid staking pool implementation
*
* Lido is an Ethereum 2.0 liquid staking protocol solving the problem of frozen staked Ethers
* until transfers become available in Ethereum 2.0.
* Whitepaper: https://lido.fi/static/Lido:Ethereum-Liquid-Staking.pdf
*
* NOTE: the code below assumes moderate amount of node operators, e.g. up to 50.
*
* Since balances of all token holders change when the amount of total pooled Ether
* changes, this token cannot fully implement ERC20 standard: it only emits `Transfer`
* events upon explicit transfer between holders. In contrast, when Lido oracle reports
* rewards, no Transfer events are generated: doing so would require emitting an event
* for each token holder and thus running an unbounded loop.
*/
contract Lido is ILido, IsContract, StETH, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
using UnstructuredStorage for bytes32;
/// ACL
bytes32 constant public PAUSE_ROLE = keccak256("PAUSE_ROLE");
bytes32 constant public MANAGE_FEE = keccak256("MANAGE_FEE");
bytes32 constant public MANAGE_WITHDRAWAL_KEY = keccak256("MANAGE_WITHDRAWAL_KEY");
bytes32 constant public SET_ORACLE = keccak256("SET_ORACLE");
bytes32 constant public BURN_ROLE = keccak256("BURN_ROLE");
bytes32 constant public SET_TREASURY = keccak256("SET_TREASURY");
bytes32 constant public SET_INSURANCE_FUND = keccak256("SET_INSURANCE_FUND");
bytes32 constant public DEPOSIT_ROLE = keccak256("DEPOSIT_ROLE");
uint256 constant public PUBKEY_LENGTH = 48;
uint256 constant public WITHDRAWAL_CREDENTIALS_LENGTH = 32;
uint256 constant public SIGNATURE_LENGTH = 96;
uint256 constant public DEPOSIT_SIZE = 32 ether;
uint256 internal constant DEPOSIT_AMOUNT_UNIT = 1000000000 wei;
/// @dev default value for maximum number of Ethereum 2.0 validators registered in a single depositBufferedEther call
uint256 internal constant DEFAULT_MAX_DEPOSITS_PER_CALL = 150;
bytes32 internal constant FEE_POSITION = keccak256("lido.Lido.fee");
bytes32 internal constant TREASURY_FEE_POSITION = keccak256("lido.Lido.treasuryFee");
bytes32 internal constant INSURANCE_FEE_POSITION = keccak256("lido.Lido.insuranceFee");
bytes32 internal constant NODE_OPERATORS_FEE_POSITION = keccak256("lido.Lido.nodeOperatorsFee");
bytes32 internal constant DEPOSIT_CONTRACT_POSITION = keccak256("lido.Lido.depositContract");
bytes32 internal constant ORACLE_POSITION = keccak256("lido.Lido.oracle");
bytes32 internal constant NODE_OPERATORS_REGISTRY_POSITION = keccak256("lido.Lido.nodeOperatorsRegistry");
bytes32 internal constant TREASURY_POSITION = keccak256("lido.Lido.treasury");
bytes32 internal constant INSURANCE_FUND_POSITION = keccak256("lido.Lido.insuranceFund");
/// @dev amount of Ether (on the current Ethereum side) buffered on this smart contract balance
bytes32 internal constant BUFFERED_ETHER_POSITION = keccak256("lido.Lido.bufferedEther");
/// @dev number of deposited validators (incrementing counter of deposit operations).
bytes32 internal constant DEPOSITED_VALIDATORS_POSITION = keccak256("lido.Lido.depositedValidators");
/// @dev total amount of Beacon-side Ether (sum of all the balances of Lido validators)
bytes32 internal constant BEACON_BALANCE_POSITION = keccak256("lido.Lido.beaconBalance");
/// @dev number of Lido's validators available in the Beacon state
bytes32 internal constant BEACON_VALIDATORS_POSITION = keccak256("lido.Lido.beaconValidators");
/// @dev Credentials which allows the DAO to withdraw Ether on the 2.0 side
bytes32 internal constant WITHDRAWAL_CREDENTIALS_POSITION = keccak256("lido.Lido.withdrawalCredentials");
/**
* @dev As AragonApp, Lido contract must be initialized with following variables:
* @param depositContract official ETH2 Deposit contract
* @param _oracle oracle contract
* @param _operators instance of Node Operators Registry
*/
function initialize(
IDepositContract depositContract,
address _oracle,
INodeOperatorsRegistry _operators,
address _treasury,
address _insuranceFund
)
public onlyInit
{
_setDepositContract(depositContract);
_setOracle(_oracle);
_setOperators(_operators);
_setTreasury(_treasury);
_setInsuranceFund(_insuranceFund);
initialized();
}
/**
* @notice Send funds to the pool
* @dev Users are able to submit their funds by transacting to the fallback function.
* Unlike vanilla Eth2.0 Deposit contract, accepting only 32-Ether transactions, Lido
* accepts payments of any size. Submitted Ethers are stored in Buffer until someone calls
* depositBufferedEther() and pushes them to the ETH2 Deposit contract.
*/
function() external payable {
// protection against accidental submissions by calling non-existent function
require(msg.data.length == 0, "NON_EMPTY_DATA");
_submit(0);
}
/**
* @notice Send funds to the pool with optional _referral parameter
* @dev This function is alternative way to submit funds. Supports optional referral address.
* @return Amount of StETH shares generated
*/
function submit(address _referral) external payable returns (uint256) {
return _submit(_referral);
}
/**
* @notice Deposits buffered ethers to the official DepositContract.
* @dev This function is separated from submit() to reduce the cost of sending funds.
*/
function depositBufferedEther() external auth(DEPOSIT_ROLE) {
return _depositBufferedEther(DEFAULT_MAX_DEPOSITS_PER_CALL);
}
/**
* @notice Deposits buffered ethers to the official DepositContract, making no more than `_maxDeposits` deposit calls.
* @dev This function is separated from submit() to reduce the cost of sending funds.
*/
function depositBufferedEther(uint256 _maxDeposits) external auth(DEPOSIT_ROLE) {
return _depositBufferedEther(_maxDeposits);
}
function burnShares(address _account, uint256 _sharesAmount)
external
authP(BURN_ROLE, arr(_account, _sharesAmount))
returns (uint256 newTotalShares)
{
return _burnShares(_account, _sharesAmount);
}
/**
* @notice Stop pool routine operations
*/
function stop() external auth(PAUSE_ROLE) {
_stop();
}
/**
* @notice Resume pool routine operations
*/
function resume() external auth(PAUSE_ROLE) {
_resume();
}
/**
* @notice Set fee rate to `_feeBasisPoints` basis points. The fees are accrued when oracles report staking results
* @param _feeBasisPoints Fee rate, in basis points
*/
function setFee(uint16 _feeBasisPoints) external auth(MANAGE_FEE) {
_setBPValue(FEE_POSITION, _feeBasisPoints);
emit FeeSet(_feeBasisPoints);
}
/**
* @notice Set fee distribution: `_treasuryFeeBasisPoints` basis points go to the treasury, `_insuranceFeeBasisPoints` basis points go to the insurance fund, `_operatorsFeeBasisPoints` basis points go to node operators. The sum has to be 10 000.
*/
function setFeeDistribution(
uint16 _treasuryFeeBasisPoints,
uint16 _insuranceFeeBasisPoints,
uint16 _operatorsFeeBasisPoints
)
external auth(MANAGE_FEE)
{
require(
10000 == uint256(_treasuryFeeBasisPoints)
.add(uint256(_insuranceFeeBasisPoints))
.add(uint256(_operatorsFeeBasisPoints)),
"FEES_DONT_ADD_UP"
);
_setBPValue(TREASURY_FEE_POSITION, _treasuryFeeBasisPoints);
_setBPValue(INSURANCE_FEE_POSITION, _insuranceFeeBasisPoints);
_setBPValue(NODE_OPERATORS_FEE_POSITION, _operatorsFeeBasisPoints);
emit FeeDistributionSet(_treasuryFeeBasisPoints, _insuranceFeeBasisPoints, _operatorsFeeBasisPoints);
}
/**
* @notice Set authorized oracle contract address to `_oracle`
* @dev Contract specified here is allowed to make periodical updates of beacon states
* by calling pushBeacon.
* @param _oracle oracle contract
*/
function setOracle(address _oracle) external auth(SET_ORACLE) {
_setOracle(_oracle);
}
/**
* @notice Set treasury contract address to `_treasury`
* @dev Contract specified here is used to accumulate the protocol treasury fee.
* @param _treasury contract which accumulates treasury fee.
*/
function setTreasury(address _treasury) external auth(SET_TREASURY) {
_setTreasury(_treasury);
}
/**
* @notice Set insuranceFund contract address to `_insuranceFund`
* @dev Contract specified here is used to accumulate the protocol insurance fee.
* @param _insuranceFund contract which accumulates insurance fee.
*/
function setInsuranceFund(address _insuranceFund) external auth(SET_INSURANCE_FUND) {
_setInsuranceFund(_insuranceFund);
}
/**
* @notice Set credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched to `_withdrawalCredentials`
* @dev Note that setWithdrawalCredentials discards all unused signing keys as the signatures are invalidated.
* @param _withdrawalCredentials hash of withdrawal multisignature key as accepted by
* the deposit_contract.deposit function
*/
function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external auth(MANAGE_WITHDRAWAL_KEY) {
WITHDRAWAL_CREDENTIALS_POSITION.setStorageBytes32(_withdrawalCredentials);
getOperators().trimUnusedKeys();
emit WithdrawalCredentialsSet(_withdrawalCredentials);
}
/**
* @notice Issues withdrawal request. Not implemented.
* @param _amount Amount of StETH to withdraw
* @param _pubkeyHash Receiving address
*/
function withdraw(uint256 _amount, bytes32 _pubkeyHash) external whenNotStopped { /* solhint-disable-line no-unused-vars */
//will be upgraded to an actual implementation when withdrawals are enabled (Phase 1.5 or 2 of Eth2 launch, likely late 2021 or 2022).
//at the moment withdrawals are not possible in the beacon chain and there's no workaround
revert("NOT_IMPLEMENTED_YET");
}
/**
* @notice Updates the number of Lido-controlled keys in the beacon validators set and their total balance.
* @dev periodically called by the Oracle contract
* @param _beaconValidators number of Lido's keys in the beacon state
* @param _beaconBalance simmarized balance of Lido-controlled keys in wei
*/
function pushBeacon(uint256 _beaconValidators, uint256 _beaconBalance) external whenNotStopped {
require(msg.sender == getOracle(), "APP_AUTH_FAILED");
uint256 depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
require(_beaconValidators <= depositedValidators, "REPORTED_MORE_DEPOSITED");
uint256 beaconValidators = BEACON_VALIDATORS_POSITION.getStorageUint256();
// Since the calculation of funds in the ingress queue is based on the number of validators
// that are in a transient state (deposited but not seen on beacon yet), we can't decrease the previously
// reported number (we'll be unable to figure out who is in the queue and count them).
// See LIP-1 for details https://github.com/lidofinance/lido-improvement-proposals/blob/develop/LIPS/lip-1.md
require(_beaconValidators >= beaconValidators, "REPORTED_LESS_VALIDATORS");
uint256 appearedValidators = _beaconValidators.sub(beaconValidators);
// RewardBase is the amount of money that is not included in the reward calculation
// Just appeared validators * 32 added to the previously reported beacon balance
uint256 rewardBase = (appearedValidators.mul(DEPOSIT_SIZE)).add(BEACON_BALANCE_POSITION.getStorageUint256());
// Save the current beacon balance and validators to
// calcuate rewards on the next push
BEACON_BALANCE_POSITION.setStorageUint256(_beaconBalance);
BEACON_VALIDATORS_POSITION.setStorageUint256(_beaconValidators);
if (_beaconBalance > rewardBase) {
uint256 rewards = _beaconBalance.sub(rewardBase);
distributeRewards(rewards);
}
}
/**
* @notice Send funds to recovery Vault. Overrides default AragonApp behaviour.
* @param _token Token to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), "RECOVER_DISALLOWED");
address vault = getRecoveryVault();
require(isContract(vault), "RECOVER_VAULT_NOT_CONTRACT");
uint256 balance;
if (_token == ETH) {
balance = _getUnaccountedEther();
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
// safeTransfer comes from overriden default implementation
require(token.safeTransfer(vault, balance), "RECOVER_TOKEN_TRANSFER_FAILED");
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @notice Returns staking rewards fee rate
*/
function getFee() external view returns (uint16 feeBasisPoints) {
return _getFee();
}
/**
* @notice Returns fee distribution proportion
*/
function getFeeDistribution()
external
view
returns (
uint16 treasuryFeeBasisPoints,
uint16 insuranceFeeBasisPoints,
uint16 operatorsFeeBasisPoints
)
{
return _getFeeDistribution();
}
/**
* @notice Returns current credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched
*/
function getWithdrawalCredentials() public view returns (bytes32) {
return WITHDRAWAL_CREDENTIALS_POSITION.getStorageBytes32();
}
/**
* @notice Get the amount of Ether temporary buffered on this contract balance
* @dev Buffered balance is kept on the contract from the moment the funds are received from user
* until the moment they are actually sent to the official Deposit contract.
* @return uint256 of buffered funds in wei
*/
function getBufferedEther() external view returns (uint256) {
return _getBufferedEther();
}
/**
* @notice Gets deposit contract handle
*/
function getDepositContract() public view returns (IDepositContract) {
return IDepositContract(DEPOSIT_CONTRACT_POSITION.getStorageAddress());
}
/**
* @notice Gets authorized oracle address
* @return address of oracle contract
*/
function getOracle() public view returns (address) {
return ORACLE_POSITION.getStorageAddress();
}
/**
* @notice Gets node operators registry interface handle
*/
function getOperators() public view returns (INodeOperatorsRegistry) {
return INodeOperatorsRegistry(NODE_OPERATORS_REGISTRY_POSITION.getStorageAddress());
}
/**
* @notice Returns the treasury address
*/
function getTreasury() public view returns (address) {
return TREASURY_POSITION.getStorageAddress();
}
/**
* @notice Returns the insurance fund address
*/
function getInsuranceFund() public view returns (address) {
return INSURANCE_FUND_POSITION.getStorageAddress();
}
/**
* @notice Returns the key values related to Beacon-side
* @return depositedValidators - number of deposited validators
* @return beaconValidators - number of Lido's validators visible in the Beacon state, reported by oracles
* @return beaconBalance - total amount of Beacon-side Ether (sum of all the balances of Lido validators)
*/
function getBeaconStat() public view returns (uint256 depositedValidators, uint256 beaconValidators, uint256 beaconBalance) {
depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
beaconValidators = BEACON_VALIDATORS_POSITION.getStorageUint256();
beaconBalance = BEACON_BALANCE_POSITION.getStorageUint256();
}
/**
* @dev Sets the address of Deposit contract
* @param _contract the address of Deposit contract
*/
function _setDepositContract(IDepositContract _contract) internal {
require(isContract(address(_contract)), "NOT_A_CONTRACT");
DEPOSIT_CONTRACT_POSITION.setStorageAddress(address(_contract));
}
/**
* @dev Internal function to set authorized oracle address
* @param _oracle oracle contract
*/
function _setOracle(address _oracle) internal {
require(isContract(_oracle), "NOT_A_CONTRACT");
ORACLE_POSITION.setStorageAddress(_oracle);
}
/**
* @dev Internal function to set node operator registry address
* @param _r registry of node operators
*/
function _setOperators(INodeOperatorsRegistry _r) internal {
require(isContract(_r), "NOT_A_CONTRACT");
NODE_OPERATORS_REGISTRY_POSITION.setStorageAddress(_r);
}
function _setTreasury(address _treasury) internal {
require(_treasury != address(0), "SET_TREASURY_ZERO_ADDRESS");
TREASURY_POSITION.setStorageAddress(_treasury);
}
function _setInsuranceFund(address _insuranceFund) internal {
require(_insuranceFund != address(0), "SET_INSURANCE_FUND_ZERO_ADDRESS");
INSURANCE_FUND_POSITION.setStorageAddress(_insuranceFund);
}
/**
* @dev Process user deposit, mints liquid tokens and increase the pool buffer
* @param _referral address of referral.
* @return amount of StETH shares generated
*/
function _submit(address _referral) internal whenNotStopped returns (uint256) {
address sender = msg.sender;
uint256 deposit = msg.value;
require(deposit != 0, "ZERO_DEPOSIT");
uint256 sharesAmount = getSharesByPooledEth(deposit);
if (sharesAmount == 0) {
// totalControlledEther is 0: either the first-ever deposit or complete slashing
// assume that shares correspond to Ether 1-to-1
sharesAmount = deposit;
}
_mintShares(sender, sharesAmount);
_submitted(sender, deposit, _referral);
_emitTransferAfterMintingShares(sender, sharesAmount);
return sharesAmount;
}
/**
* @dev Emits an {Transfer} event where from is 0 address. Indicates mint events.
*/
function _emitTransferAfterMintingShares(address _to, uint256 _sharesAmount) internal {
emit Transfer(address(0), _to, getPooledEthByShares(_sharesAmount));
}
/**
* @dev Deposits buffered eth to the DepositContract and assigns chunked deposits to node operators
*/
function _depositBufferedEther(uint256 _maxDeposits) internal whenNotStopped {
uint256 buffered = _getBufferedEther();
if (buffered >= DEPOSIT_SIZE) {
uint256 unaccounted = _getUnaccountedEther();
uint256 numDeposits = buffered.div(DEPOSIT_SIZE);
_markAsUnbuffered(_ETH2Deposit(numDeposits < _maxDeposits ? numDeposits : _maxDeposits));
assert(_getUnaccountedEther() == unaccounted);
}
}
/**
* @dev Performs deposits to the ETH 2.0 side
* @param _numDeposits Number of deposits to perform
* @return actually deposited Ether amount
*/
function _ETH2Deposit(uint256 _numDeposits) internal returns (uint256) {
(bytes memory pubkeys, bytes memory signatures) = getOperators().assignNextSigningKeys(_numDeposits);
if (pubkeys.length == 0) {
return 0;
}
require(pubkeys.length.mod(PUBKEY_LENGTH) == 0, "REGISTRY_INCONSISTENT_PUBKEYS_LEN");
require(signatures.length.mod(SIGNATURE_LENGTH) == 0, "REGISTRY_INCONSISTENT_SIG_LEN");
uint256 numKeys = pubkeys.length.div(PUBKEY_LENGTH);
require(numKeys == signatures.length.div(SIGNATURE_LENGTH), "REGISTRY_INCONSISTENT_SIG_COUNT");
for (uint256 i = 0; i < numKeys; ++i) {
bytes memory pubkey = BytesLib.slice(pubkeys, i * PUBKEY_LENGTH, PUBKEY_LENGTH);
bytes memory signature = BytesLib.slice(signatures, i * SIGNATURE_LENGTH, SIGNATURE_LENGTH);
_stake(pubkey, signature);
}
DEPOSITED_VALIDATORS_POSITION.setStorageUint256(
DEPOSITED_VALIDATORS_POSITION.getStorageUint256().add(numKeys)
);
return numKeys.mul(DEPOSIT_SIZE);
}
/**
* @dev Invokes a deposit call to the official Deposit contract
* @param _pubkey Validator to stake for
* @param _signature Signature of the deposit call
*/
function _stake(bytes memory _pubkey, bytes memory _signature) internal {
bytes32 withdrawalCredentials = getWithdrawalCredentials();
require(withdrawalCredentials != 0, "EMPTY_WITHDRAWAL_CREDENTIALS");
uint256 value = DEPOSIT_SIZE;
// The following computations and Merkle tree-ization will make official Deposit contract happy
uint256 depositAmount = value.div(DEPOSIT_AMOUNT_UNIT);
assert(depositAmount.mul(DEPOSIT_AMOUNT_UNIT) == value); // properly rounded
// Compute deposit data root (`DepositData` hash tree root) according to deposit_contract.sol
bytes32 pubkeyRoot = sha256(_pad64(_pubkey));
bytes32 signatureRoot = sha256(
abi.encodePacked(
sha256(BytesLib.slice(_signature, 0, 64)),
sha256(_pad64(BytesLib.slice(_signature, 64, SIGNATURE_LENGTH.sub(64))))
)
);
bytes32 depositDataRoot = sha256(
abi.encodePacked(
sha256(abi.encodePacked(pubkeyRoot, withdrawalCredentials)),
sha256(abi.encodePacked(_toLittleEndian64(depositAmount), signatureRoot))
)
);
uint256 targetBalance = address(this).balance.sub(value);
getDepositContract().deposit.value(value)(
_pubkey, abi.encodePacked(withdrawalCredentials), _signature, depositDataRoot);
require(address(this).balance == targetBalance, "EXPECTING_DEPOSIT_TO_HAPPEN");
}
/**
* @dev Distributes rewards by minting and distributing corresponding amount of liquid tokens.
* @param _totalRewards Total rewards accrued on the Ethereum 2.0 side in wei
*/
function distributeRewards(uint256 _totalRewards) internal {
// We need to take a defined percentage of the reported reward as a fee, and we do
// this by minting new token shares and assigning them to the fee recipients (see
// StETH docs for the explanation of the shares mechanics). The staking rewards fee
// is defined in basis points (1 basis point is equal to 0.01%, 10000 is 100%).
//
// Since we've increased totalPooledEther by _totalRewards (which is already
// performed by the time this function is called), the combined cost of all holders'
// shares has became _totalRewards StETH tokens more, effectively splitting the reward
// between each token holder proportionally to their token share.
//
// Now we want to mint new shares to the fee recipient, so that the total cost of the
// newly-minted shares exactly corresponds to the fee taken:
//
// shares2mint * newShareCost = (_totalRewards * feeBasis) / 10000
// newShareCost = newTotalPooledEther / (prevTotalShares + shares2mint)
//
// which follows to:
//
// _totalRewards * feeBasis * prevTotalShares
// shares2mint = --------------------------------------------------------------
// (newTotalPooledEther * 10000) - (feeBasis * _totalRewards)
//
// The effect is that the given percentage of the reward goes to the fee recipient, and
// the rest of the reward is distributed between token holders proportionally to their
// token shares.
uint256 feeBasis = _getFee();
uint256 shares2mint = (
_totalRewards.mul(feeBasis).mul(_getTotalShares())
.div(
_getTotalPooledEther().mul(10000)
.sub(feeBasis.mul(_totalRewards))
)
);
// Mint the calculated amount of shares to this contract address. This will reduce the
// balances of the holders, as if the fee was taken in parts from each of them.
_mintShares(address(this), shares2mint);
(,uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints) = _getFeeDistribution();
uint256 toInsuranceFund = shares2mint.mul(insuranceFeeBasisPoints).div(10000);
address insuranceFund = getInsuranceFund();
_transferShares(address(this), insuranceFund, toInsuranceFund);
_emitTransferAfterMintingShares(insuranceFund, toInsuranceFund);
uint256 distributedToOperatorsShares = _distributeNodeOperatorsReward(
shares2mint.mul(operatorsFeeBasisPoints).div(10000)
);
// Transfer the rest of the fee to treasury
uint256 toTreasury = shares2mint.sub(toInsuranceFund).sub(distributedToOperatorsShares);
address treasury = getTreasury();
_transferShares(address(this), treasury, toTreasury);
_emitTransferAfterMintingShares(treasury, toTreasury);
}
function _distributeNodeOperatorsReward(uint256 _sharesToDistribute) internal returns (uint256 distributed) {
(address[] memory recipients, uint256[] memory shares) = getOperators().getRewardsDistribution(_sharesToDistribute);
assert(recipients.length == shares.length);
distributed = 0;
for (uint256 idx = 0; idx < recipients.length; ++idx) {
_transferShares(
address(this),
recipients[idx],
shares[idx]
);
_emitTransferAfterMintingShares(recipients[idx], shares[idx]);
distributed = distributed.add(shares[idx]);
}
}
/**
* @dev Records a deposit made by a user with optional referral
* @param _sender sender's address
* @param _value Deposit value in wei
* @param _referral address of the referral
*/
function _submitted(address _sender, uint256 _value, address _referral) internal {
BUFFERED_ETHER_POSITION.setStorageUint256(_getBufferedEther().add(_value));
emit Submitted(_sender, _value, _referral);
}
/**
* @dev Records a deposit to the deposit_contract.deposit function.
* @param _amount Total amount deposited to the ETH 2.0 side
*/
function _markAsUnbuffered(uint256 _amount) internal {
BUFFERED_ETHER_POSITION.setStorageUint256(
BUFFERED_ETHER_POSITION.getStorageUint256().sub(_amount));
emit Unbuffered(_amount);
}
/**
* @dev Write a value nominated in basis points
*/
function _setBPValue(bytes32 _slot, uint16 _value) internal {
require(_value <= 10000, "VALUE_OVER_100_PERCENT");
_slot.setStorageUint256(uint256(_value));
}
/**
* @dev Returns staking rewards fee rate
*/
function _getFee() internal view returns (uint16) {
return _readBPValue(FEE_POSITION);
}
/**
* @dev Returns fee distribution proportion
*/
function _getFeeDistribution() internal view
returns (uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints)
{
treasuryFeeBasisPoints = _readBPValue(TREASURY_FEE_POSITION);
insuranceFeeBasisPoints = _readBPValue(INSURANCE_FEE_POSITION);
operatorsFeeBasisPoints = _readBPValue(NODE_OPERATORS_FEE_POSITION);
}
/**
* @dev Read a value nominated in basis points
*/
function _readBPValue(bytes32 _slot) internal view returns (uint16) {
uint256 v = _slot.getStorageUint256();
assert(v <= 10000);
return uint16(v);
}
/**
* @dev Gets the amount of Ether temporary buffered on this contract balance
*/
function _getBufferedEther() internal view returns (uint256) {
uint256 buffered = BUFFERED_ETHER_POSITION.getStorageUint256();
assert(address(this).balance >= buffered);
return buffered;
}
/**
* @dev Gets unaccounted (excess) Ether on this contract balance
*/
function _getUnaccountedEther() internal view returns (uint256) {
return address(this).balance.sub(_getBufferedEther());
}
/**
* @dev Calculates and returns the total base balance (multiple of 32) of validators in transient state,
* i.e. submitted to the official Deposit contract but not yet visible in the beacon state.
* @return transient balance in wei (1e-18 Ether)
*/
function _getTransientBalance() internal view returns (uint256) {
uint256 depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
uint256 beaconValidators = BEACON_VALIDATORS_POSITION.getStorageUint256();
// beaconValidators can never be less than deposited ones.
assert(depositedValidators >= beaconValidators);
uint256 transientValidators = depositedValidators.sub(beaconValidators);
return transientValidators.mul(DEPOSIT_SIZE);
}
/**
* @dev Gets the total amount of Ether controlled by the system
* @return total balance in wei
*/
function _getTotalPooledEther() internal view returns (uint256) {
uint256 bufferedBalance = _getBufferedEther();
uint256 beaconBalance = BEACON_BALANCE_POSITION.getStorageUint256();
uint256 transientBalance = _getTransientBalance();
return bufferedBalance.add(beaconBalance).add(transientBalance);
}
/**
* @dev Padding memory array with zeroes up to 64 bytes on the right
* @param _b Memory array of size 32 .. 64
*/
function _pad64(bytes memory _b) internal pure returns (bytes memory) {
assert(_b.length >= 32 && _b.length <= 64);
if (64 == _b.length)
return _b;
bytes memory zero32 = new bytes(32);
assembly { mstore(add(zero32, 0x20), 0) }
if (32 == _b.length)
return BytesLib.concat(_b, zero32);
else
return BytesLib.concat(_b, BytesLib.slice(zero32, 0, uint256(64).sub(_b.length)));
}
/**
* @dev Converting value to little endian bytes and padding up to 32 bytes on the right
* @param _value Number less than `2**64` for compatibility reasons
*/
function _toLittleEndian64(uint256 _value) internal pure returns (uint256 result) {
result = 0;
uint256 temp_value = _value;
for (uint256 i = 0; i < 8; ++i) {
result = (result << 8) | (temp_value & 0xFF);
temp_value >>= 8;
}
assert(0 == temp_value); // fully converted
result <<= (24 * 8);
}
function to64(uint256 v) internal pure returns (uint64) {
assert(v <= uint256(uint64(-1)));
return uint64(v);
}
}