-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathvalidatorCompound.js
More file actions
897 lines (790 loc) · 26.9 KB
/
validatorCompound.js
File metadata and controls
897 lines (790 loc) · 26.9 KB
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
const addresses = require("../utils/addresses");
const { formatUnits, parseUnits } = require("ethers/lib/utils");
const { BigNumber } = require("ethers");
const { getBlock } = require("../tasks/block");
const {
calcDepositRoot,
calcWithdrawalCredential,
} = require("./beaconTesting");
const {
calcSlot,
getValidatorBalance,
getBeaconBlock,
} = require("../utils/beacon");
const { getNetworkName } = require("../utils/hardhat-helpers");
const { getSigner } = require("../utils/signers");
const { verifyDepositSignatureAndMessageRoot } = require("../utils/beacon");
const { resolveContract } = require("../utils/resolvers");
const { getClusterInfo, splitOperatorIds } = require("../utils/ssv");
const { logTxDetails } = require("../utils/txLogger");
const {
createValidatorRequest,
getValidatorRequestStatus,
getValidatorRequestDepositData,
} = require("../utils/p2pValidatorCompound");
const { toHex } = require("../utils/units");
const {
calcTargetBuffer,
calcAvailableInVault,
totalPartialWithdrawals,
withdrawFromStrategyIfNeeded,
} = require("../utils/vault");
const log = require("../utils/logger")("task:validator:compounding");
async function snapBalances({ consol = false }) {
const signer = await getSigner();
// TODO check the slot of the first pending deposit is not zero
const contract = consol
? await resolveContract("ConsolidationController")
: await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
log(`About to snap balances on ${contract.address}`);
const tx = await contract.connect(signer).snapBalances();
await logTxDetails(tx, "snapBalances");
const receipt = await tx.wait();
const event = receipt.events.find(
(event) => event.event === "BalancesSnapped"
);
if (!event) {
throw new Error("BalancesSnapped event not found in transaction receipt");
}
console.log(
`Balances snapped successfully. Beacon block root ${
event.args.blockRoot
}, block ${receipt.blockNumber}, ETH balance ${formatUnits(
event.args.ethBalance
)}`
);
}
async function registerValidatorCreateRequest({ days }) {
await createValidatorRequest({
validatorSpawnOperationalPeriodInDays: days,
});
}
/**
* If the UUID is passed to this function then pubkey, shares, operatorIds are
* ignored and fetched from the P2P
*/
async function registerValidator({ pubkey, shares, operatorids, ssv, uuid }) {
const signer = await getSigner();
if (uuid) {
const {
pubkey: _pubkey,
shares: _shares,
operatorids: _operatorids,
} = await getValidatorRequestStatus({ uuid });
pubkey = _pubkey;
shares = _shares;
// unsorted string of operators
operatorids = _operatorids;
}
log(`Splitting operator IDs ${operatorids}`);
const operatorIds = splitOperatorIds(operatorids);
const ssvAmount = parseUnits(ssv.toString(), 18);
const strategy = await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
// Cluster details
const { chainId } = await ethers.provider.getNetwork();
const { cluster } = await getClusterInfo({
chainId,
operatorids,
ownerAddress: strategy.address,
});
log(`About to register compounding validator with pubkey ${pubkey}`);
const tx = await strategy
.connect(signer)
.registerSsvValidator(pubkey, operatorIds, shares, ssvAmount, cluster);
await logTxDetails(tx, "registerValidator");
}
/**
* If the UUID is passed to this function then pubkey, sig, amount are
* ignored and fetched from the P2P
*/
async function stakeValidator({
dryrun,
pubkey,
sig,
amount,
withdrawalCredentials,
depositMessageRoot,
forkVersion,
uuid,
consol = false,
}) {
const signer = await getSigner();
if (uuid) {
const {
pubkey: _pubkey,
sig: _sig,
amount: _amount,
depositMessageRoot: _depositMessageRoot,
withdrawalCredentials: _withdrawalCredentials,
forkVersion: _forkVersion,
} = await getValidatorRequestDepositData({ uuid });
pubkey = _pubkey;
sig = _sig;
amount = _amount;
withdrawalCredentials = _withdrawalCredentials;
depositMessageRoot = _depositMessageRoot;
forkVersion = _forkVersion;
}
const strategy = await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
const contract = consol
? await resolveContract("ConsolidationController")
: strategy;
if (!withdrawalCredentials) {
withdrawalCredentials = calcWithdrawalCredential("0x02", strategy.address);
}
if (amount == 1) {
if (!sig) {
throw new Error(
"The signature is required for the first deposit of 1 ETH"
);
}
await verifyDepositSignatureAndMessageRoot({
pubkey,
withdrawalCredentials,
amount,
signature: sig,
depositMessageRoot,
forkVersion,
});
} else {
// The signatures doesn't mater after the first deposit
sig =
"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001";
}
const depositDataRoot = await calcDepositRoot(
strategy.address,
"0x02",
pubkey,
sig,
amount
);
const amountGwei = parseUnits(amount.toString(), 9);
if (dryrun) {
console.log(`About to stake ${amount} ETH to validator with`);
console.log(` pubkey : ${pubkey}`);
console.log(` signature : ${sig}`);
console.log(` depositDataRoot: ${depositDataRoot}`);
return;
}
log(
`About to stake ${amount} ETH to validator with pubkey ${pubkey}, deposit root ${depositDataRoot} and signature ${sig} via ${
consol ? "ConsolidationController" : "strategy"
}`
);
const tx = await contract
.connect(signer)
.stakeEth({ pubkey, signature: sig, depositDataRoot }, amountGwei);
const receipt = await logTxDetails(tx, "stakeETH");
const event = receipt.events.find((event) => event.event === "ETHStaked");
if (!event) {
throw new Error("ETHStaked event not found in transaction receipt");
}
console.log(`Pending deposit root: ${event.args.pendingDepositRoot}`);
}
async function autoValidatorDeposits({
signer,
slot, // undefined = latest slot
maxBalance: maxBalanceGwei = parseUnits("2030", 9),
minDeposit: minDepositGwei = parseUnits("1.1", 9),
buffer: bufferBps = 100, // 1% buffer
minStrategyWithdrawAmount = parseUnits("0.1", 18),
dryrun = false,
}) {
const networkName = await getNetworkName();
const wethAddress = addresses[networkName].WETH;
const weth = await ethers.getContractAt("IERC20", wethAddress);
const strategy = await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
const strategyView = await resolveContract("CompoundingStakingStrategyView");
const vault = await resolveContract("OETHVaultProxy", "IVault");
// 1. Calculate the WETH available in the vault = WETH balance - withdrawals queued + withdrawals claimed
const availableInVault = await calcAvailableInVault({
vault,
weth,
blockTag: "latest",
});
// 2. Calculate the buffer amount = total assets * buffer in basis points
const buffer = await calcTargetBuffer({ vault, bufferBps });
// 3. Withdraw any WETH or ETH in the staking strategy if needed in the Vault
await withdrawFromStrategyIfNeeded({
weth,
strategy,
vault,
availableInVault,
buffer,
minStrategyWithdrawAmount,
signer,
dryrun,
});
// 4. Calculate how much can be deposited and stop if not enough
// WETH in the strategy
const wethInStrategy = await weth.balanceOf(strategy.address);
log(`WETH balance in strategy ${formatUnits(wethInStrategy, 18)}`);
// Convert wei balance to gwei
let remainingGwei = wethInStrategy.div(parseUnits("1", 9));
if (remainingGwei.lt(minDepositGwei)) {
log(
`${formatUnits(
remainingGwei,
9
)} WETH balance in strategy less than ${formatUnits(
minDepositGwei,
9
)} ETH min deposit. Stopping`
);
return;
}
// 5. Get the staking strategy's active validators and pending deposits
const verifiedValidators = await strategyView.getVerifiedValidators();
const activeValidators = verifiedValidators.filter(
(validator) => validator.state === 4 // ACTIVE
);
const pendingDeposits = await strategyView.getPendingDeposits();
// 6. Calculate validators balances after all the pending deposits have been processed
// Get beacon chain data
const { stateView } = await getBeaconBlock(slot, networkName);
let validators = [];
// Iterate over the active validators
for (const validator of activeValidators) {
// get the validator's balance
let balanceGwei = stateView.balances.get(validator.index);
log(
` Validator ${validator.index} balance ${formatUnits(
balanceGwei,
9
)} ETH`
);
// Add any pending deposits for this validator's balance
for (const deposit of pendingDeposits) {
if (deposit.pubKeyHash === validator.pubKeyHash) {
balanceGwei = BigNumber.from(balanceGwei.toString()).add(
deposit.amountGwei
);
log(
` Pending deposit of ${formatUnits(
deposit.amountGwei,
9
)} ETH for validator ${validator.index}. New balance ${formatUnits(
balanceGwei,
9
)} ETH`
);
}
}
// Get the validator public key
const { pubkey } = stateView.validators.get(validator.index);
validators.push({
index: validator.index,
pubKey: toHex(pubkey),
balanceGwei: BigNumber.from(balanceGwei.toString()),
});
}
// 7. Filter and sort validators
// Filter out any validators that are already at or above the max balance
const filteredValidators = validators.filter((v) =>
v.balanceGwei.lt(maxBalanceGwei)
);
// Sort by largest to smallest balance
const sortedValidators = filteredValidators.sort((a, b) =>
a.balanceGwei.gt(b.balanceGwei) ? -1 : 1
);
// 8. Iterate over each validator and top up to max ETH if necessary
const emptySignature =
"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
// For each active validator that is under the max balance
for (const validator of sortedValidators) {
const maxDepositAmount = maxBalanceGwei.sub(validator.balanceGwei);
const depositAmountGwei = remainingGwei.lt(maxDepositAmount)
? remainingGwei
: maxDepositAmount;
if (depositAmountGwei.lt(minDepositGwei)) continue;
log(
`About to top up validator ${validator.index} with ${formatUnits(
depositAmountGwei,
9
)} WETH`
);
if (!dryrun) {
// Calculate the deposit data root
const depositDataRoot = await calcDepositRoot(
strategy.address,
"0x02",
validator.pubKey,
// This sig doesn't matter after the first deposit
emptySignature,
// Need to convert to an ETH amount with no decimals
formatUnits(depositAmountGwei, 9)
);
// Call the strategy to deposit to the beacon deposit contract
const tx = await strategy.connect(signer).stakeEth(
{
pubkey: validator.pubKey,
signature: emptySignature,
depositDataRoot,
},
depositAmountGwei
);
await logTxDetails(tx, "stakeEth");
}
// Reduce the remaining amount that needs to be deposited
remainingGwei = remainingGwei.sub(depositAmountGwei);
if (remainingGwei.lt(minDepositGwei)) {
log(
`${formatUnits(
remainingGwei,
9
)} WETH remaining less than ${formatUnits(
minDepositGwei,
9
)} WETH min deposit. Stopping`
);
break;
}
}
if (remainingGwei.gt(0)) {
log(
`${formatUnits(
remainingGwei,
9
)} WETH remaining. Need more active validators before it can be deposited`
);
}
}
async function withdrawValidator({ pubkey, amount, signer, consol = false }) {
const strategy = consol
? await resolveContract("ConsolidationController")
: await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
/// Get the validator's balance
const balance = await getValidatorBalance(pubkey);
const isFullExit = amount === undefined || amount === 0;
if (consol && isFullExit) {
throw new Error(
"The ConsolidationController only supports partial withdrawals. Set a non-zero amount."
);
}
const amountGwei = isFullExit ? 0 : parseUnits(amount.toString(), 9);
if (isFullExit) {
log(
`About to fully exit validator with balance ${formatUnits(
balance,
9
)} ETH and pubkey ${pubkey}`
);
} else {
log(
`About to partially withdraw ${formatUnits(amountGwei, 9)} ETH from ${
consol ? "ConsolidationController" : "validator"
} with balance ${formatUnits(balance, 9)} ETH and pubkey ${pubkey}`
);
}
// Send 1 wei of value to cover the request withdrawal fee
const tx = await strategy
.connect(signer)
.validatorWithdrawal(pubkey, amountGwei, { value: 1 });
await logTxDetails(tx, "validatorWithdrawal");
}
async function autoValidatorWithdrawals({
signer,
slot, // undefined = latest slot
buffer: bufferBps = 100, // 1% buffer
minValidatorWithdrawAmount = BigInt(10e18),
minStrategyWithdrawAmount = parseUnits("0.1", 18),
dryrun = false,
}) {
const networkName = await getNetworkName();
const wethAddress = addresses[networkName].WETH;
const weth = await ethers.getContractAt("IERC20", wethAddress);
const vaultAddress = addresses[networkName].OETHVaultProxy;
const vault = await ethers.getContractAt("IVault", vaultAddress);
const strategy = await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
const strategyView = await resolveContract("CompoundingStakingStrategyView");
// 1. Calculate the WETH available in the vault = WETH balance - withdrawals queued + withdrawals claimed
const availableInVault = await calcAvailableInVault({
vault,
weth,
blockTag: "latest",
});
// 2. Get the staking strategy's active validator indexes
const activeValidators = await strategyView.getVerifiedValidators();
const validatorIndexes = activeValidators.map((v) => v.index.toNumber());
// 3. Calculate pending validator partial withdrawal = sum amount in the partial withdrawal from the beacon chain data
// Get beacon chain data
const { stateView } = await getBeaconBlock(slot, networkName);
const totalPendingPartialWithdrawals = await totalPartialWithdrawals(
stateView,
validatorIndexes
);
// 4. Calculate the buffer amount = total assets * buffer in basis points
const buffer = await calcTargetBuffer({ vault, bufferBps });
// 5. Withdraw any WETH or ETH in the staking strategy if needed in the Vault
const { availableInStrategy } = await withdrawFromStrategyIfNeeded({
weth,
strategy,
vault,
availableInVault,
buffer,
minStrategyWithdrawAmount,
signer,
dryrun,
});
// 6. Remaining amount = buffer - WETH available in the vault - pending withdrawals - any ETH or WETH in the staking strategy
let remainingAmount = buffer
.sub(availableInVault)
.sub(totalPendingPartialWithdrawals)
.sub(availableInStrategy);
log(`Remaining amount to withdraw ${formatUnits(remainingAmount, 18)}`);
// 7. Withdraw from the validators is necessary
// End job if remaining amount < 0
if (remainingAmount.lt(0)) {
log(`No need to withdraw from the validators.`);
return;
}
// Get validator balances from the beacon chain data
const validators = [];
for (let i = 0; i < activeValidators.length; i++) {
const validatorIndex = activeValidators[i].index;
const validator = stateView.validators.get(validatorIndex);
const balanceGwei = stateView.balances.get(validatorIndex);
validators.push({
index: validatorIndex,
pubKey: toHex(validator.pubkey),
balanceWei: parseUnits(balanceGwei.toString(), 9),
});
log(
` Validator ${validatorIndex} balance ${formatUnits(balanceGwei, 9)} ETH`
);
}
// Sort validators by smallest to highest balance
const sortedValidators = validators.sort((a, b) =>
a.balanceWei.lt(b.balanceWei) ? -1 : 1
);
// For each validator
for (const validator of sortedValidators) {
const maxValidatorWithdrawal = validator.balanceWei.sub(
parseUnits("32.25", 18)
);
const withdrawalAmount = maxValidatorWithdrawal.lt(remainingAmount)
? maxValidatorWithdrawal
: remainingAmount;
// continue if withdrawal amount < min partial withdraw amount
if (withdrawalAmount < minValidatorWithdrawAmount) {
log(
` Skipping validator ${
validator.index
} as withdrawal amount ${formatUnits(
withdrawalAmount.toString(),
18
)} is less than the minimum partial withdrawal amount`
);
continue;
}
const withdrawalAmountGwei = withdrawalAmount.div(parseUnits("1", 9));
log(
` Withdrawing ${formatUnits(
withdrawalAmountGwei,
9
)} ETH from validator ${validator.index}`
);
if (!dryrun) {
// Call strategy to partially withdraw from the validator
const tx = await strategy
.connect(signer)
.validatorWithdrawal(
validator.pubKey,
withdrawalAmountGwei.toString(),
{
value: 1,
}
);
await logTxDetails(tx, "validatorWithdrawal");
}
remainingAmount = remainingAmount.sub(withdrawalAmount);
if (remainingAmount.lte(0)) {
log(` Reached the required withdrawal amount`);
break;
}
}
if (remainingAmount.gt(0)) {
log(
` Still need to withdraw ${formatUnits(
remainingAmount,
18
)} ETH from the validators next time`
);
}
}
async function snapStakingStrategy({
buffer: bufferBps = 100, // 1% buffer
block,
}) {
let blockTag = await getBlock(block);
// Don't use the latest block as the slot probably won't be available yet
if (!block) blockTag -= 1;
const { timestamp } = await ethers.provider.getBlock(blockTag);
const networkName = await getNetworkName();
const slot = calcSlot(timestamp, networkName);
log(`Snapping block ${blockTag} at slot ${slot}`);
const { stateView } = await getBeaconBlock(slot, networkName);
const wethAddress = addresses[networkName].WETH;
const weth = await ethers.getContractAt("IERC20", wethAddress);
const ssvAddress = addresses[networkName].SSV;
const ssv = await ethers.getContractAt("IERC20", ssvAddress);
const strategy = await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
const strategyView = await resolveContract("CompoundingStakingStrategyView");
const vault = await resolveContract("OETHVaultProxy", "IVault");
// Pending deposits
const totalDeposits = await logDeposits(strategyView, blockTag, stateView);
if (stateView.pendingDeposits.length === 0) {
console.log("No pending beacon chain deposits");
} else {
const firstBeaconDeposit = stateView.pendingDeposits.get(0);
console.log(
`${
stateView.pendingDeposits.length
} beacon chain deposits. The first has slot ${
firstBeaconDeposit.slot
} and public key ${toHex(firstBeaconDeposit.pubkey)}`
);
}
// Pending withdrawals
const activeValidators = await strategyView.getVerifiedValidators();
const validatorIndexes = activeValidators.map((v) => v.index.toNumber());
const totalWithdrawals = await totalPartialWithdrawals(
stateView,
validatorIndexes,
true
);
// Verified validators
const verifiedValidators = await strategyView.getVerifiedValidators({
blockTag,
});
console.log(`\n${verifiedValidators.length || "No"} verified validators:`);
if (verifiedValidators.length > 0) {
console.log(
` amount (ETH) index status public key Withdrawable Exit epoch`
);
}
let totalValidators = BigNumber.from(0);
for (const validator of verifiedValidators) {
const balance = stateView.balances.get(validator.index);
const validatorData = await strategy.validator(validator.pubKeyHash, {
blockTag,
});
const beaconValidator = stateView.validators.get(validator.index);
console.log(
` ${formatUnits(balance, 9).padEnd(14)} ${
validator.index
} ${validatorStatus(validatorData.state).padEnd(8)} ${toHex(
beaconValidator.pubkey
)} ${beaconValidator.withdrawableEpoch || "\t\t"} ${
beaconValidator.exitEpoch || ""
}`
);
totalValidators = totalValidators.add(balance);
}
console.log(
`${
stateView.pendingPartialWithdrawals.length || "No"
} pending beacon chain withdrawals`
);
const stratWethBalance = await weth.balanceOf(strategy.address, { blockTag });
const stratEthBalance = await ethers.provider.getBalance(
strategy.address,
blockTag
);
const stratSsvBalance = await ssv.balanceOf(strategy.address, { blockTag });
const stratBalance = await strategy.checkBalance(wethAddress, {
blockTag,
});
const totalAssets = parseUnits(totalDeposits.toString(), 9)
.add(parseUnits(totalValidators.toString(), 9))
.add(stratWethBalance)
.add(stratEthBalance);
const assetDiff = totalAssets.sub(stratBalance);
const snappedBalance = await strategy.snappedBalance({
blockTag,
});
const vaultTotalValue = await vault.totalValue({ blockTag });
const targetBuffer = vaultTotalValue.mul(bufferBps).div(10000);
const availableInVault = await calcAvailableInVault({
vault,
weth,
blockTag,
});
const snappedSlot =
snappedBalance.timestamp == 0
? 0n
: calcSlot(snappedBalance.timestamp, networkName);
const lastVerifiedEthBalance = await strategy.lastVerifiedEthBalance({
blockTag,
});
const depositedWethAccountedFor = await strategy.depositedWethAccountedFor({
blockTag,
});
console.log(`\nBalances at block ${blockTag}, slot ${slot}:`);
console.log(`Total deposit : ${formatUnits(totalDeposits, 9)}`);
console.log(`Total withdrawals : ${formatUnits(totalWithdrawals, 18)}`);
console.log(`Validator balances : ${formatUnits(totalValidators, 9)}`);
console.log(`WETH in strategy : ${formatUnits(stratWethBalance, 18)}`);
console.log(`ETH in strategy : ${formatUnits(stratEthBalance, 18)}`);
console.log(`Total assets : ${formatUnits(totalAssets, 18)}`);
console.log(
`Strategy balance : ${formatUnits(stratBalance, 18)} diff ${formatUnits(
assetDiff,
18
)}`
);
console.log(`Vault total value : ${formatUnits(vaultTotalValue, 18)}`);
console.log(`Target buffer (1%) : ${formatUnits(targetBuffer, 18)}`);
console.log(`Available in vault : ${formatUnits(availableInVault, 18)}`);
console.log(
`Last verified ETH : ${formatUnits(lastVerifiedEthBalance, 18)}`
);
console.log(
`Last snapped ETH : ${formatUnits(snappedBalance.ethBalance, 18)}`
);
console.log(`Last snapped root : ${snappedBalance.blockRoot}`);
console.log(
`Last snap timestamp: ${snappedBalance.timestamp} ${new Date(
snappedBalance.timestamp * 1000
).toISOString()} `
);
console.log(
`Last snap slot : ${snappedSlot} (${slot - snappedSlot} slots ago)`
);
console.log(`SSV balance : ${formatUnits(stratSsvBalance, 18)}`);
console.log(
`WETH Deposits : ${formatUnits(depositedWethAccountedFor, 18)}`
);
}
async function logDeposits(strategyView, blockTag = "latest", stateView) {
const deposits = await strategyView.getPendingDeposits({ blockTag });
let totalDeposits = BigNumber.from(0);
console.log(`\n${deposits.length || "No"} pending strategy deposits:`);
if (deposits.length > 0) {
console.log(
` Pending deposit root amount (ETH) slot Q pos public key`
);
}
for (const deposit of deposits) {
const { pendingDeposit, position } = findDepositInQueue(
deposit.pendingDepositRoot,
stateView
);
const pubKey = pendingDeposit
? toHex(pendingDeposit.pubkey)
: deposit.pubKeyHash;
console.log(
` ${deposit.pendingDepositRoot} ${formatUnits(
deposit.amountGwei,
9
).padEnd(14)} ${deposit.slot} ${position
.toString()
.padStart(5)} ${pubKey}`
);
totalDeposits = totalDeposits.add(deposit.amountGwei);
}
return totalDeposits;
}
function findDepositInQueue(pendingDepositRoot, stateView) {
for (let i = 0; i < stateView.pendingDeposits.length; i++) {
const pendingDeposit = stateView.pendingDeposits.get(i);
if (toHex(pendingDeposit.hashTreeRoot()) === pendingDepositRoot) {
return { pendingDeposit, position: i };
}
}
return { pendingDeposit: undefined, position: -1 };
}
function validatorStatus(status) {
if (status === 0) {
return "NON_REGISTERED";
} else if (status === 1) {
return "REGISTERED";
} else if (status === 2) {
return "STAKED";
} else if (status === 3) {
return "VERIFIED";
} else if (status === 4) {
return "ACTIVE";
} else if (status === 5) {
return "EXITING";
} else if (status === 6) {
return "EXITED";
} else if (status === 7) {
return "REMOVED";
} else if (status === 8) {
return "INVALID";
} else {
return "UNKNOWN";
}
}
async function setRegistrator({ account, type }) {
const signer = await getSigner();
const strategy =
type === "new"
? await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
)
: await resolveContract(
"NativeStakingSSVStrategyProxy",
"NativeStakingSSVStrategy"
);
const tx = await strategy.connect(signer).setRegistrator(account);
await logTxDetails(tx, "setRegistrator");
}
async function removeValidator({ pubkey, operatorids }) {
const signer = await getSigner();
log(`Splitting operator IDs ${operatorids}`);
const operatorIds = splitOperatorIds(operatorids);
const strategy = await resolveContract(
"CompoundingStakingSSVStrategyProxy",
"CompoundingStakingSSVStrategy"
);
// Cluster details
const { chainId } = await ethers.provider.getNetwork();
const { cluster } = await getClusterInfo({
chainId,
operatorids,
ownerAddress: strategy.address,
});
log(`About to remove compounding validator with pubkey ${pubkey}`);
const tx = await strategy
.connect(signer)
.removeSsvValidator(pubkey, operatorIds, cluster);
await logTxDetails(tx, "removeSsvValidator");
}
module.exports = {
snapBalances,
registerValidatorCreateRequest,
registerValidator,
stakeValidator,
autoValidatorDeposits,
snapStakingStrategy,
logDeposits,
setRegistrator,
validatorStatus,
withdrawValidator,
autoValidatorWithdrawals,
removeValidator,
};