From 82548b339a71582a8d858e77391aa43a8c17c028 Mon Sep 17 00:00:00 2001 From: batphonghan Date: Mon, 26 Feb 2024 21:39:04 +0700 Subject: [PATCH] Refactor --- .golangci.yml | 4 +--- shared/services/bc-manager.go | 1 + .../services/beacon/client/std-http-client.go | 9 ++++++-- shared/services/config/stader-config.go | 1 + shared/services/ec-manager.go | 4 ++-- shared/services/stader/node.go | 8 +++++++ shared/services/wallet/node.go | 2 +- shared/utils/stader/node-diversity.go | 1 - stader-cli/node/claim-rewards.go | 2 ++ stader-cli/node/claim-sp-rewards.go | 21 +++++++++++++------ stader-cli/node/commands.go | 5 +---- stader-cli/node/deposit-sd.go | 1 + stader-cli/node/repay-sd.go | 4 +++- stader-cli/node/send-el-rewards.go | 2 ++ stader-cli/node/status.go | 4 +++- stader-cli/node/utilize-sd.go | 1 - stader-cli/validator/deposit.go | 12 +++++------ stader-cli/wallet/export.go | 2 +- 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 | 9 +++----- stader/api/node/claim-rewards.go | 7 ++++--- stader/api/node/claim-sp-rewards.go | 2 +- stader/api/node/deposit-sd.go | 3 +++ stader/api/node/get-contracts-info.go | 10 +++++++++ stader/api/node/status.go | 1 + stader/api/node/utility-sd.go | 5 +++-- stader/api/validator/deposit.go | 4 ++-- .../guardian/collector/network-collector.go | 3 +-- .../guardian/collector/operator-collector.go | 6 +++--- stader/node/node.go | 1 - 33 files changed, 102 insertions(+), 56 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index aa68692b2..ed4f24cf0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,8 +13,6 @@ linters-settings: - style govet: check-shadowing: true - enable: - - fieldalignment nolintlint: require-explanation: true require-specific: true @@ -33,7 +31,7 @@ linters: - gocritic - gofmt - goimports - - gocyclo + # - gocyclo - gosec - gosimple - govet diff --git a/shared/services/bc-manager.go b/shared/services/bc-manager.go index 6ff1b1147..1582123c8 100644 --- a/shared/services/bc-manager.go +++ b/shared/services/bc-manager.go @@ -141,6 +141,7 @@ func (m *BeaconClientManager) GetNodeVersion() (beacon.NodeVersion, error) { if err != nil { return beacon.NodeVersion{}, err } + return result.(beacon.NodeVersion), nil } diff --git a/shared/services/beacon/client/std-http-client.go b/shared/services/beacon/client/std-http-client.go index 34ed242d9..f3f6f9325 100644 --- a/shared/services/beacon/client/std-http-client.go +++ b/shared/services/beacon/client/std-http-client.go @@ -423,10 +423,12 @@ func (c *StandardHttpClient) GetValidatorIndex(pubkey types.ValidatorPubkey) (ui // Get domain data for a domain type at a given epoch func (c *StandardHttpClient) GetExitDomainData(domainType []byte, network config.Network) ([]byte, error) { - var genesis GenesisResponse genesis, err := c.getGenesis() + if err != nil { + return []byte{}, fmt.Errorf("GetGenesis %w", err) + } // Get fork version var capellaForkVersion string @@ -445,8 +447,8 @@ func (c *StandardHttpClient) GetExitDomainData(domainType []byte, network config // Compute & return domain var dt [4]byte copy(dt[:], domainType[:]) - return eth2types.Domain(dt, decodedForkVersion, genesis.Data.GenesisValidatorsRoot), nil + return eth2types.Domain(dt, decodedForkVersion, genesis.Data.GenesisValidatorsRoot), nil } // Perform a voluntary exit on a validator @@ -589,13 +591,16 @@ func (c *StandardHttpClient) getNodeVersion() (NodeVersionResponse, error) { if err != nil { return NodeVersionResponse{}, fmt.Errorf("Could not get node sync status: %w", err) } + if status != http.StatusOK { return NodeVersionResponse{}, fmt.Errorf("Could not get node sync status: HTTP status %d; response body: '%s'", status, string(responseBody)) } + var nodeVersion NodeVersionResponse if err := json.Unmarshal(responseBody, &nodeVersion); err != nil { return NodeVersionResponse{}, fmt.Errorf("Could not decode node sync status: %w", err) } + return nodeVersion, nil } diff --git a/shared/services/config/stader-config.go b/shared/services/config/stader-config.go index 0fce3fd35..474f0b8cc 100644 --- a/shared/services/config/stader-config.go +++ b/shared/services/config/stader-config.go @@ -986,6 +986,7 @@ func (cfg *StaderConfig) GenerateEnvironmentVariables() map[string]string { envVars["PROMETHEUS_ADDITIONAL_FLAGS"] = fmt.Sprintf(", \"%s\"", cfg.Prometheus.AdditionalFlags.Value.(string)) } } + if cfg.ExposeGuardianPort.Value == true { envVars["GUARDIAN_OPEN_PORTS"] = fmt.Sprintf("%d:%d/tcp", cfg.NodeMetricsPort.Value, cfg.NodeMetricsPort.Value) } diff --git a/shared/services/ec-manager.go b/shared/services/ec-manager.go index b3216279a..f61769ff8 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"` + ID int64 `json:"id"` }{ Jsonrpc: "2.0", Method: "web3_clientVersion", Params: []string{}, - Id: 1, + ID: 1, } res, err := net.MakePostRequest(url, payload) diff --git a/shared/services/stader/node.go b/shared/services/stader/node.go index 2febd65db..e3b26ff89 100644 --- a/shared/services/stader/node.go +++ b/shared/services/stader/node.go @@ -118,10 +118,12 @@ func (c *Client) NodeSdApprovalGas(amountWei *big.Int, address common.Address) ( if err != nil { return api.SdApproveGasResponse{}, fmt.Errorf("could not get new SD approval gas: %w", err) } + var response api.SdApproveGasResponse if err := json.Unmarshal(responseBytes, &response); err != nil { return api.SdApproveGasResponse{}, fmt.Errorf("could not decode node deposit S approve gas response: %w", err) } + if response.Error != "" { return api.SdApproveGasResponse{}, fmt.Errorf("could not get new SD approval gas: %s", response.Error) } @@ -134,13 +136,16 @@ func (c *Client) NodeSdApprove(amountWei *big.Int, address common.Address) (api. if err != nil { return api.SdApproveResponse{}, fmt.Errorf("could not approve SD for staking: %w", err) } + var response api.SdApproveResponse if err := json.Unmarshal(responseBytes, &response); err != nil { return api.SdApproveResponse{}, fmt.Errorf("could not decode deposit node SD approve response: %w", err) } + if response.Error != "" { return api.SdApproveResponse{}, fmt.Errorf("could not approve SD for staking: %s", response.Error) } + return response, nil } @@ -196,13 +201,16 @@ func (c *Client) GetNodeSdAllowance(contractAddress common.Address) (api.SdAllow if err != nil { return api.SdAllowanceResponse{}, fmt.Errorf("could not get node deposit SD allowance: %w", err) } + var response api.SdAllowanceResponse if err := json.Unmarshal(responseBytes, &response); err != nil { return api.SdAllowanceResponse{}, fmt.Errorf("could not decode node deposit SD allowance response: %w", err) } + if response.Error != "" { return api.SdAllowanceResponse{}, fmt.Errorf("could not get node deposit SD allowance: %s", response.Error) } + return response, nil } 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-rewards.go b/stader-cli/node/claim-rewards.go index 3161cd8d0..66e9c1068 100644 --- a/stader-cli/node/claim-rewards.go +++ b/stader-cli/node/claim-rewards.go @@ -79,8 +79,10 @@ func ClaimRewards(c *cli.Context) error { if err != nil { return err } + fmt.Printf("Withdrawing %s Rewards to Operator Reward Address: %s\n\n", eth.DisplayAmountInUnits(res.RewardsClaimed, "eth"), res.OperatorRewardAddress) cliutils.PrintTransactionHash(staderClient, res.TxHash) + if _, err = staderClient.WaitForTransaction(res.TxHash); err != nil { return err } diff --git a/stader-cli/node/claim-sp-rewards.go b/stader-cli/node/claim-sp-rewards.go index 18d290084..2f11e9835 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 @@ -215,6 +223,7 @@ func ClaimSpRewards(c *cli.Context) error { } fmt.Printf("Transaction Successful\n") + if depositSd { fmt.Printf("%s rewards have been sent to your Reward Address and %s rewards have been re-deposited as SD collateral\n", eth.DisplayAmountInUnits(totalClaimableEth, "eth"), eth.DisplayAmountInUnits(totalClaimableSd, "sd")) } else { diff --git a/stader-cli/node/commands.go b/stader-cli/node/commands.go index 0aced0956..7b78ad0dd 100644 --- a/stader-cli/node/commands.go +++ b/stader-cli/node/commands.go @@ -367,10 +367,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Usage: "Automatically confirm SD repay", }, }, - Action: func(c *cli.Context) error { - // Run - return repaySD(c) - }, + Action: repaySD, }, { Name: "approve-deposit-sd", 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/repay-sd.go b/stader-cli/node/repay-sd.go index 2143b55a7..6bdbf53d4 100644 --- a/stader-cli/node/repay-sd.go +++ b/stader-cli/node/repay-sd.go @@ -61,6 +61,7 @@ func repaySD(c *cli.Context) error { i, _ := cliutils.Select("Please choose one of the following options for repayment. Enter 1 or 2:", ops) fullRepay := false + var amountWei *big.Int switch i { @@ -86,6 +87,7 @@ func repaySD(c *cli.Context) error { if allowance.Allowance.Cmp(sdStatus.SdUtilizerLatestBalance) < 0 { fmt.Println("Before repaying the SD, you must first give the utility contract approval to interact with your SD.") + maxApproval := maxUint256() err = nodeApproveUtilitySd(c, maxApproval.String()) @@ -131,11 +133,11 @@ func repaySD(c *cli.Context) error { remainUtilize := new(big.Int).Sub(sdStatus.SdUtilizerLatestBalance, amountWei) fmt.Printf("Repayment of %s successful. Current Utilization Position: %s.\n", eth.DisplayAmountInUnits(amountWei, "sd"), eth.DisplayAmountInUnits(remainUtilize, "sd")) } + return nil } func PromptChooseRepayAmount(sdStatus *api.SdStatusResponse) (*big.Int, error) { - msg := fmt.Sprintf(`%sPlease enter the amount of SD you wish to repay. Your current Utilization Position is %s%s`, log.ColorYellow, eth.DisplayAmountInUnits(sdStatus.SdUtilizerLatestBalance, "sd"), log.ColorReset) errMsg := fmt.Sprintf("%sInvalid input, please specify a valid amount of SD you wish to repay. Your current Utilization Position is %s SD%s", log.ColorRed, eth.DisplayAmountInUnits(sdStatus.SdUtilizerLatestBalance, "sd"), log.ColorReset) 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..aec995c87 100644 --- a/stader-cli/node/status.go +++ b/stader-cli/node/status.go @@ -154,6 +154,7 @@ func getNodeStatus(c *cli.Context) error { if err != nil { return err } + collateralPct := 0.0 sdStatus := sdStatusResp.SDStatus totalCollateral := new(big.Int).Add(sdStatus.SdCollateralCurrentAmount, sdStatus.SdUtilizedBalance) @@ -183,7 +184,6 @@ func getNodeStatus(c *cli.Context) error { totalRegisteredValidators, eth.DisplayAmountInUnits(sdStatus.SdCollateralRequireAmount, "sd"), "10%", "10%", "10%") - } else { fmt.Println("") } @@ -194,6 +194,7 @@ func getNodeStatus(c *cli.Context) error { fmt.Printf("The Operator has a current Utilization Position of %s. (including the utilization fee)\n", eth.DisplayAmountInUnits(sdStatus.SdUtilizerLatestBalance, "sd")) + if sdStatus.SdUtilizerLatestBalance.Cmp(big.NewInt(0)) == 0 { fmt.Println("") } else { @@ -204,6 +205,7 @@ func getNodeStatus(c *cli.Context) error { if maxUtilizable.Cmp(sdStatus.PoolAvailableSDBalance) > 0 { maxUtilizable = sdStatus.PoolAvailableSDBalance } + if maxUtilizable.Sign() < 0 { maxUtilizable = big.NewInt(0) } diff --git a/stader-cli/node/utilize-sd.go b/stader-cli/node/utilize-sd.go index 2940b008d..d32fca739 100644 --- a/stader-cli/node/utilize-sd.go +++ b/stader-cli/node/utilize-sd.go @@ -159,7 +159,6 @@ Maximum utilization amount: %s } func PromptChooseSelfBondAmount(sdStatus *api.SdStatusResponse) (*big.Int, error) { - totalCollateral := new(big.Int).Add(sdStatus.SdCollateralCurrentAmount, sdStatus.SdUtilizedBalance) amountToCollateralRemain := new(big.Int).Sub(sdStatus.SdCollateralRequireAmount, totalCollateral) 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-cli/wallet/export.go b/stader-cli/wallet/export.go index f2cba675e..9deae1372 100644 --- a/stader-cli/wallet/export.go +++ b/stader-cli/wallet/export.go @@ -51,7 +51,7 @@ func exportWallet(c *cli.Context) error { // Check if stdout is interactive stat, err := os.Stdout.Stat() if err != nil { - fmt.Fprintf(os.Stderr, "An error occured while determining whether or not the output is a tty: %s\n"+ + fmt.Fprintf(os.Stderr, "An error occurred while determining whether or not the output is a tty: %s\n"+ "Use \"stader-cli --secure-session wallet export\" to bypass.\n", err.Error()) os.Exit(1) } 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..8eb178ee9 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) (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..2c2d7b1b8 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) @@ -37,7 +32,9 @@ func PromptChooseSDWithMaxMin(msg, errMsg string, min, max *big.Int) (*big.Int, `^[0-9]\d*(\.\d+)?$`, errMsg) - utilityAmountFloat, errParse := strconv.ParseFloat(s, 64) + var utilityAmountFloat float64 + utilityAmountFloat, errParse = strconv.ParseFloat(s, 64) + if errParse != nil { fmt.Println(errMsg) continue diff --git a/stader/api/node/claim-rewards.go b/stader/api/node/claim-rewards.go index e06a85671..5df3f01ab 100644 --- a/stader/api/node/claim-rewards.go +++ b/stader/api/node/claim-rewards.go @@ -97,11 +97,12 @@ 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 } @@ -134,8 +135,8 @@ func ClaimRewards(c *cli.Context) (*api.ClaimRewards, error) { if err != nil { return nil, err } - response.RewardsClaimed = totalWithdrawableEth + response.RewardsClaimed = totalWithdrawableEth response.TxHash = tx.Hash() return &response, nil 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/api/node/deposit-sd.go b/stader/api/node/deposit-sd.go index 0ba70afc3..b031dad68 100644 --- a/stader/api/node/deposit-sd.go +++ b/stader/api/node/deposit-sd.go @@ -91,6 +91,7 @@ func getSdApprovalGas(c *cli.Context, amountWei *big.Int, contractAddress common if err != nil { return nil, err } + gasInfo, err := tokens.EstimateApproveGas(sdt, contractAddress, amountWei, opts) if err != nil { return nil, err @@ -153,10 +154,12 @@ func approveSd(c *cli.Context, amountWei *big.Int, contractAddress common.Addres if err != nil { return nil, err } + err = eth1.CheckForNonceOverride(c, opts) if err != nil { return nil, fmt.Errorf("Error checking for nonce override: %w", err) } + hash, err := tokens.Approve(sdt, contractAddress, amountWei, opts) if err != nil { return nil, err diff --git a/stader/api/node/get-contracts-info.go b/stader/api/node/get-contracts-info.go index 72d78261e..b694faaca 100644 --- a/stader/api/node/get-contracts-info.go +++ b/stader/api/node/get-contracts-info.go @@ -18,6 +18,7 @@ func getContractsInfo(c *cli.Context) (*api.ContractsInfoResponse, error) { if err != nil { return nil, fmt.Errorf("Error getting configuration: %w", err) } + response.Network = uint64(config.StaderNode.GetChainID()) response.EncryptionKey = config.StaderNode.GetPresignEncryptionKey() @@ -34,6 +35,7 @@ func getContractsInfo(c *cli.Context) (*api.ContractsInfoResponse, error) { response.BeaconNetwork = eth2DepositContract.ChainID response.BeaconDepositContract = eth2DepositContract.Address + response.SdCollateralContract, err = services.GetSdCollateralAddress(c) if err != nil { return nil, err @@ -44,34 +46,42 @@ func getContractsInfo(c *cli.Context) (*api.ContractsInfoResponse, error) { if err != nil { return nil, err } + response.SdToken, err = services.GetSdTokenAddress(c) if err != nil { return nil, err } + response.PermissionlessNodeRegistry, err = services.GetPermissionlessNodeRegistryAddress(c) if err != nil { return nil, err } + response.VaultFactory, err = services.GetVaultFactoryAddress(c) if err != nil { return nil, err } + response.SocializingPoolContract, err = services.GetSocializingPoolAddress(c) if err != nil { return nil, err } + response.PermisionlessPool, err = services.GetPermissionlessPoolAddress(c) if err != nil { return nil, err } + response.StaderOracle, err = services.GetStaderOracleAddress(c) if err != nil { return nil, err } + response.StakePoolManager, err = services.GetStakePoolManagerAddress(c) if err != nil { return nil, err } + response.SdUtilityContract, err = services.GetSdUtilityAddress(c) if err != nil { return nil, err diff --git a/stader/api/node/status.go b/stader/api/node/status.go index b75a0f141..7b48dff08 100644 --- a/stader/api/node/status.go +++ b/stader/api/node/status.go @@ -183,6 +183,7 @@ func getStatus(c *cli.Context) (*api.NodeStatusResponse, error) { if err != nil { return nil, err } + response.OperatorWithdrawableEth = operatorWithdrawableEth operatorReward, err := tokens.GetEthBalance(pnr.Client, operatorRegistry.OperatorRewardAddress, nil) diff --git a/stader/api/node/utility-sd.go b/stader/api/node/utility-sd.go index 0f031c6d3..7fcd192f4 100644 --- a/stader/api/node/utility-sd.go +++ b/stader/api/node/utility-sd.go @@ -39,15 +39,16 @@ func canUtilitySd(c *cli.Context, amountWei *big.Int) (*api.CanUtilitySDResponse return nil, err } - operatorId, err := node.GetOperatorId(prn, nodeAccount.Address, nil) + operatorID, err := node.GetOperatorId(prn, nodeAccount.Address, nil) if err != nil { return nil, err } - totalValidatorKeys, err := node.GetTotalValidatorKeys(prn, operatorId, nil) + totalValidatorKeys, err := node.GetTotalValidatorKeys(prn, operatorID, nil) if err != nil { return nil, err } + totalValidatorNonTerminalKeys, err := node.GetTotalNonTerminalValidatorKeys(prn, nodeAccount.Address, totalValidatorKeys, nil) if err != nil { return nil, err diff --git a/stader/api/validator/deposit.go b/stader/api/validator/deposit.go index 3a98ebbd2..7e6252f1d 100644 --- a/stader/api/validator/deposit.go +++ b/stader/api/validator/deposit.go @@ -88,7 +88,7 @@ func GetSDStatus( return nil, err } - alreadyLiquidated, err := sdutility.AlreadyLiquidated(sdu, operatorAddress, nil) + alreadyLiquidated, err := sdutility.AlreadyLiquidated(sdu, operatorAddress) if err != nil { return nil, err } @@ -110,7 +110,7 @@ func GetSDStatus( }, nil } -func canNodeDeposit(c *cli.Context, baseAmountWei, utilityAmountWei, numValidators *big.Int, reloadKeys bool) (*api.CanNodeDepositResponse, error) { +func canNodeDeposit(c *cli.Context, baseAmountWei, utilityAmountWei, numValidators *big.Int, _reloadKeys bool) (*api.CanNodeDepositResponse, error) { if err := services.RequireNodeWallet(c); err != nil { return nil, err } 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