Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
batphonghan committed Feb 26, 2024
1 parent caef917 commit fad0f7d
Show file tree
Hide file tree
Showing 19 changed files with 50 additions and 39 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ linters:
- gocritic
- gofmt
- goimports
- gocyclo
# - gocyclo
- gosec
- gosimple
- govet
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"`
IdD int64 `json:"id"`

Check failure on line 544 in shared/services/ec-manager.go

View workflow job for this annotation

GitHub Actions / Lint

var-naming: struct field IdD should be IDD (revive)
}{
Jsonrpc: "2.0",
Method: "web3_clientVersion",
Params: []string{},
Id: 1,
IdD: 1,
}

res, err := net.MakePostRequest(url, payload)
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

}
20 changes: 14 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 @@ -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
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
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
1 change: 0 additions & 1 deletion stader-cli/node/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@ func getNodeStatus(c *cli.Context) error {
totalRegisteredValidators,
eth.DisplayAmountInUnits(sdStatus.SdCollateralRequireAmount, "sd"),
"10%", "10%", "10%")

} else {
fmt.Println("")
}
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
8 changes: 4 additions & 4 deletions stader-lib/node/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
}
Expand Down
8 changes: 7 additions & 1 deletion stader-lib/sdutility/sd-utility.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) {

Check failure on line 124 in stader-lib/sdutility/sd-utility.go

View workflow job for this annotation

GitHub Actions / Lint

unused-parameter: parameter '_opts' seems to be unused, consider removing or renaming it as _ (revive)
liquidationIndex, err := LiquidationIndexByOperator(sp, address, nil)
if err != nil {
return false, err
Expand Down
4 changes: 2 additions & 2 deletions stader-lib/socializing-pool/rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions stader-lib/utils/eth/units.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
}

Expand Down
5 changes: 0 additions & 5 deletions stader-lib/utils/sd/sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package sd

import (
"fmt"
"math"
"math/big"
"strconv"

Expand All @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions stader/api/node/claim-rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion stader/api/node/claim-sp-rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 1 addition & 2 deletions stader/guardian/collector/network-collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions stader/guardian/collector/operator-collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
Expand Down Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion stader/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit fad0f7d

Please sign in to comment.