/
Syndicate.sol
681 lines (544 loc) · 35.7 KB
/
Syndicate.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
pragma solidity 0.8.13;
// SPDX-License-Identifier: MIT
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { StakehouseAPI } from "@blockswaplab/stakehouse-solidity-api/contracts/StakehouseAPI.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { ISyndicateInit } from "../interfaces/ISyndicateInit.sol";
import {
ZeroAddress,
EmptyArray,
InconsistentArrayLengths,
InvalidBLSPubKey,
InvalidNumberOfCollateralizedOwners,
KnotSlashed,
FreeFloatingStakeAmountTooSmall,
KnotIsNotRegisteredWithSyndicate,
NotPriorityStaker,
KnotIsFullyStakedWithFreeFloatingSlotTokens,
InvalidStakeAmount,
KnotIsNotAssociatedWithAStakeHouse,
UnableToStakeFreeFloatingSlot,
NothingStaked,
TransferFailed,
NotCollateralizedOwnerAtIndex,
InactiveKnot,
DuplicateArrayElements,
KnotIsAlreadyRegistered,
KnotHasAlreadyBeenDeRegistered
} from "./SyndicateErrors.sol";
/// @notice Syndicate registry and funds splitter for EIP1559 execution layer transaction tips across SLOT shares
/// @dev This contract can be extended to allow lending and borrowing of time slots for borrower to redeem any revenue generated within the specified window
contract Syndicate is ISyndicateInit, Initializable, Ownable, ReentrancyGuard, StakehouseAPI {
/// @notice Emitted when the contract is initially deployed
event ContractDeployed();
/// @notice Emitted when accrued ETH per SLOT share type is updated
event UpdateAccruedETH(uint256 unprocessed);
/// @notice Emitted when new collateralized SLOT owners for a knot prompts re-calibration
event CollateralizedSLOTReCalibrated(bytes BLSPubKey);
/// @notice Emitted when a new KNOT is associated with the syndicate contract
event KNOTRegistered(bytes BLSPubKey);
/// @notice Emitted when a KNOT is de-registered from the syndicate
event KnotDeRegistered(bytes BLSPubKey);
/// @notice Emitted when a priority staker is added to the syndicate
event PriorityStakerRegistered(address indexed staker);
/// @notice Emitted when a user stakes free floating sETH tokens
event Staked(bytes BLSPubKey, uint256 amount);
/// @notice Emitted when a user unstakes free floating sETH tokens
event UnStaked(bytes BLSPubKey, uint256 amount);
/// @notice Emitted when either an sETH staker or collateralized SLOT owner claims ETH
event ETHClaimed(bytes BLSPubKey, address indexed user, address recipient, uint256 claim, bool indexed isCollateralizedClaim);
/// @notice Precision used in rewards calculations for scaling up and down
uint256 public constant PRECISION = 1e24;
/// @notice Total accrued ETH per free floating share for new and old stakers
uint256 public accumulatedETHPerFreeFloatingShare;
/// @notice Total accrued ETH for all collateralized SLOT holders per knot which is then distributed based on individual balances
uint256 public accumulatedETHPerCollateralizedSlotPerKnot;
/// @notice Last cached highest seen balance for all collateralized shares
uint256 public lastSeenETHPerCollateralizedSlotPerKnot;
/// @notice Last cached highest seen balance for all free floating shares
uint256 public lastSeenETHPerFreeFloating;
/// @notice Total number of sETH token shares staked across all houses
uint256 public totalFreeFloatingShares;
/// @notice Total amount of ETH drawn down by syndicate beneficiaries regardless of SLOT type
uint256 public totalClaimed;
/// @notice Number of knots registered with the syndicate which can be across any house
uint256 public numberOfRegisteredKnots;
/// @notice Informational - is the knot registered to this syndicate or not - the node should point to this contract
mapping(bytes => bool) public isKnotRegistered;
/// @notice Block number after which if there are sETH staking slots available, it can be supplied by anyone on the market
uint256 public priorityStakingEndBlock;
/// @notice Syndicate deployer can highlight addresses that get priority for staking free floating house sETH up to a certain block before anyone can do it
mapping(address => bool) public isPriorityStaker;
/// @notice Total amount of free floating sETH staked
mapping(bytes => uint256) public sETHTotalStakeForKnot;
/// @notice Amount of sETH staked by user against a knot
mapping(bytes => mapping(address => uint256)) public sETHStakedBalanceForKnot;
/// @notice Amount of ETH claimed by user from sETH staking
mapping(bytes => mapping(address => uint256)) public sETHUserClaimForKnot;
/// @notice Total amount of ETH that has been allocated to the collateralized SLOT owners of a KNOT
mapping(bytes => uint256) public totalETHProcessedPerCollateralizedKnot;
/// @notice Total amount of ETH accrued for the collateralized SLOT owner of a KNOT
mapping(bytes => mapping(address => uint256)) public accruedEarningPerCollateralizedSlotOwnerOfKnot;
/// @notice Total amount of ETH claimed by the collateralized SLOT owner of a KNOT
mapping(bytes => mapping(address => uint256)) public claimedPerCollateralizedSlotOwnerOfKnot;
/// @notice Whether a BLS public key, that has been previously registered, is no longer part of the syndicate and its shares (free floating or SLOT) cannot earn any more rewards
mapping(bytes => bool) public isNoLongerPartOfSyndicate;
/// @notice Once a BLS public key is no longer part of the syndicate, the accumulated ETH per free floating SLOT share is snapshotted so historical earnings can be drawn down correctly
mapping(bytes => uint256) public lastAccumulatedETHPerFreeFloatingShare;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
/// @param _contractOwner Ethereum public key that will receive management rights of the contract
/// @param _priorityStakingEndBlock Block number when priority sETH staking ends and anyone can stake
/// @param _priorityStakers Optional list of addresses that will have priority for staking sETH against each knot registered
/// @param _blsPubKeysForSyndicateKnots List of BLS public keys of Stakehouse protocol registered KNOTs participating in syndicate
function initialize(
address _contractOwner,
uint256 _priorityStakingEndBlock,
address[] memory _priorityStakers,
bytes[] memory _blsPubKeysForSyndicateKnots
) external virtual override initializer {
_initialize(
_contractOwner,
_priorityStakingEndBlock,
_priorityStakers,
_blsPubKeysForSyndicateKnots
);
}
/// @notice Allows the contract owner to append to the list of knots that are part of the syndicate
/// @param _newBLSPublicKeyBeingRegistered List of BLS public keys being added to the syndicate
function registerKnotsToSyndicate(
bytes[] calldata _newBLSPublicKeyBeingRegistered
) external onlyOwner {
// update accrued ETH per SLOT type
updateAccruedETHPerShares();
_registerKnotsToSyndicate(_newBLSPublicKeyBeingRegistered);
}
/// @notice Make knot shares of a registered list of BLS public keys inactive - the action cannot be undone and no further ETH accrued
function deRegisterKnots(bytes[] calldata _blsPublicKeys) external onlyOwner {
updateAccruedETHPerShares();
_deRegisterKnots(_blsPublicKeys);
}
/// @notice Allows the contract owner to append to the list of priority sETH stakers
/// @param _priorityStakers List of staker addresses eligible for sETH staking
function addPriorityStakers(address[] calldata _priorityStakers) external onlyOwner {
updateAccruedETHPerShares();
_addPriorityStakers(_priorityStakers);
}
/// @notice Should this block be in the future, it means only those listed in the priority staker list can stake sETH
/// @param _endBlock Arbitrary block number after which anyone can stake up to 4 SLOT in sETH per KNOT
function updatePriorityStakingBlock(uint256 _endBlock) external onlyOwner {
updateAccruedETHPerShares();
priorityStakingEndBlock = _endBlock;
}
/// @notice Update accrued ETH per SLOT share without distributing ETH as users of the syndicate individually pull funds
function updateAccruedETHPerShares() public {
// Ensure there are registered KNOTs. Syndicates are deployed with at least 1 registered but this can fall to zero.
// Fee recipient should be re-assigned in the event that happens as any further ETH can be collected by owner
if (numberOfRegisteredKnots > 0) {
// All time, total ETH that was earned per slot type (free floating or collateralized)
uint256 totalEthPerSlotType = calculateETHForFreeFloatingOrCollateralizedHolders();
// Process free floating if there are staked shares
uint256 freeFloatingUnprocessed;
if (totalFreeFloatingShares > 0) {
freeFloatingUnprocessed = getUnprocessedETHForAllFreeFloatingSlot();
accumulatedETHPerFreeFloatingShare += _calculateNewAccumulatedETHPerFreeFloatingShare(freeFloatingUnprocessed);
lastSeenETHPerFreeFloating = totalEthPerSlotType;
}
uint256 collateralizedUnprocessed = ((totalEthPerSlotType - lastSeenETHPerCollateralizedSlotPerKnot) / numberOfRegisteredKnots);
accumulatedETHPerCollateralizedSlotPerKnot += collateralizedUnprocessed;
lastSeenETHPerCollateralizedSlotPerKnot = totalEthPerSlotType;
emit UpdateAccruedETH(freeFloatingUnprocessed + collateralizedUnprocessed);
} else {
// todo - check else case for any ETH lost
}
}
/// @notice Stake up to 4 collateralized SLOT worth of sETH per KNOT to get a portion of syndicate rewards
/// @param _blsPubKeys List of BLS public keys for KNOTs registered with the syndicate
/// @param _sETHAmounts Per BLS public key, the total amount of sETH that will be staked (up to 4 collateralized SLOT per KNOT)
/// @param _onBehalfOf Allows a caller to specify an address that will be assigned stake ownership and rights to claim
function stake(bytes[] calldata _blsPubKeys, uint256[] calldata _sETHAmounts, address _onBehalfOf) external {
if (_blsPubKeys.length == 0) revert EmptyArray();
if (_blsPubKeys.length != _sETHAmounts.length) revert InconsistentArrayLengths();
if (_onBehalfOf == address(0)) revert ZeroAddress();
// Make sure we have the latest accrued information
updateAccruedETHPerShares();
for (uint256 i; i < _blsPubKeys.length; ++i) {
bytes memory _blsPubKey = _blsPubKeys[i];
uint256 _sETHAmount = _sETHAmounts[i];
if (_sETHAmount < 1 gwei) revert FreeFloatingStakeAmountTooSmall();
if (!isKnotRegistered[_blsPubKey] || isNoLongerPartOfSyndicate[_blsPubKey]) revert KnotIsNotRegisteredWithSyndicate();
if (block.number < priorityStakingEndBlock && !isPriorityStaker[_onBehalfOf]) revert NotPriorityStaker();
uint256 totalStaked = sETHTotalStakeForKnot[_blsPubKey];
if (totalStaked == 12 ether) revert KnotIsFullyStakedWithFreeFloatingSlotTokens();
if (_sETHAmount + totalStaked > 12 ether) revert InvalidStakeAmount();
totalFreeFloatingShares += _sETHAmount;
sETHTotalStakeForKnot[_blsPubKey] += _sETHAmount;
sETHStakedBalanceForKnot[_blsPubKey][_onBehalfOf] += _sETHAmount;
sETHUserClaimForKnot[_blsPubKey][_onBehalfOf] = (_sETHAmount * accumulatedETHPerFreeFloatingShare) / PRECISION;
(address stakeHouse,,,,,) = getStakeHouseUniverse().stakeHouseKnotInfo(_blsPubKey);
if (stakeHouse == address(0)) revert KnotIsNotAssociatedWithAStakeHouse();
IERC20 sETH = IERC20(getSlotRegistry().stakeHouseShareTokens(stakeHouse));
bool transferResult = sETH.transferFrom(msg.sender, address(this), _sETHAmount);
if (!transferResult) revert UnableToStakeFreeFloatingSlot();
emit Staked(_blsPubKey, _sETHAmount);
}
}
/// @notice Unstake an sETH position against a particular KNOT and claim ETH on exit
/// @param _unclaimedETHRecipient The address that will receive any unclaimed ETH received to the syndicate
/// @param _sETHRecipient The address that will receive the sETH that is being unstaked
/// @param _blsPubKeys List of BLS public keys for KNOTs registered with the syndicate
/// @param _sETHAmounts Per BLS public key, the total amount of sETH that will be unstaked
function unstake(
address _unclaimedETHRecipient,
address _sETHRecipient,
bytes[] calldata _blsPubKeys,
uint256[] calldata _sETHAmounts
) external nonReentrant {
if (_blsPubKeys.length == 0) revert EmptyArray();
if (_blsPubKeys.length != _sETHAmounts.length) revert InconsistentArrayLengths();
if (_unclaimedETHRecipient == address(0)) revert ZeroAddress();
if (_sETHRecipient == address(0)) revert ZeroAddress();
// Claim all ETH owed before unstaking but even if nothing is owed `updateAccruedETHPerShares` will be called
_claimAsStaker(_unclaimedETHRecipient, _blsPubKeys);
for (uint256 i; i < _blsPubKeys.length; ++i) {
bytes memory _blsPubKey = _blsPubKeys[i];
uint256 _sETHAmount = _sETHAmounts[i];
if (sETHStakedBalanceForKnot[_blsPubKey][msg.sender] < _sETHAmount) revert NothingStaked();
(address stakeHouse,,,,,) = getStakeHouseUniverse().stakeHouseKnotInfo(_blsPubKey);
IERC20 sETH = IERC20(getSlotRegistry().stakeHouseShareTokens(stakeHouse));
// Only decrease totalFreeFloatingShares in the event that the knot is still active in the syndicate
if (!isNoLongerPartOfSyndicate[_blsPubKey]) {
totalFreeFloatingShares -= _sETHAmount;
}
sETHTotalStakeForKnot[_blsPubKey] -= _sETHAmount;
sETHStakedBalanceForKnot[_blsPubKey][msg.sender] -= _sETHAmount;
bool transferResult = sETH.transfer(_sETHRecipient, _sETHAmount);
if (!transferResult) revert TransferFailed();
emit UnStaked(_blsPubKey, _sETHAmount);
}
}
/// @notice Claim ETH cashflow from the syndicate as an sETH staker proportional to how much the user has staked
/// @param _recipient Address that will receive the share of ETH funds
/// @param _blsPubKeys List of BLS public keys that the caller has staked against
function claimAsStaker(address _recipient, bytes[] calldata _blsPubKeys) public nonReentrant {
_claimAsStaker(_recipient, _blsPubKeys);
}
/// @param _blsPubKeys List of BLS public keys that the caller has staked against
function claimAsCollateralizedSLOTOwner(
address _recipient,
bytes[] calldata _blsPubKeys
) external nonReentrant {
if (_blsPubKeys.length == 0) revert EmptyArray();
if (_recipient == address(0)) revert ZeroAddress();
if (_recipient == address(this)) revert ZeroAddress();
// Make sure we have the latest accrued information for all shares
updateAccruedETHPerShares();
for (uint256 i; i < _blsPubKeys.length; ++i) {
bytes memory _blsPubKey = _blsPubKeys[i];
if (!isKnotRegistered[_blsPubKey]) revert KnotIsNotRegisteredWithSyndicate();
// process newly accrued ETH and distribute it to collateralized SLOT owners for the given knot
_updateCollateralizedSlotOwnersLiabilitySnapshot(_blsPubKey);
// Calculate total amount of unclaimed ETH
uint256 userShare = accruedEarningPerCollateralizedSlotOwnerOfKnot[_blsPubKey][msg.sender];
// This is designed to cope with falling SLOT balances i.e. when collateralized SLOT is burnt after applying penalties
uint256 unclaimedUserShare = userShare - claimedPerCollateralizedSlotOwnerOfKnot[_blsPubKey][msg.sender];
// Send ETH to the user if there is an unclaimed amount
if (unclaimedUserShare > 0) {
// Increase total claimed and claimed at the user level
totalClaimed += unclaimedUserShare;
claimedPerCollateralizedSlotOwnerOfKnot[_blsPubKey][msg.sender] = userShare;
// Send ETH to user
(bool success,) = _recipient.call{value: unclaimedUserShare}("");
if (!success) revert TransferFailed();
emit ETHClaimed(
_blsPubKey,
msg.sender,
_recipient,
unclaimedUserShare,
true
);
}
}
}
/// @notice For any new ETH received by the syndicate, at the knot level allocate ETH owed to each collateralized owner
/// @param _blsPubKey BLS public key relating to the collateralized owners that need updating
function updateCollateralizedSlotOwnersAccruedETH(bytes memory _blsPubKey) external {
_updateCollateralizedSlotOwnersLiabilitySnapshot(_blsPubKey);
}
/// @notice For any new ETH received by the syndicate, at the knot level allocate ETH owed to each collateralized owner and do it for a batch of knots
/// @param _blsPubKeys List of BLS public keys related to the collateralized owners that need updating
function batchUpdateCollateralizedSlotOwnersAccruedETH(bytes[] memory _blsPubKeys) external {
uint256 numOfKeys = _blsPubKeys.length;
if (numOfKeys == 0) revert EmptyArray();
for (uint256 i; i < _blsPubKeys.length; ++i) {
_updateCollateralizedSlotOwnersLiabilitySnapshot(_blsPubKeys[i]);
}
}
/// @notice Syndicate contract can receive ETH
receive() external payable {
// No logic here because one cannot assume that more than 21K GAS limit is forwarded
}
/// @notice Calculate the amount of unclaimed ETH for a given BLS publice key + free floating SLOT staker without factoring in unprocessed rewards
/// @param _blsPubKey BLS public key of the KNOT that is registered with the syndicate
/// @param _user The address of a user that has staked sETH against the BLS public key
function calculateUnclaimedFreeFloatingETHShare(bytes memory _blsPubKey, address _user) public view returns (uint256) {
// Check the user has staked sETH for the KNOT
uint256 stakedBal = sETHStakedBalanceForKnot[_blsPubKey][_user];
if (stakedBal < 1 gwei) revert FreeFloatingStakeAmountTooSmall();
// Get the amount of ETH eligible for the user based on their staking amount
uint256 accumulatedETHPerShare = _getCorrectAccumulatedETHPerFreeFloatingShareForBLSPublicKey(_blsPubKey);
uint256 userShare = (accumulatedETHPerShare * stakedBal) / PRECISION;
// Calculate how much their unclaimed share of ETH is based on total ETH claimed so far
return userShare - sETHUserClaimForKnot[_blsPubKey][_user];
}
/// @notice Using `highestSeenBalance`, this is the amount that is separately allocated to either free floating or collateralized SLOT holders
function calculateETHForFreeFloatingOrCollateralizedHolders() public view returns (uint256) {
// Get total amount of ETH that can be drawn down by all SLOT holders associated with a knot
uint256 ethPerKnot = totalETHReceived();
// Get the amount of ETH eligible for free floating sETH or collateralized SLOT stakers
return ethPerKnot / 2;
}
/// @notice Preview the amount of unclaimed ETH available for an sETH staker against a KNOT which factors in unprocessed rewards from new ETH sent to contract
/// @param _blsPubKey BLS public key of the KNOT that is registered with the syndicate
/// @param _staker The address of a user that has staked sETH against the BLS public key
function previewUnclaimedETHAsFreeFloatingStaker(
address _staker,
bytes calldata _blsPubKey
) external view returns (uint256) {
uint256 currentAccumulatedETHPerFreeFloatingShare = accumulatedETHPerFreeFloatingShare;
uint256 updatedAccumulatedETHPerFreeFloatingShare =
currentAccumulatedETHPerFreeFloatingShare + calculateNewAccumulatedETHPerFreeFloatingShare();
uint256 stakedBal = sETHStakedBalanceForKnot[_blsPubKey][_staker];
uint256 userShare = (updatedAccumulatedETHPerFreeFloatingShare * stakedBal) / PRECISION;
return userShare - sETHUserClaimForKnot[_blsPubKey][_staker];
}
/// @notice Preview the amount of unclaimed ETH available for a collatearlized SLOT staker against a KNOT which factors in unprocessed rewards from new ETH sent to contract
/// @param _staker Address of a collateralized SLOT owner for a KNOT
/// @param _blsPubKey BLS public key of the KNOT that is registered with the syndicate
function previewUnclaimedETHAsCollateralizedSlotOwner(
address _staker,
bytes calldata _blsPubKey
) external view returns (uint256) {
// Per collateralized SLOT per KNOT before distributing to individual collateralized owners
uint256 accumulatedSoFar = accumulatedETHPerCollateralizedSlotPerKnot
+ ((calculateETHForFreeFloatingOrCollateralizedHolders() - lastSeenETHPerCollateralizedSlotPerKnot) / numberOfRegisteredKnots);
uint256 unprocessedForKnot = accumulatedSoFar - totalETHProcessedPerCollateralizedKnot[_blsPubKey];
// Fetch information on what has been processed so far against the ECDSA address of the collateralized SLOT owner
uint256 currentAccrued = accruedEarningPerCollateralizedSlotOwnerOfKnot[_blsPubKey][_staker];
// Fetch information about the knot including total slashed amount
uint256 currentSlashedAmount = getSlotRegistry().currentSlashedAmountOfSLOTForKnot(_blsPubKey);
uint256 numberOfCollateralisedSlotOwnersForKnot = getSlotRegistry().numberOfCollateralisedSlotOwnersForKnot(_blsPubKey);
(address stakeHouse,,,,,) = getStakeHouseUniverse().stakeHouseKnotInfo(_blsPubKey);
// Find the collateralized SLOT owner and work out how much they're owed
for (uint256 i; i < numberOfCollateralisedSlotOwnersForKnot; ++i) {
address collateralizedOwnerAtIndex = getSlotRegistry().getCollateralisedOwnerAtIndex(_blsPubKey, i);
if (collateralizedOwnerAtIndex == _staker) {
uint256 balance = getSlotRegistry().totalUserCollateralisedSLOTBalanceForKnot(
stakeHouse,
collateralizedOwnerAtIndex,
_blsPubKey
);
if (currentSlashedAmount < 4 ether) {
currentAccrued +=
balance * unprocessedForKnot / (4 ether - currentSlashedAmount);
}
break;
}
}
return currentAccrued - claimedPerCollateralizedSlotOwnerOfKnot[_blsPubKey][_staker];
}
/// @notice Amount of ETH per free floating share that hasn't yet been allocated to each share
function getUnprocessedETHForAllFreeFloatingSlot() public view returns (uint256) {
return calculateETHForFreeFloatingOrCollateralizedHolders() - lastSeenETHPerFreeFloating;
}
/// @notice Amount of ETH per collateralized share that hasn't yet been allocated to each share
function getUnprocessedETHForAllCollateralizedSlot() public view returns (uint256) {
return ((calculateETHForFreeFloatingOrCollateralizedHolders() - lastSeenETHPerCollateralizedSlotPerKnot) / numberOfRegisteredKnots);
}
/// @notice New accumulated ETH per free floating share that hasn't yet been applied
/// @dev The return value is scaled by 1e24
function calculateNewAccumulatedETHPerFreeFloatingShare() public view returns (uint256) {
uint256 ethSinceLastUpdate = getUnprocessedETHForAllFreeFloatingSlot();
return _calculateNewAccumulatedETHPerFreeFloatingShare(ethSinceLastUpdate);
}
/// @notice New accumulated ETH per collateralized share per knot that hasn't yet been applied
function calculateNewAccumulatedETHPerCollateralizedSharePerKnot() public view returns (uint256) {
uint256 ethSinceLastUpdate = getUnprocessedETHForAllCollateralizedSlot();
return accumulatedETHPerCollateralizedSlotPerKnot + ethSinceLastUpdate;
}
/// @notice Total amount of ETH received by the contract
function totalETHReceived() public view returns (uint256) {
return address(this).balance + totalClaimed;
}
/// @dev Internal logic for initializing the syndicate contract
function _initialize(
address _contractOwner,
uint256 _priorityStakingEndBlock,
address[] memory _priorityStakers,
bytes[] memory _blsPubKeysForSyndicateKnots
) internal {
// Transfer ownership from the deployer to the address specified as the owner
_transferOwnership(_contractOwner);
// Add the initial set of knots to the syndicate
_registerKnotsToSyndicate(_blsPubKeysForSyndicateKnots);
// Optionally process priority staking if the required params and array is configured
if (_priorityStakingEndBlock > block.number) {
priorityStakingEndBlock = _priorityStakingEndBlock;
_addPriorityStakers(_priorityStakers);
}
emit ContractDeployed();
}
/// Given an amount of ETH allocated to the collateralized SLOT owners of a KNOT, distribute this amongs the current set of collateralized owners (a dynamic set of addresses and balances)
function _updateCollateralizedSlotOwnersLiabilitySnapshot(bytes memory _blsPubKey) internal {
// Establish how much new ETH is for the new KNOT
uint256 unprocessedETHForCurrentKnot =
accumulatedETHPerCollateralizedSlotPerKnot - totalETHProcessedPerCollateralizedKnot[_blsPubKey];
// Get information about the knot i.e. associated house and whether its active
(address stakeHouse,,,,,bool isActive) = getStakeHouseUniverse().stakeHouseKnotInfo(_blsPubKey);
// Assuming that there is unprocessed ETH and the knot is still part of the syndicate
if (unprocessedETHForCurrentKnot > 0 && !isNoLongerPartOfSyndicate[_blsPubKey]) {
uint256 currentSlashedAmount = getSlotRegistry().currentSlashedAmountOfSLOTForKnot(_blsPubKey);
// Don't allocate ETH when the current slashed amount is four. Syndicate will wait until ETH is topped up to claim revenue
if (currentSlashedAmount < 4 ether) {
// This copes with increasing numbers of collateralized slot owners and also copes with SLOT that has been slashed but not topped up
uint256 numberOfCollateralisedSlotOwnersForKnot = getSlotRegistry().numberOfCollateralisedSlotOwnersForKnot(_blsPubKey);
if (numberOfCollateralisedSlotOwnersForKnot == 1) {
// For only 1 collateralized SLOT owner, they get the full amount of unprocessed ETH for the knot
address collateralizedOwnerAtIndex = getSlotRegistry().getCollateralisedOwnerAtIndex(_blsPubKey, 0);
accruedEarningPerCollateralizedSlotOwnerOfKnot[_blsPubKey][collateralizedOwnerAtIndex] += unprocessedETHForCurrentKnot;
} else {
for (uint256 i; i < numberOfCollateralisedSlotOwnersForKnot; ++i) {
address collateralizedOwnerAtIndex = getSlotRegistry().getCollateralisedOwnerAtIndex(_blsPubKey, i);
uint256 balance = getSlotRegistry().totalUserCollateralisedSLOTBalanceForKnot(
stakeHouse,
collateralizedOwnerAtIndex,
_blsPubKey
);
accruedEarningPerCollateralizedSlotOwnerOfKnot[_blsPubKey][collateralizedOwnerAtIndex] +=
balance * unprocessedETHForCurrentKnot / (4 ether - currentSlashedAmount);
}
}
// record so unprocessed goes to zero
totalETHProcessedPerCollateralizedKnot[_blsPubKey] = accumulatedETHPerCollateralizedSlotPerKnot;
}
}
// if the knot is no longer active, no further accrual of rewards are possible snapshots are possible but ETH accrued up to that point
// Basically, under a rage quit or voluntary withdrawal from the beacon chain, the knot kick is auto-propagated to syndicate
if (!isActive && !isNoLongerPartOfSyndicate[_blsPubKey]) {
_deRegisterKnot(_blsPubKey);
}
}
function _calculateCollateralizedETHOwedPerKnot() internal view returns (uint256) {
uint256 collateralizedSLOTShareOfETH = calculateETHForFreeFloatingOrCollateralizedHolders();
uint256 collateralizedSLOTShareOfETHPerKnot = (collateralizedSLOTShareOfETH / numberOfRegisteredKnots);
return collateralizedSLOTShareOfETHPerKnot;
}
/// @dev Business logic for calculating per collateralized share how much ETH from 1559 rewards is owed
function _calculateNewAccumulatedETHPerCollateralizedShare(uint256 _ethSinceLastUpdate) internal view returns (uint256) {
return (_ethSinceLastUpdate * PRECISION) / (numberOfRegisteredKnots * 4 ether);
}
/// @dev Business logic for calculating per free floating share how much ETH from 1559 rewards is owed
function _calculateNewAccumulatedETHPerFreeFloatingShare(uint256 _ethSinceLastUpdate) internal view returns (uint256) {
return totalFreeFloatingShares > 0 ? (_ethSinceLastUpdate * PRECISION) / totalFreeFloatingShares : 0;
}
/// @dev Business logic for adding a new set of knots to the syndicate for collecting revenue
function _registerKnotsToSyndicate(bytes[] memory _blsPubKeysForSyndicateKnots) internal {
uint256 knotsToRegister = _blsPubKeysForSyndicateKnots.length;
if (knotsToRegister == 0) revert EmptyArray();
numberOfRegisteredKnots += knotsToRegister;
for (uint256 i; i < knotsToRegister; ++i) {
bytes memory blsPubKey = _blsPubKeysForSyndicateKnots[i];
if (isKnotRegistered[blsPubKey]) revert KnotIsAlreadyRegistered();
// incomming knot collateralized SLOT holders do not get historical earnings
totalETHProcessedPerCollateralizedKnot[blsPubKey] = accumulatedETHPerCollateralizedSlotPerKnot;
// Health check - if knot is inactive or slashed, should it really be part of the syndicate?
// KNOTs closer to 32 effective at all times is the target
(,,,,,bool isActive) = getStakeHouseUniverse().stakeHouseKnotInfo(blsPubKey);
if (!isActive) revert InactiveKnot();
uint256 numberOfCollateralisedSlotOwnersForKnot = getSlotRegistry().numberOfCollateralisedSlotOwnersForKnot(blsPubKey);
if (numberOfCollateralisedSlotOwnersForKnot < 1) revert InvalidNumberOfCollateralizedOwners();
if (getSlotRegistry().currentSlashedAmountOfSLOTForKnot(blsPubKey) != 0) revert InvalidNumberOfCollateralizedOwners();
isKnotRegistered[blsPubKey] = true;
emit KNOTRegistered(blsPubKey);
}
}
/// @dev Business logic for adding priority stakers to the syndicate
function _addPriorityStakers(address[] memory _priorityStakers) internal {
if (_priorityStakers.length == 0) revert EmptyArray();
for (uint256 i; i < _priorityStakers.length; ++i) {
address staker = _priorityStakers[i];
if (i > 0 && staker < _priorityStakers[i-1]) revert DuplicateArrayElements();
isPriorityStaker[staker] = true;
emit PriorityStakerRegistered(staker);
}
}
/// @dev Business logic for de-registering a set of knots from the syndicate and doing the required snapshots to ensure historical earnings are preserved
function _deRegisterKnots(bytes[] calldata _blsPublicKeys) internal {
for (uint256 i; i < _blsPublicKeys.length; ++i) {
bytes memory blsPublicKey = _blsPublicKeys[i];
// Do one final snapshot of ETH owed to the collateralized SLOT owners so they can claim later
_updateCollateralizedSlotOwnersLiabilitySnapshot(blsPublicKey);
// Execute the business logic for de-registering the single knot
_deRegisterKnot(blsPublicKey);
}
}
/// @dev Business logic for de-registering a specific knots assuming all accrued ETH has been processed
function _deRegisterKnot(bytes memory _blsPublicKey) internal {
if (isKnotRegistered[_blsPublicKey] == false) revert KnotIsNotRegisteredWithSyndicate();
if (isNoLongerPartOfSyndicate[_blsPublicKey] == true) revert KnotHasAlreadyBeenDeRegistered();
// We flag that the knot is no longer part of the syndicate
isNoLongerPartOfSyndicate[_blsPublicKey] = true;
// For the free floating and collateralized SLOT of the knot, snapshot the accumulated ETH per share
lastAccumulatedETHPerFreeFloatingShare[_blsPublicKey] = accumulatedETHPerFreeFloatingShare;
// We need to reduce `totalFreeFloatingShares` in order to avoid further ETH accruing to shares of de-registered knot
totalFreeFloatingShares -= sETHTotalStakeForKnot[_blsPublicKey];
// Total number of registered knots with the syndicate reduces by one
numberOfRegisteredKnots -= 1;
emit KnotDeRegistered(_blsPublicKey);
}
/// @dev Work out the accumulated ETH per free floating share value that must be used for distributing ETH
function _getCorrectAccumulatedETHPerFreeFloatingShareForBLSPublicKey(
bytes memory _blsPublicKey
) internal view returns (uint256) {
return
lastAccumulatedETHPerFreeFloatingShare[_blsPublicKey] > 0 ?
lastAccumulatedETHPerFreeFloatingShare[_blsPublicKey] :
accumulatedETHPerFreeFloatingShare;
}
/// @dev Business logic for allowing a free floating SLOT holder to claim their share of ETH
function _claimAsStaker(address _recipient, bytes[] calldata _blsPubKeys) internal {
if (_blsPubKeys.length == 0) revert EmptyArray();
if (_recipient == address(0)) revert ZeroAddress();
if (_recipient == address(this)) revert ZeroAddress();
// Make sure we have the latest accrued information
updateAccruedETHPerShares();
for (uint256 i; i < _blsPubKeys.length; ++i) {
bytes memory _blsPubKey = _blsPubKeys[i];
if (!isKnotRegistered[_blsPubKey]) revert KnotIsNotRegisteredWithSyndicate();
uint256 unclaimedUserShare = calculateUnclaimedFreeFloatingETHShare(_blsPubKey, msg.sender);
// this means that user can call the funtion even if there is nothing to claim but the
// worst that will happen is that they will just waste gas. this is needed for unstaking
if (unclaimedUserShare > 0) {
// Increase total claimed at the contract level
totalClaimed += unclaimedUserShare;
// Work out which accumulated ETH per free floating share value was used
uint256 accumulatedETHPerShare = _getCorrectAccumulatedETHPerFreeFloatingShareForBLSPublicKey(_blsPubKey);
// Update the total ETH claimed by the free floating SLOT holder based on their share of sETH
sETHUserClaimForKnot[_blsPubKey][msg.sender] =
(accumulatedETHPerShare * sETHStakedBalanceForKnot[_blsPubKey][msg.sender]) / PRECISION;
// Send ETH to user
(bool success,) = _recipient.call{value: unclaimedUserShare}("");
if (!success) revert TransferFailed();
emit ETHClaimed(
_blsPubKey,
msg.sender,
_recipient,
unclaimedUserShare,
false
);
}
}
}
}