From fad0f7df1a039d85e88a72fb2b6284489c94086c Mon Sep 17 00:00:00 2001 From: batphonghan Date: Mon, 26 Feb 2024 21:39:04 +0700 Subject: [PATCH] Refactor --- .golangci.yml | 2 +- shared/services/ec-manager.go | 4 ++-- shared/services/wallet/node.go | 2 +- shared/utils/stader/node-diversity.go | 1 - stader-cli/node/claim-sp-rewards.go | 20 +++++++++++++------ stader-cli/node/deposit-sd.go | 1 + stader-cli/node/send-el-rewards.go | 2 ++ stader-cli/node/status.go | 1 - stader-cli/validator/deposit.go | 12 +++++------ stader-lib/node/validator.go | 8 ++++---- stader-lib/sdutility/sd-utility.go | 8 +++++++- stader-lib/socializing-pool/rewards.go | 4 ++-- stader-lib/utils/eth/units.go | 3 +++ stader-lib/utils/sd/sd.go | 5 ----- stader/api/node/claim-rewards.go | 4 ++-- stader/api/node/claim-sp-rewards.go | 2 +- .../guardian/collector/network-collector.go | 3 +-- .../guardian/collector/operator-collector.go | 6 +++--- stader/node/node.go | 1 - 19 files changed, 50 insertions(+), 39 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index aa68692b2..cddc6543d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -33,7 +33,7 @@ linters: - gocritic - gofmt - goimports - - gocyclo + # - gocyclo - gosec - gosimple - govet diff --git a/shared/services/ec-manager.go b/shared/services/ec-manager.go index b3216279a..a057ec591 100644 --- a/shared/services/ec-manager.go +++ b/shared/services/ec-manager.go @@ -541,12 +541,12 @@ func (p *ExecutionClientManager) Version() (string, error) { Jsonrpc string `json:"jsonrpc"` Method string `json:"method"` Params []string `json:"params"` - Id int64 `json:"id"` + IdD int64 `json:"id"` }{ Jsonrpc: "2.0", Method: "web3_clientVersion", Params: []string{}, - Id: 1, + IdD: 1, } res, err := net.MakePostRequest(url, payload) diff --git a/shared/services/wallet/node.go b/shared/services/wallet/node.go index 695282175..28a285774 100644 --- a/shared/services/wallet/node.go +++ b/shared/services/wallet/node.go @@ -190,7 +190,6 @@ func (w *Wallet) getNodeDerivedKey(index uint) (*hdkeychain.ExtendedKey, string, // Get the node hex encoding public key func (w *Wallet) GetNodePubkey() (string, error) { - // Check wallet is initialized if !w.IsInitialized() { return "", errors.New("Wallet is not initialized") @@ -204,6 +203,7 @@ func (w *Wallet) GetNodePubkey() (string, error) { // Get public key publicKey := privateKey.Public() + publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey) if !ok { return "", errors.New("Could not get node public key") diff --git a/shared/utils/stader/node-diversity.go b/shared/utils/stader/node-diversity.go index 6902c4080..b42957d6e 100644 --- a/shared/utils/stader/node-diversity.go +++ b/shared/utils/stader/node-diversity.go @@ -33,5 +33,4 @@ func SendNodeDiversityResponseType( } return &resp, nil - } diff --git a/stader-cli/node/claim-sp-rewards.go b/stader-cli/node/claim-sp-rewards.go index 18d290084..ccdc9834f 100644 --- a/stader-cli/node/claim-sp-rewards.go +++ b/stader-cli/node/claim-sp-rewards.go @@ -82,11 +82,14 @@ func ClaimSpRewards(c *cli.Context) error { if !ok { return fmt.Errorf("Unable to parse eth rewards: %s", cycleInfo.MerkleProofInfo.Eth) } + ethRewardsConverted := math.RoundDown(eth.WeiToEth(ethRewards), 5) + sdRewards, ok := big.NewInt(0).SetString(cycleInfo.MerkleProofInfo.Sd, 10) if !ok { return fmt.Errorf("Unable to parse sd rewards: %s", cycleInfo.MerkleProofInfo.Sd) } + sdRewardsConverted := math.RoundDown(eth.WeiToEth(sdRewards), 5) if ethRewards.Cmp(big.NewInt(0)) == 0 && sdRewards.Cmp(big.NewInt(0)) == 0 { @@ -142,21 +145,27 @@ func ClaimSpRewards(c *cli.Context) error { totalClaimableEth := big.NewInt(0) totalClaimableSd := big.NewInt(0) + for _, cycle := range cyclesToClaimArray { cycleInfo := indexedDetailedCyclesInfo[cycle.Int64()] + ethRewards, ok := big.NewInt(0).SetString(cycleInfo.Eth, 10) if !ok { return fmt.Errorf("Unable to parse eth rewards: %s", cycleInfo.Eth) } + totalClaimableEth = totalClaimableEth.Add(totalClaimableEth, ethRewards) + sdRewards, ok := big.NewInt(0).SetString(cycleInfo.Sd, 10) if !ok { return fmt.Errorf("Unable to parse sd rewards: %s", cycleInfo.Sd) } + totalClaimableSd = totalClaimableSd.Add(totalClaimableSd, sdRewards) } depositSd := false + if totalClaimableSd.Cmp(big.NewInt(0)) > 0 { fmt.Printf("You will claim %s and %s with the following selection - cycles %v\n\n", eth.DisplayAmountInUnits(totalClaimableSd, "sd"), eth.DisplayAmountInUnits(totalClaimableEth, "eth"), cyclesToClaimArray) fmt.Printf("Your ETH rewards will be sent to your Reward Address\n") @@ -181,16 +190,15 @@ func ClaimSpRewards(c *cli.Context) error { } depositSd = true } - } else { - if !cliutils.Confirm(fmt.Sprintf( - "Are you sure you want to claim %s ETH for cycles %v to your reward address?", totalClaimableEth.String(), cyclesToClaimArray)) { - fmt.Println("Cancelled.") - return nil - } + } else if !cliutils.Confirm(fmt.Sprintf( + "Are you sure you want to claim %s ETH for cycles %v to your reward address?", totalClaimableEth.String(), cyclesToClaimArray)) { + fmt.Println("Cancelled.") + return nil } // estimate gas fmt.Println("Estimating gas...") + estimateGasResponse, err := staderClient.EstimateClaimSpRewardsGas(cyclesToClaimArray, depositSd) if err != nil { return err diff --git a/stader-cli/node/deposit-sd.go b/stader-cli/node/deposit-sd.go index b98d4a704..fde3c0468 100644 --- a/stader-cli/node/deposit-sd.go +++ b/stader-cli/node/deposit-sd.go @@ -63,6 +63,7 @@ func DepositSdWithAmount(staderClient *stader.Client, amountWei *big.Int, autoCo maxApproval := maxUint256() fmt.Println("Before depositing SD, you must first give the collateral contract approval to interact with your SD.") + err = nodeApproveSdWithAmountAndAddress(staderClient, maxApproval, contracts.SdCollateralContract, autoConfirm, nonce) if err != nil { return err diff --git a/stader-cli/node/send-el-rewards.go b/stader-cli/node/send-el-rewards.go index ef83edbef..79256b449 100644 --- a/stader-cli/node/send-el-rewards.go +++ b/stader-cli/node/send-el-rewards.go @@ -52,8 +52,10 @@ func SendElRewards(c *cli.Context) error { if err != nil { return err } + fmt.Printf("Sending %s EL Rewards to Claim Vault\n\n", eth.DisplayAmountInUnits(res.ElRewardsAmount, "eth")) cliutils.PrintTransactionHash(staderClient, res.TxHash) + if _, err = staderClient.WaitForTransaction(res.TxHash); err != nil { return err } diff --git a/stader-cli/node/status.go b/stader-cli/node/status.go index 5fd0e6bc3..ef5245e6c 100644 --- a/stader-cli/node/status.go +++ b/stader-cli/node/status.go @@ -183,7 +183,6 @@ func getNodeStatus(c *cli.Context) error { totalRegisteredValidators, eth.DisplayAmountInUnits(sdStatus.SdCollateralRequireAmount, "sd"), "10%", "10%", "10%") - } else { fmt.Println("") } diff --git a/stader-cli/validator/deposit.go b/stader-cli/validator/deposit.go index e5b9152f8..a86e5476c 100644 --- a/stader-cli/validator/deposit.go +++ b/stader-cli/validator/deposit.go @@ -116,9 +116,9 @@ func nodeDeposit(c *cli.Context) error { return nil } case 1: - selfBondAmount, err := node.PromptChooseSelfBondAmount(sdStatus) - if err != nil { - return err + selfBondAmount, errSelfBond := node.PromptChooseSelfBondAmount(sdStatus) + if errSelfBond != nil { + return errSelfBond } if status.AccountBalances.Sd.Cmp(selfBondAmount) < 0 { @@ -132,10 +132,10 @@ func nodeDeposit(c *cli.Context) error { } nounce := c.GlobalUint64("nonce") - err = node.DepositSdWithAmount(staderClient, selfBondAmount, true, nounce) + errSelfBond = node.DepositSdWithAmount(staderClient, selfBondAmount, true, nounce) - if err != nil { - return err + if errSelfBond != nil { + return errSelfBond } default: diff --git a/stader-lib/node/validator.go b/stader-lib/node/validator.go index 0d7c21d03..0969ecc5f 100644 --- a/stader-lib/node/validator.go +++ b/stader-lib/node/validator.go @@ -19,13 +19,13 @@ func EstimateAddValidatorKeys( pubKeys [][]byte, preDepositSignatures [][]byte, depositSignatures [][]byte, - referralId string, + referralID string, opts *bind.TransactOpts, ) (stader.GasInfo, error) { return pnr.PermissionlessNodeRegistryContract.GetTransactionGasInfo( opts, "addValidatorKeysWithUtilizeSD", - referralId, + referralID, utilityAmount, pubKeys, preDepositSignatures, @@ -39,9 +39,9 @@ func AddValidatorKeysWithAmount( preDepositSignatures [][]byte, depositSignatures [][]byte, utilityAmount *big.Int, - referralId string, + referralID string, opts *bind.TransactOpts) (*types.Transaction, error) { - tx, err := pnr.PermissionlessNodeRegistry.AddValidatorKeysWithUtilizeSD(opts, referralId, utilityAmount, pubKeys, preDepositSignatures, depositSignatures) + tx, err := pnr.PermissionlessNodeRegistry.AddValidatorKeysWithUtilizeSD(opts, referralID, utilityAmount, pubKeys, preDepositSignatures, depositSignatures) if err != nil { return nil, fmt.Errorf("could not add validator keys with utilize: %w", err) } diff --git a/stader-lib/sdutility/sd-utility.go b/stader-lib/sdutility/sd-utility.go index 486481b81..b1f156253 100644 --- a/stader-lib/sdutility/sd-utility.go +++ b/stader-lib/sdutility/sd-utility.go @@ -19,10 +19,12 @@ func GetPoolAvailableSDBalance(sp *stader.SDUtilityPoolContractManager, opts *bi if err != nil { return nil, err } + sdRequestedForWithdraw, err := GetSdRequestedForWithdraw(sp, opts) if err != nil { return nil, err } + utilityPoolBalance, err := GetUtilityPoolBalance(sp, opts) if err != nil { return nil, err @@ -81,6 +83,10 @@ func RepayFullAmount(sp *stader.SDUtilityPoolContractManager, opts *bind.Transac func SDMaxUtilizableAmount(sp *stader.SDUtilityPoolContractManager, sdc *stader.SdCollateralContractManager, numValidators *big.Int, opts *bind.CallOpts) (*big.Int, error) { maxThreshold, err := sp.SDUtilityPool.MaxETHWorthOfSDPerValidator(opts) + if err != nil { + return nil, err + } + ethAmount := new(big.Int).Mul(maxThreshold, numValidators) sdAmount, err := sdc.SdCollateral.ConvertETHToSD(opts, ethAmount) @@ -115,7 +121,7 @@ func GetUserData(sp *stader.SDUtilityPoolContractManager, address common.Address return &userData, nil } -func AlreadyLiquidated(sp *stader.SDUtilityPoolContractManager, address common.Address, opts *bind.CallOpts) (bool, error) { +func AlreadyLiquidated(sp *stader.SDUtilityPoolContractManager, address common.Address, _opts *bind.CallOpts) (bool, error) { liquidationIndex, err := LiquidationIndexByOperator(sp, address, nil) if err != nil { return false, err diff --git a/stader-lib/socializing-pool/rewards.go b/stader-lib/socializing-pool/rewards.go index 3779e7771..38d706909 100644 --- a/stader-lib/socializing-pool/rewards.go +++ b/stader-lib/socializing-pool/rewards.go @@ -23,11 +23,11 @@ func ClaimRewards(sp *stader.SocializingPoolContractManager, index []*big.Int, a return tx, nil } -func EstimateClaimRewardsAndDepositSD(sp *stader.SocializingPoolContractManager, index []*big.Int, amountSd []*big.Int, amountEth []*big.Int, merkleProof [][][32]byte, opts *bind.TransactOpts) (stader.GasInfo, error) { +func EstimateClaimRewardsAndDepositSD(sp *stader.SocializingPoolContractManager, index, amountSd, amountEth []*big.Int, merkleProof [][][32]byte, opts *bind.TransactOpts) (stader.GasInfo, error) { return sp.SocializingPoolContract.GetTransactionGasInfo(opts, "claimAndDepositSD", index, amountSd, amountEth, merkleProof) } -func ClaimRewardsAndDepositSD(sp *stader.SocializingPoolContractManager, index []*big.Int, amountSd []*big.Int, amountEth []*big.Int, merkleProof [][][32]byte, opts *bind.TransactOpts) (*types.Transaction, error) { +func ClaimRewardsAndDepositSD(sp *stader.SocializingPoolContractManager, index, amountSd, amountEth []*big.Int, merkleProof [][][32]byte, opts *bind.TransactOpts) (*types.Transaction, error) { tx, err := sp.SocializingPool.ClaimAndDepositSD(opts, index, amountSd, amountEth, merkleProof) if err != nil { return nil, err diff --git a/stader-lib/utils/eth/units.go b/stader-lib/utils/eth/units.go index 526f293ad..3f6a15c38 100644 --- a/stader-lib/utils/eth/units.go +++ b/stader-lib/utils/eth/units.go @@ -38,6 +38,7 @@ func DisplayAmountInUnits(wei *big.Int, denom string) string { if denom == "sd" { gweiDenom = " gwei SD" } + regDenom := " ETH" if denom == "sd" { regDenom = " SD" @@ -46,9 +47,11 @@ func DisplayAmountInUnits(wei *big.Int, denom string) string { if wei == nil { return "" } + if wei.Cmp(big.NewInt(Threshold)) < 0 && wei.Cmp(big.NewInt(0)) != 0 { return strconv.FormatFloat(WeiToGwei(wei), 'f', 6, 64) + gweiDenom } + return strconv.FormatFloat(WeiToEth(wei), 'f', 6, 64) + regDenom } diff --git a/stader-lib/utils/sd/sd.go b/stader-lib/utils/sd/sd.go index 3980c8be9..223984986 100644 --- a/stader-lib/utils/sd/sd.go +++ b/stader-lib/utils/sd/sd.go @@ -2,7 +2,6 @@ package sd import ( "fmt" - "math" "math/big" "strconv" @@ -16,10 +15,6 @@ const ( var SDWeiEqualityThreshold = eth.EthToWei(SDFloatStringEqualityThreshold) -func almostEqual(lhs, rhs float64) bool { - return math.Abs(lhs-rhs) <= SDFloatStringEqualityThreshold -} - func WeiAlmostEqual(lhs, rhs *big.Int) bool { diversity := new(big.Int).Sub(lhs, rhs) diff --git a/stader/api/node/claim-rewards.go b/stader/api/node/claim-rewards.go index e06a85671..b5da506dd 100644 --- a/stader/api/node/claim-rewards.go +++ b/stader/api/node/claim-rewards.go @@ -97,11 +97,11 @@ func ClaimRewards(c *cli.Context) (*api.ClaimRewards, error) { return nil, err } - operatorId, err := node.GetOperatorId(pnr, nodeAccount.Address, nil) + operatorID, err := node.GetOperatorId(pnr, nodeAccount.Address, nil) if err != nil { return nil, err } - operatorInfo, err := node.GetOperatorInfo(pnr, operatorId, nil) + operatorInfo, err := node.GetOperatorInfo(pnr, operatorID, nil) if err != nil { return nil, err } diff --git a/stader/api/node/claim-sp-rewards.go b/stader/api/node/claim-sp-rewards.go index c83d68329..ec91e9433 100644 --- a/stader/api/node/claim-sp-rewards.go +++ b/stader/api/node/claim-sp-rewards.go @@ -169,7 +169,7 @@ func estimateSpRewardsGas(c *cli.Context, stringifiedCycles string, depositSd bo return nil, err } - gasInfo := stader.GasInfo{} + var gasInfo stader.GasInfo if depositSd { gasInfo, err = socializing_pool.EstimateClaimRewardsAndDepositSD(sp, cycles, amountSd, amountEth, merkleProofs, opts) if err != nil { diff --git a/stader/guardian/collector/network-collector.go b/stader/guardian/collector/network-collector.go index 0a01e286f..1401f310f 100644 --- a/stader/guardian/collector/network-collector.go +++ b/stader/guardian/collector/network-collector.go @@ -62,7 +62,7 @@ type NetworkCollector struct { // The utilize amount + fee SdUtilityPoolBalance *prometheus.Desc - //Total amount of outstanding SD utilized + // Total amount of outstanding SD utilized TotalSDUtilized *prometheus.Desc TotalValueLocledSDUtilization *prometheus.Desc @@ -151,7 +151,6 @@ func NewNetworkCollector(bc beacon.Client, ec stader.ExecutionClient, nodeAddres "The current balance of the SD utility pool", nil, nil, ), - //Total amount of outstanding SD utilized TotalSDUtilized: prometheus.NewDesc(prometheus.BuildFQName(namespace, subsystem, "total_outstanding_sd_utilized"), "The total the SD utilized in network", nil, nil, diff --git a/stader/guardian/collector/operator-collector.go b/stader/guardian/collector/operator-collector.go index 70b9253fa..e83e2be37 100644 --- a/stader/guardian/collector/operator-collector.go +++ b/stader/guardian/collector/operator-collector.go @@ -143,7 +143,7 @@ func NewOperatorCollector( prometheus.BuildFQName(namespace, OperatorSub, LiquidationStatus), "", nil, nil), ClaimVaultBalance: prometheus.NewDesc( prometheus.BuildFQName(namespace, OperatorSub, ClaimVaultBalance), "", nil, nil), - SDUtilizationPosition: prometheus.NewDesc(prometheus.BuildFQName(namespace, OperatorSub, "sd_utility_positon"), + SDUtilizationPosition: prometheus.NewDesc(prometheus.BuildFQName(namespace, OperatorSub, "sd_utility_position"), "The current balance of the SD utility pool", nil, nil, ), @@ -224,8 +224,8 @@ func (collector *OperatorCollector) Collect(channel chan<- prometheus.Metric) { channel <- prometheus.MustNewConstMetric(collector.SdCollateralPct, prometheus.GaugeValue, state.StaderNetworkDetails.SdCollateralPct) channel <- prometheus.MustNewConstMetric(collector.LockedEth, prometheus.GaugeValue, state.StaderNetworkDetails.LockedEth) channel <- prometheus.MustNewConstMetric(collector.HealthFactor, prometheus.GaugeValue, state.StaderNetworkDetails.HealthFactor) - channel <- prometheus.MustNewConstMetric(collector.TotalSDUtilizationPosition, prometheus.GaugeValue, float64(state.StaderNetworkDetails.OperatorSDUtilizationPosition)) - channel <- prometheus.MustNewConstMetric(collector.TotalSDSelfBond, prometheus.GaugeValue, float64(state.StaderNetworkDetails.OperatorSDSelfBond)) + channel <- prometheus.MustNewConstMetric(collector.TotalSDUtilizationPosition, prometheus.GaugeValue, state.StaderNetworkDetails.OperatorSDUtilizationPosition) + channel <- prometheus.MustNewConstMetric(collector.TotalSDSelfBond, prometheus.GaugeValue, state.StaderNetworkDetails.OperatorSDSelfBond) channel <- prometheus.MustNewConstMetric(collector.LiquidationStatus, prometheus.GaugeValue, state.StaderNetworkDetails.LiquidationStatus) channel <- prometheus.MustNewConstMetric(collector.ClaimVaultBalance, prometheus.GaugeValue, state.StaderNetworkDetails.ClaimVaultBalance) channel <- prometheus.MustNewConstMetric(collector.SDUtilizationPosition, prometheus.GaugeValue, state.StaderNetworkDetails.OperatorSDUtilizationPosition) diff --git a/stader/node/node.go b/stader/node/node.go index aeba383ef..1fbd00d53 100644 --- a/stader/node/node.go +++ b/stader/node/node.go @@ -540,7 +540,6 @@ func makeNodeDiversityMessage( return nil, err } - //fmt.Printf("Get total non terminal validator keys\n") totalNonTerminalValidatorKeys, err := node.GetTotalNonTerminalValidatorKeys(pnr, nodeAccount.Address, totalValidatorKeys, nil) if err != nil { return nil, err