/
service.go
935 lines (756 loc) · 28.5 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
package ethservice
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"math/big"
"strings"
"github.com/attestantio/go-eth2-client/spec/phase0"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
types "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/sirupsen/logrus"
k2common "github.com/restaking-cloud/native-delegation-for-plus/common"
config "github.com/restaking-cloud/native-delegation-for-plus/ethservice/config"
"github.com/restaking-cloud/native-delegation-for-plus/ethservice/contracts"
)
type EthService struct {
client *ethclient.Client
cfg config.EthServiceConfig
log *logrus.Entry
}
func NewEthService() *EthService {
return &EthService{}
}
func (e *EthService) Configure(cfg config.EthServiceConfig, logger *logrus.Entry) error {
e.cfg = cfg
e.log = logger
err := e.connect(cfg.ExecutionNodeUrl)
if err != nil {
return fmt.Errorf("failed to connect to execution node: %w", err)
}
err = e.configureMulticallContract(common.HexToAddress(contracts.MULTICALL3_CONTRACT_ADDRESS))
if err != nil {
return err
}
if (cfg.K2LendingContractAddress != common.Address{}) && (cfg.K2NodeOperatorContractAddress != common.Address{}) {
err = e.configureK2LendingContract(cfg.K2LendingContractAddress)
if err != nil {
return err
}
err = e.configureK2NodeOperatorContract(cfg.K2NodeOperatorContractAddress)
if err != nil {
return err
}
k2LendingProposerRegistryAddress, err := e.FetchProposerRegistryAddressFromK2Lending()
if err != nil {
return err
}
k2NodeOperatorProposerRegistryAddress, err := e.FetchProposerRegistryAddressFromK2NodeOperator()
if err != nil {
return err
}
// check that both k2 contracts are pointing to the same Proposer Registry contract
if !strings.EqualFold(k2LendingProposerRegistryAddress, k2NodeOperatorProposerRegistryAddress) {
return fmt.Errorf("k2 Lending and NodeOperator contracts are pointing to different proposer registry contracts")
}
// check that the Proposer Registry address matches what is configured if not override
if !strings.EqualFold(k2LendingProposerRegistryAddress, cfg.ProposerRegistryContractAddress.String()) {
e.log.WithFields(
logrus.Fields{
"configuredProposerRegistryAddress": cfg.ProposerRegistryContractAddress.String(),
"k2LendingProposerRegistryAddress": k2LendingProposerRegistryAddress,
"k2NodeOperatorProposerRegistryAddress": k2NodeOperatorProposerRegistryAddress,
},
).Warn("Proposer Registry contract address mismatch, overriding with the one from K2 contracts")
cfg.ProposerRegistryContractAddress = common.HexToAddress(k2LendingProposerRegistryAddress)
}
}
// check there is a Proposer Registry contract address
if (cfg.ProposerRegistryContractAddress == common.Address{}) {
return fmt.Errorf("proposer registry contract address not configured")
// ideally this would not be possible, since bundled with the module,
// but in case it happened to be overridden by a wrong address from the K2 contract
}
err = e.configureProposerRegistryContract(cfg.ProposerRegistryContractAddress)
if err != nil {
return err
}
return nil
}
func (e *EthService) ConnectedChainId() *big.Int {
return e.cfg.ChainID
}
func (e *EthService) Status() (*ethereum.SyncProgress, error) {
return e.client.SyncProgress(context.Background())
}
func (e *EthService) SetMaxGasPrice(maxGasPrice uint64) {
e.cfg.MaxGasPrice = big.NewInt(int64(maxGasPrice))
logger := e.log.WithField("maxGasPrice", e.cfg.MaxGasPrice.String())
currentGasPrice, err := e.client.SuggestGasPrice(context.Background())
if err != nil {
logger.WithError(err).Debug("Failed to retrieve current gas price")
} else {
// check if max gas price is more than 30% lower than current gas price
diff := new(big.Float).Sub(new(big.Float).SetInt(e.cfg.MaxGasPrice), new(big.Float).SetInt(currentGasPrice))
percentage := new(big.Float).Quo(diff, new(big.Float).SetInt(currentGasPrice))
if percentage.Cmp(big.NewFloat(-0.3)) < 0 {
logger.WithFields(
logrus.Fields{
"currentGasPrice": currentGasPrice.String() + " Wei",
"maxGasPrice": e.cfg.MaxGasPrice.String() + " Wei",
},
).Warn("Max gas price is more than 30% lower than current gas price, consider increasing it, else registrations might be paused for a long time")
}
}
}
func (e *EthService) GetBlock(number *big.Int) (*types.Block, error) {
block, err := e.client.BlockByNumber(context.Background(), number)
if err != nil {
return nil, fmt.Errorf("error fetching block: %w", err)
}
return block, nil
}
func (e *EthService) FetchProposerRegistryAddressFromK2Lending() (string, error) {
data, err := e.cfg.K2LendingContractABI.Pack("proposerRegistry")
if err != nil {
return "", fmt.Errorf("error packing proposerRegistry call: %w", err)
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2LendingContractAddress,
Data: data,
}, nil)
if err != nil {
return "", fmt.Errorf("error calling proposerRegistry: %w", err)
}
var contractAddress common.Address
err = e.cfg.K2LendingContractABI.UnpackIntoInterface(&contractAddress, "proposerRegistry", callResult)
if err != nil {
return "", fmt.Errorf("error unpacking proposerRegistry result: %w", err)
}
return contractAddress.String(), nil
}
func (e *EthService) FetchProposerRegistryAddressFromK2NodeOperator() (string, error) {
data, err := e.cfg.K2NodeOperatorContractABI.Pack("proposerRegistry")
if err != nil {
return "", err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}, nil)
if err != nil {
return "", err
}
var contractAddress common.Address
err = e.cfg.K2NodeOperatorContractABI.UnpackIntoInterface(&contractAddress, "proposerRegistry", callResult)
if err != nil {
return "", err
}
return contractAddress.String(), nil
}
// Proposer Registry Registration
func (e *EthService) BatchCheckRegisteredValidators(validators []phase0.BLSPubKey) (map[string]contracts.BlsPublicKeyToProposerResult, error) {
var multicallInputs contracts.Multicall3AggregateArgs
results := make(map[string]contracts.BlsPublicKeyToProposerResult)
if len(validators) == 0 {
return results, nil
}
for _, validator := range validators {
data, err := e.cfg.ProposerRegistryContractABI.Pack("blsPublicKeyToProposer", validator[:])
if err != nil {
return nil, err
}
multicallInputs.Calls = append(multicallInputs.Calls, contracts.Call3{
Target: e.cfg.ProposerRegistryContractAddress,
CallData: data,
AllowFailure: true,
})
}
multicallInputsEncoded, err := e.cfg.MulticallContractABI.Pack("aggregate3", multicallInputs.Calls)
if err != nil {
return nil, err
}
batchCallResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.MulticallContractAddress,
Data: multicallInputsEncoded,
}, nil)
if err != nil {
return nil, err
}
var batchCallResultDecoded contracts.Multicall3AggregateResult
err = e.cfg.MulticallContractABI.UnpackIntoInterface(&batchCallResultDecoded, "aggregate3", batchCallResult)
if err != nil {
return nil, fmt.Errorf("error unpacking batch call result: %w", err)
}
successfulValidatorChecks := make(map[string]contracts.BlsPublicKeyToProposerResult)
failedValidatorChecks := make(map[string]contracts.BlsPublicKeyToProposerResult)
for i, validator := range validators {
if !batchCallResultDecoded.ReturnData[i].Success {
failedValidatorChecks[validator.String()] = contracts.BlsPublicKeyToProposerResult{}
continue
}
var registrationResult contracts.BlsPublicKeyToProposerResult
err = e.cfg.ProposerRegistryContractABI.UnpackIntoInterface(®istrationResult, "blsPublicKeyToProposer", batchCallResultDecoded.ReturnData[i].ReturnData)
if err != nil {
return nil, fmt.Errorf("error unpacking blsPublicKeyToProposer result: %w", err)
}
successfulValidatorChecks[validator.String()] = registrationResult
}
for k, v := range successfulValidatorChecks {
results[k] = v
}
for k := range failedValidatorChecks {
results[k] = contracts.BlsPublicKeyToProposerResult{}
}
return results, nil
}
func (e *EthService) BatchRegisterValidators(validatorRegistrations []k2common.K2ValidatorRegistration) (tx *types.Transaction, err error) {
var blsKeys [][]byte
var feeRecipients []common.Address
var blsSignatures [][]byte
var ecdsaSignatures []struct {
V uint8
R [32]byte
S [32]byte
}
var openClaim []bool
representative := k2common.ValidatorWallet{
Address: common.Address{},
}
for _, reg := range validatorRegistrations {
blsKeys = append(blsKeys, reg.SignedValidatorRegistration.Message.Pubkey[:])
feeRecipients = append(feeRecipients, common.HexToAddress(reg.SignedValidatorRegistration.Message.FeeRecipient.String()))
blsSignatures = append(blsSignatures, reg.SignedValidatorRegistration.Signature[:])
sig_r, err := hex.DecodeString(strings.TrimPrefix(reg.ECDSASignature.R, "0x"))
if err != nil {
return nil, err
}
var sig_r32 [32]byte
copy(sig_r32[:], sig_r)
sig_s, err := hex.DecodeString(strings.TrimPrefix(reg.ECDSASignature.S, "0x"))
if err != nil {
return nil, err
}
var sig_s32 [32]byte
copy(sig_s32[:], sig_s)
ecdsaSignatures = append(ecdsaSignatures, struct {
V uint8
R [32]byte
S [32]byte
}{
V: reg.ECDSASignature.V,
R: sig_r32,
S: sig_s32,
})
openClaim = append(openClaim, true)
// If there is already a representative wallet, check if it matches the current registration
if representative.Address != (common.Address{}) {
if representative.Address != reg.RepresentativeAddress {
return nil, fmt.Errorf("batchRegisterProposerWithoutPayoutPoolRegistration payload contains different representative addresses: %s and %s", representative.Address.String(), reg.RepresentativeAddress)
}
} else {
// find the representative wallet from the configured wallets
for _, wallet := range e.cfg.ValidatorWallets {
if wallet.Address == reg.RepresentativeAddress {
representative = wallet
break
}
}
// If no representative wallet found, return error
if representative.Address == (common.Address{}) {
return nil, fmt.Errorf("representative wallet not found for address: %s", reg.RepresentativeAddress.String())
}
}
}
data, err := e.cfg.ProposerRegistryContractABI.Pack("batchRegisterProposerWithoutPayoutPoolRegistration", blsKeys, feeRecipients, blsSignatures, ecdsaSignatures, openClaim, feeRecipients)
if err != nil {
return nil, err
}
executedTx, err := e.transactAndWait(context.Background(), types.NewTx(&types.DynamicFeeTx{
To: &e.cfg.ProposerRegistryContractAddress,
Data: data,
}), representative.PrivateKey)
if err != nil {
return nil, fmt.Errorf("error sending batch register: %w", err)
}
return executedTx, nil
}
// K2 Native Delegation
func (e *EthService) BatchK2CheckRegisteredValidators(validators []phase0.BLSPubKey) (map[string]string, error) {
var multicallInputs contracts.Multicall3AggregateArgs
results := make(map[string]string)
if len(validators) == 0 {
return results, nil
}
for _, validator := range validators {
data, err := e.cfg.K2LendingContractABI.Pack("blsPublicKeyToNodeOperator", validator[:])
if err != nil {
return nil, err
}
multicallInputs.Calls = append(multicallInputs.Calls, contracts.Call3{
Target: e.cfg.K2LendingContractAddress,
CallData: data,
AllowFailure: true,
})
}
multicallInputsEncoded, err := e.cfg.MulticallContractABI.Pack("aggregate3", multicallInputs.Calls)
if err != nil {
return nil, err
}
batchCallResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.MulticallContractAddress,
Data: multicallInputsEncoded,
}, nil)
if err != nil {
return nil, err
}
var batchCallResultDecoded contracts.Multicall3AggregateResult
err = e.cfg.MulticallContractABI.UnpackIntoInterface(&batchCallResultDecoded, "aggregate3", batchCallResult)
if err != nil {
return nil, fmt.Errorf("error unpacking batch call result: %w", err)
}
successfulValidatorChecks := make(map[string]string)
failedValidatorChecks := make(map[string]string)
for i, validator := range validators {
if !batchCallResultDecoded.ReturnData[i].Success {
failedValidatorChecks[validator.String()] = ""
continue
}
successfulValidatorChecks[validator.String()] = common.BytesToAddress(batchCallResultDecoded.ReturnData[i].ReturnData).String()
}
for k, v := range successfulValidatorChecks {
results[k] = v
}
for k := range failedValidatorChecks {
results[k] = common.Address{}.String()
}
return results, nil
}
func (e *EthService) K2NodeOperatorToPayoutRecipient(nodeOperatorAddresses []common.Address) (map[string]common.Address, error) {
var multicallInputs contracts.Multicall3AggregateArgs
results := make(map[string]common.Address)
if len(nodeOperatorAddresses) == 0 {
return results, nil
}
for _, nodeOperatorAddress := range nodeOperatorAddresses {
data, err := e.cfg.K2LendingContractABI.Pack("nodeOperatorToPayoutRecipient", nodeOperatorAddress)
if err != nil {
return nil, err
}
multicallInputs.Calls = append(multicallInputs.Calls, contracts.Call3{
Target: e.cfg.K2LendingContractAddress,
CallData: data,
AllowFailure: true,
})
}
multicallInputsEncoded, err := e.cfg.MulticallContractABI.Pack("aggregate3", multicallInputs.Calls)
if err != nil {
return nil, err
}
batchCallResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.MulticallContractAddress,
Data: multicallInputsEncoded,
}, nil)
if err != nil {
return nil, err
}
var batchCallResultDecoded contracts.Multicall3AggregateResult
err = e.cfg.MulticallContractABI.UnpackIntoInterface(&batchCallResultDecoded, "aggregate3", batchCallResult)
if err != nil {
return nil, fmt.Errorf("error unpacking batch call result: %w", err)
}
successfulChecks := make(map[string]common.Address)
failedChecks := make(map[string]common.Address)
for i, nodeOperatorAddress := range nodeOperatorAddresses {
if !batchCallResultDecoded.ReturnData[i].Success {
failedChecks[nodeOperatorAddress.String()] = common.Address{}
continue
}
successfulChecks[nodeOperatorAddress.String()] = common.BytesToAddress(batchCallResultDecoded.ReturnData[i].ReturnData)
}
for k, v := range successfulChecks {
results[k] = v
}
for k := range failedChecks {
results[k] = common.Address{}
}
return results, nil
}
func (e *EthService) K2BatchNativeDelegation(validatorRegistrations []k2common.K2ValidatorRegistration) (tx *types.Transaction, err error) {
// K2 deposit for native delegation
var blsKeys [][]byte
var feeRecipients []common.Address
var blsSignatures [][]byte
var ecdsaSignatures []struct {
V uint8
R [32]byte
S [32]byte
}
representative := k2common.ValidatorWallet{
Address: common.Address{},
}
for _, reg := range validatorRegistrations {
blsKeys = append(blsKeys, reg.SignedValidatorRegistration.Message.Pubkey[:])
feeRecipients = append(feeRecipients, common.HexToAddress(reg.SignedValidatorRegistration.Message.FeeRecipient.String()))
blsSignatures = append(blsSignatures, reg.SignedValidatorRegistration.Signature[:])
sig_r, err := hex.DecodeString(strings.TrimPrefix(reg.ECDSASignature.R, "0x"))
if err != nil {
return nil, err
}
var sig_r32 [32]byte
copy(sig_r32[:], sig_r)
sig_s, err := hex.DecodeString(strings.TrimPrefix(reg.ECDSASignature.S, "0x"))
if err != nil {
return nil, err
}
var sig_s32 [32]byte
copy(sig_s32[:], sig_s)
ecdsaSignatures = append(ecdsaSignatures, struct {
V uint8
R [32]byte
S [32]byte
}{
V: reg.ECDSASignature.V,
R: sig_r32,
S: sig_s32,
})
// If there is already a representative wallet, check if it matches the current registration
if representative.Address != (common.Address{}) {
if representative.Address != reg.RepresentativeAddress {
return nil, fmt.Errorf("batchRegisterProposerWithoutPayoutPoolRegistration payload contains different representative addresses: %s and %s", representative.Address.String(), reg.RepresentativeAddress)
}
} else {
// find the representative wallet from the configured wallets
for _, wallet := range e.cfg.ValidatorWallets {
if wallet.Address == reg.RepresentativeAddress {
representative = wallet
break
}
}
// If no representative wallet found, return error
if representative.Address == (common.Address{}) {
return nil, fmt.Errorf("representative wallet not found for address: %s", reg.RepresentativeAddress.String())
}
}
}
data, err := e.cfg.K2LendingContractABI.Pack("batchNodeOperatorDeposit", blsKeys, feeRecipients, blsSignatures, ecdsaSignatures)
if err != nil {
return nil, err
}
executedTx, err := e.transactAndWait(context.Background(), types.NewTx(&types.DynamicFeeTx{
To: &e.cfg.K2LendingContractAddress,
Data: data,
}), representative.PrivateKey)
if err != nil {
return nil, fmt.Errorf("error sending batch node deposit: %w", err)
}
return executedTx, nil
}
// Rewards Claiming
func (e *EthService) BatchK2CheckClaimableRewards(nodeOperators []common.Address) (map[common.Address]uint64, error) {
var multicallInputs contracts.Multicall3AggregateArgs
results := make(map[common.Address]uint64)
if len(nodeOperators) == 0 {
return results, nil
}
for _, nodeOperator := range nodeOperators {
data, err := e.cfg.K2LendingContractABI.Pack("claimableKETHForNodeOperator", nodeOperator)
if err != nil {
return nil, err
}
multicallInputs.Calls = append(multicallInputs.Calls, contracts.Call3{
Target: e.cfg.K2LendingContractAddress,
CallData: data,
AllowFailure: true,
})
}
multicallInputsEncoded, err := e.cfg.MulticallContractABI.Pack("aggregate3", multicallInputs.Calls)
if err != nil {
return nil, err
}
batchCallResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.MulticallContractAddress,
Data: multicallInputsEncoded,
}, nil)
if err != nil {
return nil, err
}
var batchCallResultDecoded contracts.Multicall3AggregateResult
err = e.cfg.MulticallContractABI.UnpackIntoInterface(&batchCallResultDecoded, "aggregate3", batchCallResult)
if err != nil {
return nil, fmt.Errorf("error unpacking batch call result: %w", err)
}
successfulValidatorChecks := make(map[common.Address]uint64)
failedValidatorChecks := make(map[common.Address]uint64)
for i, nodeOperator := range nodeOperators {
if !batchCallResultDecoded.ReturnData[i].Success {
failedValidatorChecks[nodeOperator] = 0
continue
}
var claimableRewards *big.Int
err = e.cfg.K2LendingContractABI.UnpackIntoInterface(&claimableRewards, "claimableKETHForNodeOperator", batchCallResultDecoded.ReturnData[i].ReturnData)
if err != nil {
return nil, fmt.Errorf("error unpacking claimableKETHForNodeOperator result: %w", err)
}
successfulValidatorChecks[nodeOperator] = claimableRewards.Uint64()
}
for k, v := range successfulValidatorChecks {
results[k] = v
}
for k, v := range failedValidatorChecks {
results[k] = v
}
return results, nil
}
func (e *EthService) BatchK2ClaimRewards(rewardClaims []k2common.K2Claim) (tx *types.Transaction, err error) {
var blsKeys [][]byte
var effectiveBalances []*big.Int
var ecdsaSignatures []struct {
V uint8
R [32]byte
S [32]byte
}
// Claim can be triggered by any representative wallet, use the primary wallet
representative := e.cfg.ValidatorWallets[0]
for _, claim := range rewardClaims {
blsKeys = append(blsKeys, claim.ValidatorPubKey[:])
effectiveBalances = append(effectiveBalances, big.NewInt(0).SetUint64(claim.EffectiveBalance))
sig_r, err := hex.DecodeString(strings.TrimPrefix(claim.EffectiveBalanceReportSignature.R, "0x"))
if err != nil {
return nil, err
}
var sig_r32 [32]byte
copy(sig_r32[:], sig_r)
sig_s, err := hex.DecodeString(strings.TrimPrefix(claim.EffectiveBalanceReportSignature.S, "0x"))
if err != nil {
return nil, err
}
var sig_s32 [32]byte
copy(sig_s32[:], sig_s)
ecdsaSignatures = append(ecdsaSignatures, struct {
V uint8
R [32]byte
S [32]byte
}{
V: claim.EffectiveBalanceReportSignature.V,
R: sig_r32,
S: sig_s32,
})
}
data, err := e.cfg.K2NodeOperatorContractABI.Pack("nodeOperatorClaim", blsKeys, effectiveBalances, ecdsaSignatures)
if err != nil {
return nil, err
}
executedTx, err := e.transactAndWait(context.Background(), types.NewTx(&types.DynamicFeeTx{
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}), representative.PrivateKey)
if err != nil {
return nil, fmt.Errorf("error sending batch claim: %w", err)
}
return executedTx, nil
}
func (e *EthService) K2Exit(validatorExit k2common.K2Exit) (tx *types.Transaction, err error) {
blsKey := validatorExit.ValidatorPubKey[:]
effectiveBalance := big.NewInt(0).SetUint64(validatorExit.EffectiveBalance)
sig_r, err := hex.DecodeString(strings.TrimPrefix(validatorExit.ECDSASignature.R, "0x"))
if err != nil {
return nil, err
}
var sig_r32 [32]byte
copy(sig_r32[:], sig_r)
sig_s, err := hex.DecodeString(strings.TrimPrefix(validatorExit.ECDSASignature.S, "0x"))
if err != nil {
return nil, err
}
var sig_s32 [32]byte
copy(sig_s32[:], sig_s)
ecdsaSignature := struct {
V uint8
R [32]byte
S [32]byte
}{
V: validatorExit.ECDSASignature.V,
R: sig_r32,
S: sig_s32,
}
var pk *ecdsa.PrivateKey
for _, wallet := range e.cfg.ValidatorWallets {
if wallet.Address == validatorExit.RepresentativeAddress {
pk = wallet.PrivateKey
break
}
}
data, err := e.cfg.K2NodeOperatorContractABI.Pack("nodeOperatorWithdraw", blsKey, effectiveBalance, ecdsaSignature)
if err != nil {
return nil, err
}
executedTx, err := e.transactAndWait(context.Background(), types.NewTx(&types.DynamicFeeTx{
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}), pk)
if err != nil {
return nil, fmt.Errorf("error sending k2 exit: %w", err)
}
return executedTx, nil
}
func (e *EthService) NativeDelegationCountForNodeOperator(nodeOperatorAddress common.Address) (*big.Int, error) {
data, err := e.cfg.K2LendingContractABI.Pack("nodeOperatorToBlsPublicKeyCount", nodeOperatorAddress)
if err != nil {
return nil, err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address,
To: &e.cfg.K2LendingContractAddress,
Data: data,
}, nil)
if err != nil {
return nil, err
}
var callResultDecoded *big.Int
err = e.cfg.K2LendingContractABI.UnpackIntoInterface(&callResultDecoded, "nodeOperatorToBlsPublicKeyCount", callResult)
if err != nil {
return nil, fmt.Errorf("error unpacking nodeOperatorToBlsPublicKeyCount result: %w", err)
}
return callResultDecoded, nil
}
func (e *EthService) K2ChangeNodeOperatorPayoutAddress(nodeOperator common.Address, newPayoutAddress common.Address) (tx *types.Transaction, err error) {
if (nodeOperator == common.Address{}) {
return nil, fmt.Errorf("nodeOperator address is null address")
}
if (newPayoutAddress == common.Address{}) {
return nil, fmt.Errorf("newPayoutAddress is null address")
}
data, err := e.cfg.K2LendingContractABI.Pack("nodeOperatorFeeRecipientUpdate", newPayoutAddress)
if err != nil {
return nil, err
}
var pk *ecdsa.PrivateKey
for _, wallet := range e.cfg.ValidatorWallets {
if wallet.Address == nodeOperator {
pk = wallet.PrivateKey
break
}
}
if pk == nil {
return nil, fmt.Errorf("nodeOperator wallet not found for address: %s", nodeOperator.String())
}
executedTx, err := e.transactAndWait(context.Background(), types.NewTx(&types.DynamicFeeTx{
To: &e.cfg.K2LendingContractAddress,
Data: data,
}), pk)
if err != nil {
return nil, fmt.Errorf("error sending k2 change payout address: %w", err)
}
return executedTx, nil
}
// K2 Capacity, Limits & Node Operator Inclusion list
func (e *EthService) K2CheckInclusionList(nodeOperatorRepresentative common.Address) (bool, error) {
data, err := e.cfg.K2NodeOperatorContractABI.Pack("isPartOfInclusionList", nodeOperatorRepresentative)
if err != nil {
return false, err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}, nil)
if err != nil {
return false, err
}
var callResultDecoded bool
err = e.cfg.K2NodeOperatorContractABI.UnpackIntoInterface(&callResultDecoded, "isPartOfInclusionList", callResult)
if err != nil {
return false, fmt.Errorf("error unpacking isPartOfInclusionList result: %w", err)
}
return callResultDecoded, nil
}
func (e *EthService) K2CheckInclusionListKeysCount(nodeOperatorRepresentative common.Address) (*big.Int, error) {
data, err := e.cfg.K2NodeOperatorContractABI.Pack("totalNumberOfRegisteredKeysForInclusionListMember", nodeOperatorRepresentative)
if err != nil {
return nil, err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}, nil)
if err != nil {
return nil, err
}
var callResultDecoded *big.Int
err = e.cfg.K2NodeOperatorContractABI.UnpackIntoInterface(&callResultDecoded, "totalNumberOfRegisteredKeysForInclusionListMember", callResult)
if err != nil {
return nil, fmt.Errorf("error unpacking totalNumberOfRegisteredKeysForInclusionListMember result: %w", err)
}
return callResultDecoded, nil
}
func (e *EthService) IndividualMaxNativeDelegation() (*big.Int, error) {
data, err := e.cfg.K2NodeOperatorContractABI.Pack("MAX_NATIVE_DELEGATION_PER_NODE_OPERATOR")
if err != nil {
return nil, err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}, nil)
if err != nil {
return nil, err
}
var callResultDecoded *big.Int
err = e.cfg.K2NodeOperatorContractABI.UnpackIntoInterface(&callResultDecoded, "MAX_NATIVE_DELEGATION_PER_NODE_OPERATOR", callResult)
if err != nil {
return nil, fmt.Errorf("error unpacking MAX_NATIVE_DELEGATION_PER_NODE_OPERATOR result: %w", err)
}
return callResultDecoded, nil
}
func (e *EthService) GetTotalNativeDelegationCapacityConsumed() (*big.Int, error) {
data, err := e.cfg.K2NodeOperatorContractABI.Pack("totalOpenNativeDelegationCapacityConsumed")
if err != nil {
return nil, err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}, nil)
if err != nil {
return nil, err
}
var callResultDecoded *big.Int
err = e.cfg.K2NodeOperatorContractABI.UnpackIntoInterface(&callResultDecoded, "totalOpenNativeDelegationCapacityConsumed", callResult)
if err != nil {
return nil, fmt.Errorf("error unpacking totalOpenNativeDelegationCapacityConsumed result: %w", err)
}
return callResultDecoded, nil
}
func (e *EthService) GlobalMaxNativeDelegation() (*big.Int, error) {
data, err := e.cfg.K2NodeOperatorContractABI.Pack("MAX_OPEN_NATIVE_DELEGATION_CAPACITY")
if err != nil {
return nil, err
}
callResult, err := e.client.CallContract(context.Background(), ethereum.CallMsg{
From: e.cfg.ValidatorWallets[0].Address, // use the first wallet to make the call as sender address is not important
To: &e.cfg.K2NodeOperatorContractAddress,
Data: data,
}, nil)
if err != nil {
return nil, err
}
var callResultDecoded *big.Int
err = e.cfg.K2NodeOperatorContractABI.UnpackIntoInterface(&callResultDecoded, "MAX_OPEN_NATIVE_DELEGATION_CAPACITY", callResult)
if err != nil {
return nil, fmt.Errorf("error unpacking MAX_OPEN_NATIVE_DELEGATION_CAPACITY result: %w", err)
}
return callResultDecoded, nil
}