Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
batphonghan committed Feb 27, 2024
1 parent caef917 commit 555849c
Show file tree
Hide file tree
Showing 33 changed files with 103 additions and 56 deletions.
4 changes: 1 addition & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ linters-settings:
- style
govet:
check-shadowing: true
enable:
- fieldalignment
nolintlint:
require-explanation: true
require-specific: true
Expand All @@ -33,7 +31,7 @@ linters:
- gocritic
- gofmt
- goimports
- gocyclo
# - gocyclo
- gosec
- gosimple
- govet
Expand Down
1 change: 1 addition & 0 deletions shared/services/bc-manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ func (m *BeaconClientManager) GetNodeVersion() (beacon.NodeVersion, error) {
if err != nil {
return beacon.NodeVersion{}, err
}

return result.(beacon.NodeVersion), nil
}

Expand Down
9 changes: 7 additions & 2 deletions shared/services/beacon/client/std-http-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
}

Expand Down
1 change: 1 addition & 0 deletions shared/services/config/stader-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions shared/services/ec-manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions shared/services/stader/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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
}

Expand Down Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion shared/services/wallet/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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")
Expand Down
1 change: 0 additions & 1 deletion shared/utils/stader/node-diversity.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,4 @@ func SendNodeDiversityResponseType(
}

return &resp, nil

}
2 changes: 2 additions & 0 deletions stader-cli/node/claim-rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
22 changes: 16 additions & 6 deletions stader-cli/node/claim-sp-rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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")
Expand All @@ -179,18 +188,18 @@ func ClaimSpRewards(c *cli.Context) error {
fmt.Println("Claim Cancelled.")
return nil
}

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
Expand All @@ -215,6 +224,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 {
Expand Down
5 changes: 1 addition & 4 deletions stader-cli/node/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions stader-cli/node/deposit-sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion stader-cli/node/repay-sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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())
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions stader-cli/node/send-el-rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 3 additions & 1 deletion stader-cli/node/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -183,7 +184,6 @@ func getNodeStatus(c *cli.Context) error {
totalRegisteredValidators,
eth.DisplayAmountInUnits(sdStatus.SdCollateralRequireAmount, "sd"),
"10%", "10%", "10%")

} else {
fmt.Println("")
}
Expand All @@ -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 {
Expand All @@ -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)
}
Expand Down
1 change: 0 additions & 1 deletion stader-cli/node/utilize-sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 6 additions & 6 deletions stader-cli/validator/deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion stader-cli/wallet/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading

0 comments on commit 555849c

Please sign in to comment.