diff --git a/rocketpool-cli/auction/bid-lot.go b/rocketpool-cli/auction/bid-lot.go index 81ae81df3..7a7b3e370 100644 --- a/rocketpool-cli/auction/bid-lot.go +++ b/rocketpool-cli/auction/bid-lot.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func bidOnLot(c *cli.Context) error { +func bidOnLot(lot, amount string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -47,12 +46,12 @@ func bidOnLot(c *cli.Context) error { // Get selected lot var selectedLot api.LotDetails - if c.String("lot") != "" { + if lot != "" { // Get selected lot index - selectedIndex, err := strconv.ParseUint(c.String("lot"), 10, 64) + selectedIndex, err := strconv.ParseUint(lot, 10, 64) if err != nil { - return fmt.Errorf("Invalid lot ID '%s': %w", c.String("lot"), err) + return fmt.Errorf("Invalid lot ID '%s': %w", lot, err) } // Get matching lot @@ -82,7 +81,7 @@ func bidOnLot(c *cli.Context) error { // Get bid amount var amountWei *big.Int - if c.String("amount") == "max" { + if amount == "max" { // Set bid amount to maximum var tmp big.Int @@ -91,12 +90,12 @@ func bidOnLot(c *cli.Context) error { maxAmount.Quo(&tmp, eth.EthToWei(1)) amountWei = &maxAmount - } else if c.String("amount") != "" { + } else if amount != "" { // Parse amount - bidAmount, err := strconv.ParseFloat(c.String("amount"), 64) + bidAmount, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid bid amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid bid amount '%s': %w", amount, err) } amountWei = eth.EthToWei(bidAmount) @@ -139,13 +138,13 @@ func bidOnLot(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canBid.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canBid.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to bid %.6f ETH on lot %d? Bids are final and non-refundable.", math.RoundDown(eth.WeiToEth(amountWei), 6), selectedLot.Details.Index)) { + if !(yes || prompt.Confirm("Are you sure you want to bid %.6f ETH on lot %d? Bids are final and non-refundable.", math.RoundDown(eth.WeiToEth(amountWei), 6), selectedLot.Details.Index)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/auction/claim-lot.go b/rocketpool-cli/auction/claim-lot.go index 36120cb56..92cdc801d 100644 --- a/rocketpool-cli/auction/claim-lot.go +++ b/rocketpool-cli/auction/claim-lot.go @@ -6,7 +6,6 @@ import ( rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func claimFromLot(c *cli.Context) error { +func claimFromLot(lot string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -47,17 +46,17 @@ func claimFromLot(c *cli.Context) error { // Get selected lots var selectedLots []api.LotDetails - if c.String("lot") == "all" { + if lot == "all" { // Select all claimable lots selectedLots = claimableLots - } else if c.String("lot") != "" { + } else if lot != "" { // Get selected lot index - selectedIndex, err := strconv.ParseUint(c.String("lot"), 10, 64) + selectedIndex, err := strconv.ParseUint(lot, 10, 64) if err != nil { - return fmt.Errorf("Invalid lot ID '%s': %w", c.String("lot"), err) + return fmt.Errorf("Invalid lot ID '%s': %w", lot, err) } // Get matching lot @@ -109,13 +108,13 @@ func claimFromLot(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to claim %d lots?", len(selectedLots))) { + if !(yes || prompt.Confirm("Are you sure you want to claim %d lots?", len(selectedLots))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/auction/commands.go b/rocketpool-cli/auction/commands.go index b159a6c17..ccfafe26c 100644 --- a/rocketpool-cli/auction/commands.go +++ b/rocketpool-cli/auction/commands.go @@ -27,7 +27,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -45,7 +45,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getLots(c) + return getLots() }, }, @@ -63,7 +63,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return createLot(c) + return createLot(c.Bool("yes")) }, }, @@ -107,7 +107,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return bidOnLot(c) + return bidOnLot(c.String("lot"), c.String("amount"), c.Bool("yes")) }, }, @@ -138,7 +138,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return claimFromLot(c) + return claimFromLot(c.String("lot"), c.Bool("yes")) }, }, @@ -169,7 +169,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return recoverRplFromLot(c) + return recoverRplFromLot(c.String("lot"), c.Bool("yes")) }, }, diff --git a/rocketpool-cli/auction/create-lot.go b/rocketpool-cli/auction/create-lot.go index 8f054eec0..745df02de 100644 --- a/rocketpool-cli/auction/create-lot.go +++ b/rocketpool-cli/auction/create-lot.go @@ -3,18 +3,16 @@ package auction import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func createLot(c *cli.Context) error { +func createLot(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -37,13 +35,13 @@ func createLot(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canCreate.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canCreate.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to create this lot?")) { + if !(yes || prompt.Confirm("Are you sure you want to create this lot?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/auction/lots.go b/rocketpool-cli/auction/lots.go index 684d652c4..d1bea51ae 100644 --- a/rocketpool-cli/auction/lots.go +++ b/rocketpool-cli/auction/lots.go @@ -5,17 +5,16 @@ import ( "math/big" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/types/api" "github.com/rocket-pool/smartnode/shared/utils/math" ) -func getLots(c *cli.Context) error { +func getLots() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/auction/recover-lot.go b/rocketpool-cli/auction/recover-lot.go index 214143df7..18ebf82e7 100644 --- a/rocketpool-cli/auction/recover-lot.go +++ b/rocketpool-cli/auction/recover-lot.go @@ -6,7 +6,6 @@ import ( rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func recoverRplFromLot(c *cli.Context) error { +func recoverRplFromLot(lot string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -47,17 +46,17 @@ func recoverRplFromLot(c *cli.Context) error { // Get selected lots var selectedLots []api.LotDetails - if c.String("lot") == "all" { + if lot == "all" { // Select all recoverable lots selectedLots = recoverableLots - } else if c.String("lot") != "" { + } else if lot != "" { // Get selected lot index - selectedIndex, err := strconv.ParseUint(c.String("lot"), 10, 64) + selectedIndex, err := strconv.ParseUint(lot, 10, 64) if err != nil { - return fmt.Errorf("Invalid lot ID '%s': %w", c.String("lot"), err) + return fmt.Errorf("Invalid lot ID '%s': %w", lot, err) } // Get matching lot @@ -109,13 +108,13 @@ func recoverRplFromLot(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to recover %d lots?", len(selectedLots))) { + if !(yes || prompt.Confirm("Are you sure you want to recover %d lots?", len(selectedLots))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/auction/status.go b/rocketpool-cli/auction/status.go index b6b4d22a3..e8ab07219 100644 --- a/rocketpool-cli/auction/status.go +++ b/rocketpool-cli/auction/status.go @@ -4,16 +4,15 @@ import ( "fmt" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/math" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/claims/claim-all.go b/rocketpool-cli/claims/claim-all.go index 6a45f392f..bf52ef779 100644 --- a/rocketpool-cli/claims/claim-all.go +++ b/rocketpool-cli/claims/claim-all.go @@ -18,7 +18,6 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) // pendingClaim represents a single category of rewards that can be claimed. @@ -49,17 +48,15 @@ func (c pendingClaim) valueString() string { } } -func claimAll(c *cli.Context, statusOnly bool) error { +func claimAll(restakeAmount string, statusOnly bool, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() - autoConfirm := c.Bool("yes") - // Track totals totalEthWei := new(big.Int) totalRplWei := new(big.Int) @@ -344,7 +341,7 @@ func claimAll(c *cli.Context, statusOnly bool) error { } if len(missingIntervals) > 0 && !statusOnly { color.YellowPrintf(" Missing or invalid Merkle tree files for intervals: %v\n", missingIntervals) - if autoConfirm || prompt.Confirm(" Would you like to download the missing rewards tree files?") { + if yes || prompt.Confirm(" Would you like to download the missing rewards tree files?") { cfg, _, err := rp.LoadConfig() if err != nil { color.YellowPrintf(" Could not load config for tree download: %s\n", err) @@ -402,12 +399,11 @@ func claimAll(c *cli.Context, statusOnly bool) error { // Parse restake flag (interactive prompt deferred until after claim selection) periodicClaimRpl = prTotalRpl periodicIntervalIndices = intervalIndices - restakeAmountFlag := c.String("restake-amount") - if restakeAmountFlag == "all" { + if restakeAmount == "all" { periodicRestakeAmount = prTotalRpl periodicRestakeResolved = true - } else if restakeAmountFlag != "" { - stakeAmt, parseErr := strconv.ParseFloat(restakeAmountFlag, 64) + } else if restakeAmount != "" { + stakeAmt, parseErr := strconv.ParseFloat(restakeAmount, 64) if parseErr == nil && stakeAmt > 0 { periodicRestakeAmount = eth.EthToWei(stakeAmt) if periodicRestakeAmount.Cmp(prTotalRpl) > 0 { @@ -415,7 +411,7 @@ func claimAll(c *cli.Context, statusOnly bool) error { } } periodicRestakeResolved = true - } else if autoConfirm { + } else if yes { // Ignore restaking if -y is specified but restake-amount isn't periodicRestakeAmount = nil periodicRestakeResolved = true @@ -769,7 +765,7 @@ func claimAll(c *cli.Context, statusOnly bool) error { // Select which claims to execute var selectedClaims []pendingClaim - if autoConfirm { + if yes { selectedClaims = claims } else { indexSelection := prompt.Prompt( @@ -872,13 +868,13 @@ func claimAll(c *cli.Context, statusOnly bool) error { lastGasInfo.SafeGasLimit = totalGasSafe // Get gas fee settings (single prompt for all transactions) - g, err := gas.GetMaxFeeAndLimit(lastGasInfo, rp, autoConfirm) + g, err := gas.GetMaxFeeAndLimit(lastGasInfo, rp, yes) if err != nil { return err } // If a custom nonce is set and there are multiple transactions, warn the user - customNonceSet := c.GlobalUint64("nonce") != 0 + customNonceSet := rocketpool.Defaults.CustomNonce != nil if customNonceSet && len(selectedClaims) > 1 { cliutils.PrintMultiTransactionNonceWarning() } @@ -901,7 +897,7 @@ func claimAll(c *cli.Context, statusOnly bool) error { // If there are more claims and we're not auto-confirming, ask whether to continue remaining := len(selectedClaims) - i - 1 if remaining > 0 { - if autoConfirm { + if yes { color.YellowPrintf(" Continuing with remaining %d claim(s)...\n", remaining) } else { if !prompt.Confirm(" The above claim failed. Continue with the remaining %d claim(s)?", remaining) { diff --git a/rocketpool-cli/claims/commands.go b/rocketpool-cli/claims/commands.go index c41e6dc78..74f6be83b 100644 --- a/rocketpool-cli/claims/commands.go +++ b/rocketpool-cli/claims/commands.go @@ -22,7 +22,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 0); err != nil { return err } - return claimAll(c, true) + return claimAll(c.String("restake-amount"), true, c.Bool("yes")) }, }, { @@ -44,7 +44,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 0); err != nil { return err } - return claimAll(c, false) + return claimAll(c.String("restake-amount"), false, c.Bool("yes")) }, }, }, diff --git a/rocketpool-cli/megapool/claim.go b/rocketpool-cli/megapool/claim.go index dbb2f2b81..2b083c932 100644 --- a/rocketpool-cli/megapool/claim.go +++ b/rocketpool-cli/megapool/claim.go @@ -10,13 +10,12 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) -func claim(c *cli.Context) error { +func claim(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -37,7 +36,7 @@ func claim(c *cli.Context) error { return nil } - if !(c.Bool("yes") || prompt.Confirm("You are about to claim your node refund. Would you like to continue?")) { + if !(yes || prompt.Confirm("You are about to claim your node refund. Would you like to continue?")) { fmt.Println("Cancelled.") return nil } @@ -53,13 +52,13 @@ func claim(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canRepay.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canRepay.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to claim your megapool refund?")) { + if !(yes || prompt.Confirm("Are you sure you want to claim your megapool refund?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/commands.go b/rocketpool-cli/megapool/commands.go index 5b05a26d4..30a4c0fa9 100644 --- a/rocketpool-cli/megapool/commands.go +++ b/rocketpool-cli/megapool/commands.go @@ -42,7 +42,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeMegapoolDeposit(c) + return nodeMegapoolDeposit(c.Uint64("count"), c.Int64("express-tickets"), c.Bool("yes")) }, }, @@ -59,7 +59,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -76,7 +76,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getValidatorStatus(c) + return getValidatorStatus() }, }, @@ -99,7 +99,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return repayDebt(c) + return repayDebt(c.Bool("yes")) }, }, { @@ -121,7 +121,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return reduceBond(c) + return reduceBond(c.Bool("yes")) }, }, { @@ -143,7 +143,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return claim(c) + return claim(c.Bool("yes")) }, }, { @@ -168,8 +168,23 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } + var validatorId uint64 + if !c.IsSet("validator-id") { + var err error + var found bool + validatorId, found, err = getStakableValidator() + if err != nil { + return err + } + if !found { + return nil + } + } else { + validatorId = c.Uint64("validator-id") + } + // Run - return stake(c) + return stake(validatorId, c.Bool("yes")) }, }, { @@ -199,7 +214,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return exitQueue(c) + return exitQueue(c.String("validator-id"), c.Bool("yes")) }, }, { @@ -224,8 +239,23 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } + var validatorId uint64 + if !c.IsSet("validator-id") { + var err error + var found bool + validatorId, found, err = getDissolvableValidator() + if err != nil { + return err + } + if !found { + return nil + } + } else { + validatorId = c.Uint64("validator-id") + } + // Run - return dissolveValidator(c) + return dissolveValidator(validatorId, c.Bool("yes")) }, }, { @@ -250,8 +280,23 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } + var validatorId uint64 + if !c.IsSet("validator-id") { + var err error + var found bool + validatorId, found, err = getExitableValidator() + if err != nil { + return err + } + if !found { + return nil + } + } else { + validatorId = c.Uint64("validator-id") + } + // Run - return exitValidator(c) + return exitValidator(validatorId, c.Bool("yes")) }, }, { @@ -276,8 +321,23 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } + var validatorId uint64 + if !c.IsSet("validator-id") { + var err error + var found bool + validatorId, found, err = getExitedValidator() + if err != nil { + return err + } + if !found { + return nil + } + } else { + validatorId = c.Uint64("validator-id") + } + // Run - return notifyValidatorExit(c) + return notifyValidatorExit(validatorId, c.Bool("yes")) }, }, { @@ -306,8 +366,16 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } + validatorId, validatorIndex, found, err := getNotifiableValidator() + if err != nil { + return err + } + if !found { + return nil + } + // Run - return notifyFinalBalance(c) + return notifyFinalBalance(validatorId, validatorIndex, c.Uint64("slot"), c.Bool("yes")) }, }, { @@ -329,7 +397,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return distribute(c) + return distribute(c.Bool("yes")) }, }, // Add set-use-latest-delegate command @@ -351,7 +419,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } - return setUseLatestDelegateMegapool(c, useLatest) + return setUseLatestDelegateMegapool(useLatest, c.Bool("yes")) }, Flags: []cli.Flag{ cli.BoolFlag{ diff --git a/rocketpool-cli/megapool/delegate.go b/rocketpool-cli/megapool/delegate.go index 06d72a06f..ae86a7ee4 100644 --- a/rocketpool-cli/megapool/delegate.go +++ b/rocketpool-cli/megapool/delegate.go @@ -7,69 +7,11 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func delegateUpgradeMegapool(c *cli.Context) error { - - // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() - if err != nil { - return err - } - defer rp.Close() - - // Get megapool status - status, err := rp.MegapoolStatus(false) - if err != nil { - return err - } - - if status.Megapool.DelegateAddress == status.LatestDelegate || status.Megapool.UseLatestDelegate { - fmt.Printf("The node's megapool: %s is already using the latest delegate\n", status.Megapool.Address.Hex()) - return nil - } - - // Get the gas estimate - canResponse, err := rp.CanDelegateUpgradeMegapool(status.Megapool.Address) - if err != nil { - return fmt.Errorf("error checking if megapool %s can upgrade: %w", status.Megapool.Address.Hex(), err) - } - - // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) - if err != nil { - return err - } - - // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to upgrade your megapool to the latest delegate?")) { - fmt.Println("Cancelled.") - return nil - } - - // Upgrade megapool - response, err := rp.DelegateUpgradeMegapool(status.Megapool.Address) - if err != nil { - fmt.Printf("Could not upgrade megapool %s: %s. \n", status.Megapool.Address.Hex(), err) - return nil - } - - // Log and wait for the auto-upgrade setting update - fmt.Printf("Upgrading megapool %s...\n", status.Megapool.Address.Hex()) - cliutils.PrintTransactionHash(rp, response.TxHash) - if _, err = rp.WaitForTransaction(response.TxHash); err != nil { - return err - } - - // Return - fmt.Printf("Successfully upgraded megapool %s.\n", status.Megapool.Address.Hex()) - return nil -} - -func setUseLatestDelegateMegapool(c *cli.Context, setting bool) error { +func setUseLatestDelegateMegapool(setting bool, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -111,13 +53,13 @@ func setUseLatestDelegateMegapool(c *cli.Context, setting bool) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to change the use-latest-delegate setting for your megapool?")) { + if !(yes || prompt.Confirm("Are you sure you want to change the use-latest-delegate setting for your megapool?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/deposit.go b/rocketpool-cli/megapool/deposit.go index 36848b81d..029048184 100644 --- a/rocketpool-cli/megapool/deposit.go +++ b/rocketpool-cli/megapool/deposit.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "golang.org/x/sync/errgroup" "github.com/rocket-pool/smartnode/shared/services/gas" @@ -23,10 +22,10 @@ const ( maxCount uint64 = 35 ) -func nodeMegapoolDeposit(c *cli.Context) error { +func nodeMegapoolDeposit(count uint64, expressTickets int64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -86,8 +85,6 @@ func nodeMegapoolDeposit(c *cli.Context) error { return err } - count := c.Uint64("count") - // If the count was not provided, prompt the user for the number of deposits for count == 0 || count > maxCount { countStr := prompt.Prompt(fmt.Sprintf("How many validators would you like to create? (max: %d)", maxCount), "^\\d+$", "Invalid number.") @@ -135,7 +132,7 @@ func nodeMegapoolDeposit(c *cli.Context) error { fmt.Printf("The total bond requirement is %.2f ETH.\n", totalBondRequirementEth) fmt.Println() - if !(c.Bool("yes") || prompt.Confirm("%s%s", + if !(yes || prompt.Confirm("%s%s", color.YellowSprintf("NOTE: You are about to create %d new megapool validator(s), requiring a total of: %.2f ETH).\n", count, totalBondRequirementEth), "Would you like to continue?", )) { @@ -163,7 +160,6 @@ func nodeMegapoolDeposit(c *cli.Context) error { } fmt.Println() - expressTickets := c.Int64("express-tickets") if expressTickets >= 0 { if expressTicketCount < uint64(expressTickets) { expressTickets = int64(expressTicketCount) @@ -236,7 +232,7 @@ func nodeMegapoolDeposit(c *cli.Context) error { fmt.Println() } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Would you like to continue?")) { + if !(yes || prompt.Confirm("Would you like to continue?")) { fmt.Println("Cancelled.") return nil } @@ -265,14 +261,14 @@ func nodeMegapoolDeposit(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canDeposit.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canDeposit.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("You are about to deposit %.6f ETH to create %d new megapool validator(s).\n%s", + if !(yes || prompt.Confirm("You are about to deposit %.6f ETH to create %d new megapool validator(s).\n%s", math.RoundDown(eth.WeiToEth(totalBondRequirement), 6), count, color.Yellow("ARE YOU SURE YOU WANT TO DO THIS?"), diff --git a/rocketpool-cli/megapool/dissolve-validator.go b/rocketpool-cli/megapool/dissolve-validator.go index 0a9558bcc..c12f8ab11 100644 --- a/rocketpool-cli/megapool/dissolve-validator.go +++ b/rocketpool-cli/megapool/dissolve-validator.go @@ -8,52 +8,55 @@ import ( "github.com/rocket-pool/smartnode/shared/types/api" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func dissolveValidator(c *cli.Context) error { +func getDissolvableValidator() (uint64, bool, error) { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { - return err + return 0, false, err } defer rp.Close() - var validatorId uint64 + // Get Megapool status + status, err := rp.MegapoolStatus(false) + if err != nil { + return 0, false, err + } + + validatorsInPrestake := []api.MegapoolValidatorDetails{} - if c.IsSet("validator-id") { - validatorId = c.Uint64("validator-id") - } else { - // Get Megapool status - status, err := rp.MegapoolStatus(false) - if err != nil { - return err + for _, validator := range status.Megapool.Validators { + if validator.InPrestake { + validatorsInPrestake = append(validatorsInPrestake, validator) } + } - validatorsInPrestake := []api.MegapoolValidatorDetails{} + if len(validatorsInPrestake) == 0 { + fmt.Println("No validators can be dissolved at the moment") + return 0, false, nil + } - for _, validator := range status.Megapool.Validators { - if validator.InPrestake { - validatorsInPrestake = append(validatorsInPrestake, validator) - } - } - if len(validatorsInPrestake) > 0 { + options := make([]string, len(validatorsInPrestake)) + for vi, v := range validatorsInPrestake { + options[vi] = fmt.Sprintf("ID: %d - Pubkey: 0x%s (Last ETH assignment: %s)", v.ValidatorId, v.PubKey.String(), v.LastAssignmentTime.Format(cliutils.TimeFormat)) + } + selected, _ := prompt.Select("Please select a validator to DISSOLVE:", options) - options := make([]string, len(validatorsInPrestake)) - for vi, v := range validatorsInPrestake { - options[vi] = fmt.Sprintf("ID: %d - Pubkey: 0x%s (Last ETH assignment: %s)", v.ValidatorId, v.PubKey.String(), v.LastAssignmentTime.Format(TimeFormat)) - } - selected, _ := prompt.Select("Please select a validator to DISSOLVE:", options) + // Get validators + validatorId := uint64(validatorsInPrestake[selected].ValidatorId) + return validatorId, true, nil +} - // Get validators - validatorId = uint64(validatorsInPrestake[selected].ValidatorId) +func dissolveValidator(validatorId uint64, yes bool) error { - } else { - fmt.Println("No validators can be dissolved at the moment") - return nil - } + // Get RP client + rp, err := rocketpool.NewClient().WithReady() + if err != nil { + return err } + defer rp.Close() // Check megapool validator can be dissolved canDissolve, err := rp.CanDissolveValidator(validatorId) @@ -69,13 +72,13 @@ func dissolveValidator(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canDissolve.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canDissolve.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to DISSOLVE megapool validator ID: %d?", validatorId)) { + if !(yes || prompt.Confirm("Are you sure you want to DISSOLVE megapool validator ID: %d?", validatorId)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/distribute.go b/rocketpool-cli/megapool/distribute.go index 64e06f13f..0d63a7bd4 100644 --- a/rocketpool-cli/megapool/distribute.go +++ b/rocketpool-cli/megapool/distribute.go @@ -10,13 +10,12 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func distribute(c *cli.Context) error { +func distribute(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -81,13 +80,13 @@ func distribute(c *cli.Context) error { fmt.Println() // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to distribute your megapool rewards?")) { + if !(yes || prompt.Confirm("Are you sure you want to distribute your megapool rewards?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/exit-queue.go b/rocketpool-cli/megapool/exit-queue.go index 921361af3..8ed06d802 100644 --- a/rocketpool-cli/megapool/exit-queue.go +++ b/rocketpool-cli/megapool/exit-queue.go @@ -11,14 +11,13 @@ import ( "github.com/rocket-pool/smartnode/shared/types/api" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) // Exit the megapool queue -func exitQueue(c *cli.Context) error { +func exitQueue(validatorId string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -27,8 +26,7 @@ func exitQueue(c *cli.Context) error { var selectedValidators []api.MegapoolValidatorDetails // Check if the validator id flag is set - if c.String("validator-id") != "" { - flagValue := c.String("validator-id") + if validatorId != "" { // Get Megapool status to resolve validator details status, err := rp.MegapoolStatus(false) @@ -43,7 +41,7 @@ func exitQueue(c *cli.Context) error { } } - if strings.ToLower(flagValue) == "all" { + if strings.ToLower(validatorId) == "all" { if len(validatorsInQueue) == 0 { fmt.Println("No validators can exit the queue at the moment") return nil @@ -51,7 +49,7 @@ func exitQueue(c *cli.Context) error { selectedValidators = validatorsInQueue } else { // Parse comma-separated validator IDs - ids := strings.Split(flagValue, ",") + ids := strings.Split(validatorId, ",") for _, idStr := range ids { idStr = strings.TrimSpace(idStr) validatorId, err := strconv.ParseUint(idStr, 10, 64) @@ -158,18 +156,18 @@ func exitQueue(c *cli.Context) error { } // If a custom nonce is set and there are multiple transactions, warn the user - if c.GlobalUint64("nonce") != 0 && len(canExitResponses) > 1 { + if rocketpool.Defaults.CustomNonce != nil && len(canExitResponses) > 1 { cliutils.PrintMultiTransactionNonceWarning() } // Assign max fees - err = gas.AssignMaxFeeAndLimit(totalGasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(totalGasInfo, rp, yes) if err != nil { return err } // Ask for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to exit %d validator(s) from the megapool queue?", len(canExitResponses))) { + if !(yes || prompt.Confirm("Are you sure you want to exit %d validator(s) from the megapool queue?", len(canExitResponses))) { fmt.Println("Cancelled.") return nil } @@ -196,7 +194,7 @@ func exitQueue(c *cli.Context) error { } // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } } diff --git a/rocketpool-cli/megapool/exit-validator.go b/rocketpool-cli/megapool/exit-validator.go index a8c48e0b5..c0fd24d33 100644 --- a/rocketpool-cli/megapool/exit-validator.go +++ b/rocketpool-cli/megapool/exit-validator.go @@ -8,7 +8,6 @@ import ( "github.com/rocket-pool/smartnode/shared/types/api" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) type ByIndex []api.MegapoolValidatorDetails @@ -17,55 +16,57 @@ func (a ByIndex) Len() int { return len(a) } func (a ByIndex) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByIndex) Less(i, j int) bool { return a[i].ValidatorIndex < a[j].ValidatorIndex } -func exitValidator(c *cli.Context) error { - +func getExitableValidator() (uint64, bool, error) { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { - return err + return 0, false, err } defer rp.Close() - // List the validators that can be exited - var validatorId uint64 - - if c.IsSet("validator-id") { - validatorId = c.Uint64("validator-id") - } else { - // Get Megapool status - status, err := rp.MegapoolStatus(false) - if err != nil { - return err - } + // Get Megapool status + status, err := rp.MegapoolStatus(false) + if err != nil { + return 0, false, err + } - activeValidators := []api.MegapoolValidatorDetails{} + activeValidators := []api.MegapoolValidatorDetails{} - for _, validator := range status.Megapool.Validators { - if validator.Activated && !validator.Exiting && !validator.Exited { - // Check if validator is old enough to exit - earliestExitEpoch := validator.BeaconStatus.ActivationEpoch + 256 - if status.BeaconHead.Epoch >= earliestExitEpoch { - activeValidators = append(activeValidators, validator) - } + for _, validator := range status.Megapool.Validators { + if validator.Activated && !validator.Exiting && !validator.Exited { + // Check if validator is old enough to exit + earliestExitEpoch := validator.BeaconStatus.ActivationEpoch + 256 + if status.BeaconHead.Epoch >= earliestExitEpoch { + activeValidators = append(activeValidators, validator) } } - if len(activeValidators) > 0 { - sort.Sort(ByIndex(activeValidators)) + } + if len(activeValidators) > 0 { + sort.Sort(ByIndex(activeValidators)) - options := make([]string, len(activeValidators)) - for vi, v := range activeValidators { - options[vi] = fmt.Sprintf("ID: %d - Index: %d Pubkey: 0x%s", v.ValidatorId, v.ValidatorIndex, v.PubKey.String()) - } - selected, _ := prompt.Select("Please select a validator to EXIT:", options) + options := make([]string, len(activeValidators)) + for vi, v := range activeValidators { + options[vi] = fmt.Sprintf("ID: %d - Index: %d Pubkey: 0x%s", v.ValidatorId, v.ValidatorIndex, v.PubKey.String()) + } + selected, _ := prompt.Select("Please select a validator to EXIT:", options) - // Get validators - validatorId = uint64(activeValidators[selected].ValidatorId) + // Get validators + return uint64(activeValidators[selected].ValidatorId), true, nil - } else { - fmt.Println("No validators can be exited at the moment") - return nil - } + } else { + fmt.Println("No validators can be exited at the moment") + return 0, false, nil + } +} + +func exitValidator(validatorId uint64, yes bool) error { + + // Get RP client + rp, err := rocketpool.NewClient().WithReady() + if err != nil { + return err } + defer rp.Close() response, err := rp.CanExitValidator(validatorId) if err != nil { @@ -86,7 +87,7 @@ func exitValidator(c *cli.Context) error { fmt.Println() // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to EXIT validator id %d?", validatorId)) { + if !(yes || prompt.Confirm("Are you sure you want to EXIT validator id %d?", validatorId)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/notify-final-balance.go b/rocketpool-cli/megapool/notify-final-balance.go index dd475f6bd..d2ef584d7 100644 --- a/rocketpool-cli/megapool/notify-final-balance.go +++ b/rocketpool-cli/megapool/notify-final-balance.go @@ -14,66 +14,62 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func notifyFinalBalance(c *cli.Context) error { +func getNotifiableValidator() (uint64, uint64, bool, error) { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { - return err + return 0, 0, false, err } defer rp.Close() - - // Get the config - cfg, _, err := rp.LoadConfig() + // Get Megapool status + status, err := rp.MegapoolStatus(true) if err != nil { - return fmt.Errorf("Error loading configuration: %w", err) + return 0, 0, false, err } - var validatorId uint64 - var validatorIndex uint64 + exitingValidators := []api.MegapoolValidatorDetails{} - if c.IsSet("validator-id") { - validatorId = c.Uint64("validator-id") - } else { - // Get Megapool status - status, err := rp.MegapoolStatus(true) - if err != nil { - return err + for _, validator := range status.Megapool.Validators { + if validator.Exiting && validator.BeaconStatus.Status == beacon.ValidatorState_WithdrawalDone { + exitingValidators = append(exitingValidators, validator) } + } + if len(exitingValidators) > 0 { + sort.Sort(ByIndex(exitingValidators)) + options := make([]string, len(exitingValidators)) + for vi, v := range exitingValidators { + options[vi] = fmt.Sprintf("ID: %d - Index: %d - Pubkey: 0x%s", v.ValidatorId, v.ValidatorIndex, v.PubKey.String()) + } + selected, _ := prompt.Select("Please select a validator to notify the final balance:", options) - exitingValidators := []api.MegapoolValidatorDetails{} + // Get validators + return uint64(exitingValidators[selected].ValidatorId), uint64(exitingValidators[selected].ValidatorIndex), true, nil - for _, validator := range status.Megapool.Validators { - if validator.Exiting && validator.BeaconStatus.Status == beacon.ValidatorState_WithdrawalDone { - exitingValidators = append(exitingValidators, validator) - } - } - if len(exitingValidators) > 0 { - sort.Sort(ByIndex(exitingValidators)) - options := make([]string, len(exitingValidators)) - for vi, v := range exitingValidators { - options[vi] = fmt.Sprintf("ID: %d - Index: %d - Pubkey: 0x%s", v.ValidatorId, v.ValidatorIndex, v.PubKey.String()) - } - selected, _ := prompt.Select("Please select a validator to notify the final balance:", options) + } else { + fmt.Println("No validators at the state where the full withdrawal can be proved") + return 0, 0, false, nil + } +} - // Get validators - validatorId = uint64(exitingValidators[selected].ValidatorId) - validatorIndex = uint64(exitingValidators[selected].ValidatorIndex) +func notifyFinalBalance(validatorId, validatorIndex, slot uint64, yes bool) error { - } else { - fmt.Println("No validators at the state where the full withdrawal can be proved") - return nil - } + // Get RP client + rp, err := rocketpool.NewClient().WithReady() + if err != nil { + return err } - slot := uint64(0) + defer rp.Close() - if c.IsSet("slot") { - fmt.Println("Using withdrawal slot: ", c.Uint64("slot")) - slot = c.Uint64("slot") - } else { + // Get the config + cfg, _, err := rp.LoadConfig() + if err != nil { + return fmt.Errorf("Error loading configuration: %w", err) + } + + if slot == 0 { fmt.Println("The Smart Node needs to find the slot containing the validator withdrawal. This may take a while. You can speed up the final balance proof generation by submitting the withdrawal slot for your validator.") fmt.Println() @@ -103,13 +99,13 @@ func notifyFinalBalance(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(response.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(response.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to notify the final balance for validator id %d exit?", validatorId)) { + if !(yes || prompt.Confirm("Are you sure you want to notify the final balance for validator id %d exit?", validatorId)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/notify-validator-exit.go b/rocketpool-cli/megapool/notify-validator-exit.go index f4bb11ee5..5070f4122 100644 --- a/rocketpool-cli/megapool/notify-validator-exit.go +++ b/rocketpool-cli/megapool/notify-validator-exit.go @@ -9,55 +9,56 @@ import ( "github.com/rocket-pool/smartnode/shared/types/api" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) const FarFutureEpoch uint64 = 0xffffffffffffffff -func notifyValidatorExit(c *cli.Context) error { +func getExitedValidator() (uint64, bool, error) { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { - return err + return 0, false, err } defer rp.Close() + // Get Megapool status + status, err := rp.MegapoolStatus(true) + if err != nil { + return 0, false, err + } - // List the validators that can be exited - var validatorId uint64 + activeValidators := []api.MegapoolValidatorDetails{} - if c.IsSet("validator-id") { - validatorId = c.Uint64("validator-id") - } else { - // Get Megapool status - status, err := rp.MegapoolStatus(true) - if err != nil { - return err + for _, validator := range status.Megapool.Validators { + if validator.Activated && !validator.Exiting && !validator.Exited && validator.BeaconStatus.WithdrawableEpoch != FarFutureEpoch { + activeValidators = append(activeValidators, validator) } + } + if len(activeValidators) > 0 { + sort.Sort(ByIndex(activeValidators)) + options := make([]string, len(activeValidators)) + for vi, v := range activeValidators { + options[vi] = fmt.Sprintf("ID: %d - Index: %d - Pubkey: 0x%s", v.ValidatorId, v.ValidatorIndex, v.PubKey.String()) + } + selected, _ := prompt.Select("Please select a validator to notify the exit:", options) - activeValidators := []api.MegapoolValidatorDetails{} + // Get validators + return uint64(activeValidators[selected].ValidatorId), true, nil - for _, validator := range status.Megapool.Validators { - if validator.Activated && !validator.Exiting && !validator.Exited && validator.BeaconStatus.WithdrawableEpoch != FarFutureEpoch { - activeValidators = append(activeValidators, validator) - } - } - if len(activeValidators) > 0 { - sort.Sort(ByIndex(activeValidators)) - options := make([]string, len(activeValidators)) - for vi, v := range activeValidators { - options[vi] = fmt.Sprintf("ID: %d - Index: %d - Pubkey: 0x%s", v.ValidatorId, v.ValidatorIndex, v.PubKey.String()) - } - selected, _ := prompt.Select("Please select a validator to notify the exit:", options) - - // Get validators - validatorId = uint64(activeValidators[selected].ValidatorId) - - } else { - fmt.Println("Can't notify the exit of any validators") - return nil - } + } else { + fmt.Println("Can't notify the exit of any validators") + return 0, false, nil } +} + +func notifyValidatorExit(validatorId uint64, yes bool) error { + + // Get RP client + rp, err := rocketpool.NewClient().WithReady() + if err != nil { + return err + } + defer rp.Close() response, err := rp.CanNotifyValidatorExit(validatorId) if err != nil { @@ -69,13 +70,13 @@ func notifyValidatorExit(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(response.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(response.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to notify about the validator id %d exit?", validatorId)) { + if !(yes || prompt.Confirm("Are you sure you want to notify about the validator id %d exit?", validatorId)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/reduce-bond.go b/rocketpool-cli/megapool/reduce-bond.go index 08fe7f399..ea31725e9 100644 --- a/rocketpool-cli/megapool/reduce-bond.go +++ b/rocketpool-cli/megapool/reduce-bond.go @@ -10,13 +10,12 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) -func reduceBond(c *cli.Context) error { +func reduceBond(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -68,13 +67,13 @@ func reduceBond(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canReduceBond.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canReduceBond.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to reduce %.6f of the megapool bond?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to reduce %.6f of the megapool bond?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/repay-debt.go b/rocketpool-cli/megapool/repay-debt.go index 7cbb195a6..b9b488945 100644 --- a/rocketpool-cli/megapool/repay-debt.go +++ b/rocketpool-cli/megapool/repay-debt.go @@ -11,13 +11,12 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) -func repayDebt(c *cli.Context) error { +func repayDebt(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -60,13 +59,13 @@ func repayDebt(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canRepay.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canRepay.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to repay %.6f ETH of megapool debt?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to repay %.6f ETH of megapool debt?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/stake.go b/rocketpool-cli/megapool/stake.go index da7cd1111..c598cb0da 100644 --- a/rocketpool-cli/megapool/stake.go +++ b/rocketpool-cli/megapool/stake.go @@ -8,70 +8,70 @@ import ( "github.com/rocket-pool/smartnode/shared/types/api" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func stake(c *cli.Context) error { - +func getStakableValidator() (uint64, bool, error) { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { - return err + return 0, false, err } defer rp.Close() + // Get Megapool status + status, err := rp.MegapoolStatus(false) + if err != nil { + return 0, false, err + } - validatorId := uint64(0) - - // check if the validator-id flag was used - if c.IsSet("validator-id") { - validatorId = c.Uint64("validator-id") - } else { - // Get Megapool status - status, err := rp.MegapoolStatus(false) - if err != nil { - return err - } - - validatorsReadyToStake := []api.MegapoolValidatorDetails{} - validatorsDepositPending := []api.MegapoolValidatorDetails{} + validatorsReadyToStake := []api.MegapoolValidatorDetails{} + validatorsDepositPending := []api.MegapoolValidatorDetails{} - for _, validator := range status.Megapool.Validators { - if validator.InPrestake { - if validator.BeaconStatus.Index != "" { - validatorsReadyToStake = append(validatorsReadyToStake, validator) - } else { - validatorsDepositPending = append(validatorsDepositPending, validator) - } + for _, validator := range status.Megapool.Validators { + if validator.InPrestake { + if validator.BeaconStatus.Index != "" { + validatorsReadyToStake = append(validatorsReadyToStake, validator) + } else { + validatorsDepositPending = append(validatorsDepositPending, validator) } } - if len(validatorsDepositPending) > 0 { - fmt.Println("The following validators have a pending deposit. Please wait until the deposit is processed before trying again:") - for _, v := range validatorsDepositPending { - fmt.Printf(" - Pubkey: 0x%s (Last ETH assignment: %s)\n", v.PubKey.String(), v.LastAssignmentTime.Format(TimeFormat)) - } - fmt.Println() + } + if len(validatorsDepositPending) > 0 { + fmt.Println("The following validators have a pending deposit. Please wait until the deposit is processed before trying again:") + for _, v := range validatorsDepositPending { + fmt.Printf(" - Pubkey: 0x%s (Last ETH assignment: %s)\n", v.PubKey.String(), v.LastAssignmentTime.Format(cliutils.TimeFormat)) } - if len(validatorsReadyToStake) > 0 { - fmt.Println("The following validators are ready to be staked:") - options := make([]string, len(validatorsReadyToStake)) - for vi, v := range validatorsReadyToStake { - options[vi] = fmt.Sprintf("Pubkey: 0x%s (Last ETH assignment: %s)", v.PubKey.String(), v.LastAssignmentTime.Format(TimeFormat)) - } - selected, _ := prompt.Select("Please select a validator to stake:", options) + fmt.Println() + } + if len(validatorsReadyToStake) > 0 { + fmt.Println("The following validators are ready to be staked:") + options := make([]string, len(validatorsReadyToStake)) + for vi, v := range validatorsReadyToStake { + options[vi] = fmt.Sprintf("Pubkey: 0x%s (Last ETH assignment: %s)", v.PubKey.String(), v.LastAssignmentTime.Format(cliutils.TimeFormat)) + } + selected, _ := prompt.Select("Please select a validator to stake:", options) - // Get validators - validatorId = uint64(validatorsReadyToStake[selected].ValidatorId) + // Get validators + return uint64(validatorsReadyToStake[selected].ValidatorId), true, nil - } else { - fmt.Println("No validators can be staked at the moment") - return nil - } + } - // Warning reg the time necessary to build the proof - if !(c.Bool("yes") || prompt.Confirm("The stake operation will construct a beacon state proof that the deposit for validator ID %d was correct. This will take several seconds to finish.\nDo you want to continue?", validatorId)) { - fmt.Println("Cancelled.") - return nil - } + fmt.Println("No validators can be staked at the moment") + return 0, false, nil +} + +func stake(validatorId uint64, yes bool) error { + + // Get RP client + rp, err := rocketpool.NewClient().WithReady() + if err != nil { + return err + } + defer rp.Close() + + // Warning reg the time necessary to build the proof + if !(yes || prompt.Confirm("The stake operation will construct a beacon state proof that the deposit for validator ID %d was correct. This will take several seconds to finish.\nDo you want to continue?", validatorId)) { + fmt.Println("Cancelled.") + return nil } // Check megapool validator can be staked @@ -90,13 +90,13 @@ func stake(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canStake.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canStake.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to stake validator id %d", validatorId)) { + if !(yes || prompt.Confirm("Are you sure you want to stake validator id %d", validatorId)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/megapool/status.go b/rocketpool-cli/megapool/status.go index 8fd1af54d..f6f721600 100644 --- a/rocketpool-cli/megapool/status.go +++ b/rocketpool-cli/megapool/status.go @@ -12,17 +12,12 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) -const ( - TimeFormat = "2006-01-02, 15:04 -0700 MST" -) - -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -138,9 +133,9 @@ func getStatus(c *cli.Context) error { } -func getValidatorStatus(c *cli.Context) error { +func getValidatorStatus() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/minipool/close.go b/rocketpool-cli/minipool/close.go index 964e1da31..61deedb2d 100644 --- a/rocketpool-cli/minipool/close.go +++ b/rocketpool-cli/minipool/close.go @@ -9,7 +9,6 @@ import ( rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/beacon" "github.com/rocket-pool/smartnode/shared/services/gas" @@ -21,10 +20,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func closeMinipools(c *cli.Context) error { +func closeMinipools(minipool string, confirmSlashing, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -42,7 +41,7 @@ func closeMinipools(c *cli.Context) error { fmt.Println("Cancelled.") return nil } - if c.Bool("yes") || prompt.ConfirmYellow("Would you like to provision express queue tickets for the node?") { + if yes || prompt.ConfirmYellow("Would you like to provision express queue tickets for the node?") { // Check if the node can provision express tickets canProvision, err := rp.CanProvisionExpressTickets() if err != nil { @@ -150,7 +149,7 @@ func closeMinipools(c *cli.Context) error { // Get selected minipools var selectedMinipools []api.MinipoolCloseDetails - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(closableMinipools)+1) @@ -174,10 +173,10 @@ func closeMinipools(c *cli.Context) error { } else { // Get matching minipools - if c.String("minipool") == "all" { + if minipool == "all" { selectedMinipools = closableMinipools } else { - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for _, minipool := range closableMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipools = []api.MinipoolCloseDetails{minipool} @@ -213,7 +212,7 @@ func closeMinipools(c *cli.Context) error { // Less than the user deposit balance, ETH + RPL will be slashed color.RedPrintf("WARNING: Minipool %s has a distributable balance of %.6f ETH which is lower than the amount borrowed from the staking pool (%.6f ETH).\n", minipool.Address.Hex(), math.RoundDown(eth.WeiToEth(distributableBalance), 6), math.RoundDown(eth.WeiToEth(minipool.UserDepositBalance), 6)) color.RedPrintln("Please visit the Rocket Pool Discord's #support channel (https://discord.gg/rocketpool) if you are not expecting this.") - if !c.Bool("confirm-slashing") { + if !confirmSlashing { fmt.Println() color.RedPrintln("If you are *sure* you want to close the minipool anyway, rerun this command with the `--confirm-slashing` flag. Doing so WILL RESULT in both your ETH bond and your RPL collateral being slashed.") return nil @@ -258,13 +257,13 @@ func closeMinipools(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to close %d minipools?", len(selectedMinipools))) { + if !(yes || prompt.Confirm("Are you sure you want to close %d minipools?", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/commands.go b/rocketpool-cli/minipool/commands.go index a43aa3494..d2c715c87 100644 --- a/rocketpool-cli/minipool/commands.go +++ b/rocketpool-cli/minipool/commands.go @@ -33,7 +33,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus(c.Bool("include-finalized")) }, }, @@ -64,7 +64,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return stakeMinipools(c) + return stakeMinipools(c.String("minipool"), c.Bool("yes")) }, }, @@ -92,7 +92,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return setWithdrawalCreds(c, address) + return setWithdrawalCreds(c.String("mnemonic"), address) }, }, @@ -127,7 +127,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return importKey(c, address) + return importKey(c.String("mnemonic"), c.Bool("no-restart"), c.Bool("yes"), address) }, }, @@ -157,7 +157,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return promoteMinipools(c) + return promoteMinipools(c.String("minipool"), c.Bool("yes")) }, }, @@ -188,7 +188,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return refundMinipools(c) + return refundMinipools(c.String("minipool"), c.Bool("yes")) }, }, @@ -227,44 +227,10 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return distributeBalance(c) + return distributeBalance(c.String("minipool"), c.Float64("threshold"), c.Bool("yes")) }, }, - - /* - REMOVED UNTIL BEACON WITHDRAWALS - cli.Command{ - Name: "dissolve", - Aliases: []string{"d"}, - Usage: "Dissolve initialized or prelaunch minipools", - UsageText: "rocketpool minipool dissolve [options]", - Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "yes, y", - Usage: "Automatically confirm dissolving minipool/s", - }, - cli.StringFlag{ - Name: "minipool, m", - Usage: "The minipool/s to dissolve (address or 'all')", - }, - }, - Action: func(c *cli.Context) error { - - // Validate args - if err := cliutils.ValidateArgCount(c, 0); err != nil { return err } - - // Validate flags - if c.String("minipool") != "" && c.String("minipool") != "all" { - if _, err := cliutils.ValidateAddress("minipool address", c.String("minipool")); err != nil { return err } - } - - // Run - return dissolveMinipools(c) - - }, - }, - */ { Name: "exit", Aliases: []string{"e"}, @@ -295,7 +261,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return exitMinipools(c) + return exitMinipools(c.String("minipool"), c.Bool("yes")) }, }, @@ -330,7 +296,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return closeMinipools(c) + return closeMinipools(c.String("minipool"), c.Bool("confirm-slashing"), c.Bool("yes")) }, }, @@ -365,7 +331,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return delegateUpgradeMinipools(c) + return delegateUpgradeMinipools(c.String("minipool"), c.Bool("include-finalized"), c.Bool("yes")) }, }, @@ -407,7 +373,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { // Validate flags // Run - return findVanitySalt(c) + return findVanitySalt(c.String("prefix"), c.String("salt"), c.Int("threads"), c.String("node-address"), c.String("amount")) }, }, @@ -446,7 +412,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return rescueDissolved(c) + return rescueDissolved(c.String("minipool"), c.String("amount"), c.Bool("no-send"), c.Bool("yes")) }, }, diff --git a/rocketpool-cli/minipool/delegate.go b/rocketpool-cli/minipool/delegate.go index 2993b9397..a8cf9ff5c 100644 --- a/rocketpool-cli/minipool/delegate.go +++ b/rocketpool-cli/minipool/delegate.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/shared/services/gas" @@ -14,10 +13,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func delegateUpgradeMinipools(c *cli.Context) error { +func delegateUpgradeMinipools(minipool string, includeFinalized, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -33,8 +32,6 @@ func delegateUpgradeMinipools(c *cli.Context) error { return err } - includeFinalized := c.Bool("include-finalized") - minipools := []api.MinipoolDetails{} for _, mp := range status.Minipools { if mp.Delegate != latestDelegateResponse.Address && !mp.UseLatestDelegate { @@ -52,11 +49,11 @@ func delegateUpgradeMinipools(c *cli.Context) error { // Get selected minipools var selectedMinipools []common.Address - if c.String("minipool") != "" && c.String("minipool") != "all" { - selectedAddress := common.HexToAddress(c.String("minipool")) + if minipool != "" && minipool != "all" { + selectedAddress := common.HexToAddress(minipool) selectedMinipools = []common.Address{selectedAddress} } else { - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(minipools)+1) options[0] = "All available minipools" @@ -103,13 +100,13 @@ func delegateUpgradeMinipools(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to upgrade %d minipools?", len(selectedMinipools))) { + if !(yes || prompt.Confirm("Are you sure you want to upgrade %d minipools?", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/dissolve.go b/rocketpool-cli/minipool/dissolve.go deleted file mode 100644 index bf0b9b97e..000000000 --- a/rocketpool-cli/minipool/dissolve.go +++ /dev/null @@ -1,155 +0,0 @@ -package minipool - -import ( - "bytes" - "fmt" - - "github.com/ethereum/go-ethereum/common" - rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" - "github.com/rocket-pool/smartnode/bindings/types" - "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" - - "github.com/rocket-pool/smartnode/shared/services/gas" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" - "github.com/rocket-pool/smartnode/shared/types/api" - cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" - "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/rocket-pool/smartnode/shared/utils/math" -) - -func dissolveMinipools(c *cli.Context) error { - - // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() - if err != nil { - return err - } - defer rp.Close() - - // Get minipool statuses - status, err := rp.MinipoolStatus() - if err != nil { - return err - } - - // Get initialized minipools - initializedMinipools := []api.MinipoolDetails{} - for _, minipool := range status.Minipools { - if minipool.Status.Status == types.Initialized { - initializedMinipools = append(initializedMinipools, minipool) - } - } - - // Check for initialized minipools - if len(initializedMinipools) == 0 { - fmt.Println("No minipools can be dissolved.") - return nil - } - - // Get selected minipools - var selectedMinipools []api.MinipoolDetails - if c.String("minipool") == "" { - - // Prompt for minipool selection - options := make([]string, len(initializedMinipools)+1) - options[0] = "All available minipools" - for mi, minipool := range initializedMinipools { - options[mi+1] = fmt.Sprintf("%s (%.6f ETH deposited)", minipool.Address.Hex(), math.RoundDown(eth.WeiToEth(minipool.Node.DepositBalance), 6)) - } - selected, _ := prompt.Select("Please select a minipool to dissolve:", options) - - // Get minipools - if selected == 0 { - selectedMinipools = initializedMinipools - } else { - selectedMinipools = []api.MinipoolDetails{initializedMinipools[selected-1]} - } - - } else { - - // Get matching minipools - if c.String("minipool") == "all" { - selectedMinipools = initializedMinipools - } else { - selectedAddress := common.HexToAddress(c.String("minipool")) - for _, minipool := range initializedMinipools { - if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { - selectedMinipools = []api.MinipoolDetails{minipool} - break - } - } - if selectedMinipools == nil { - return fmt.Errorf("The minipool %s is not available for dissolving.", selectedAddress.Hex()) - } - } - - } - - // Get the total gas limit estimate - var totalGas uint64 = 0 - var totalSafeGas uint64 = 0 - var gasInfo rocketpoolapi.GasInfo - for _, minipool := range selectedMinipools { - canResponse, err := rp.CanDissolveMinipool(minipool.Address) - if err != nil { - fmt.Printf("WARNING: Couldn't get gas price for dissolve transaction (%s)", err) - break - } else { - gasInfo = canResponse.GasInfo - totalGas += canResponse.GasInfo.EstGasLimit - totalSafeGas += canResponse.GasInfo.SafeGasLimit - } - } - gasInfo.EstGasLimit = totalGas - gasInfo.SafeGasLimit = totalSafeGas - - // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) - if err != nil { - return err - } - - // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to dissolve %d minipool(s)? This action cannot be undone!", len(selectedMinipools))) { - fmt.Println("Cancelled.") - return nil - } - - // Dissolve and close minipools - for _, minipool := range selectedMinipools { - g.Assign(rp) - response, err := rp.DissolveMinipool(minipool.Address) - if err != nil { - fmt.Printf("Could not dissolve minipool %s: %s.\n", minipool.Address.Hex(), err) - continue - } - - fmt.Printf("Dissolving minipool %s...\n", minipool.Address.Hex()) - cliutils.PrintTransactionHash(rp, response.TxHash) - if _, err = rp.WaitForTransaction(response.TxHash); err != nil { - fmt.Printf("Could not dissolve minipool %s: %s.\n", minipool.Address.Hex(), err) - continue - } else { - fmt.Printf("Successfully dissolved minipool %s.\n", minipool.Address.Hex()) - } - - closeResponse, err := rp.CloseMinipool(minipool.Address) - if err != nil { - fmt.Printf("Could not close minipool %s: %s.\n", minipool.Address.Hex(), err) - continue - } - - fmt.Printf("Closing minipool %s...\n", minipool.Address.Hex()) - cliutils.PrintTransactionHash(rp, closeResponse.TxHash) - if _, err = rp.WaitForTransaction(closeResponse.TxHash); err != nil { - fmt.Printf("Could not close minipool %s: %s.\n", minipool.Address.Hex(), err) - } else { - fmt.Printf("Successfully closed minipool %s.\n", minipool.Address.Hex()) - } - } - - // Return - return nil - -} diff --git a/rocketpool-cli/minipool/distribute.go b/rocketpool-cli/minipool/distribute.go index b42d29508..d0dd89088 100644 --- a/rocketpool-cli/minipool/distribute.go +++ b/rocketpool-cli/minipool/distribute.go @@ -10,7 +10,6 @@ import ( rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -25,10 +24,10 @@ const ( finalizationThreshold float64 = 8 ) -func distributeBalance(c *cli.Context) error { +func distributeBalance(minipool string, threshold float64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -99,7 +98,6 @@ func distributeBalance(c *cli.Context) error { } // Filter on the threshold if applicable - threshold := c.Float64("threshold") if threshold != 0 { filteredMps := []api.MinipoolBalanceDistributionDetails{} @@ -148,7 +146,7 @@ func distributeBalance(c *cli.Context) error { // Get selected minipools var selectedMinipools []api.MinipoolBalanceDistributionDetails - if c.String("minipool") == "" { + if minipool == "" { // Get total rewards totalEthAvailable := big.NewInt(0) @@ -188,10 +186,10 @@ func distributeBalance(c *cli.Context) error { } else { // Get matching minipools - if c.String("minipool") == "all" { + if minipool == "all" { selectedMinipools = eligibleMinipools } else { - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for _, minipool := range eligibleMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipools = []api.MinipoolBalanceDistributionDetails{minipool} @@ -218,13 +216,13 @@ func distributeBalance(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to distribute the ETH balance of %d minipools?", len(selectedMinipools))) { + if !(yes || prompt.Confirm("Are you sure you want to distribute the ETH balance of %d minipools?", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/exit.go b/rocketpool-cli/minipool/exit.go index 2fef45907..dbe51ed55 100644 --- a/rocketpool-cli/minipool/exit.go +++ b/rocketpool-cli/minipool/exit.go @@ -6,18 +6,18 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/types/api" + cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func exitMinipools(c *cli.Context) error { +func exitMinipools(minipool string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -45,16 +45,16 @@ func exitMinipools(c *cli.Context) error { // Get selected minipools var selectedMinipools []api.MinipoolDetails - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(activeMinipools)+1) options[0] = "All available minipools" for mi, minipool := range activeMinipools { if minipool.Status.Status == types.Staking { - options[mi+1] = fmt.Sprintf("%s (staking since %s)", minipool.Address.Hex(), minipool.Status.StatusTime.Format(TimeFormat)) + options[mi+1] = fmt.Sprintf("%s (staking since %s)", minipool.Address.Hex(), minipool.Status.StatusTime.Format(cliutils.TimeFormat)) } else { - options[mi+1] = fmt.Sprintf("%s (dissolved since %s)", minipool.Address.Hex(), minipool.Status.StatusTime.Format(TimeFormat)) + options[mi+1] = fmt.Sprintf("%s (dissolved since %s)", minipool.Address.Hex(), minipool.Status.StatusTime.Format(cliutils.TimeFormat)) } } selected, _ := prompt.Select("Please select a minipool to exit:", options) @@ -69,10 +69,10 @@ func exitMinipools(c *cli.Context) error { } else { // Get matching minipools - if c.String("minipool") == "all" { + if minipool == "all" { selectedMinipools = activeMinipools } else { - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for _, minipool := range activeMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipools = []api.MinipoolDetails{minipool} @@ -96,7 +96,7 @@ func exitMinipools(c *cli.Context) error { fmt.Println() // Prompt for confirmation - if !(c.Bool("yes") || prompt.ConfirmWithIAgree("Are you sure you want to exit %d minipool(s)? This action cannot be undone!", len(selectedMinipools))) { + if !(yes || prompt.ConfirmWithIAgree("Are you sure you want to exit %d minipool(s)? This action cannot be undone!", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/import-key.go b/rocketpool-cli/minipool/import-key.go index 136ee1b51..de7fa25a8 100644 --- a/rocketpool-cli/minipool/import-key.go +++ b/rocketpool-cli/minipool/import-key.go @@ -6,14 +6,14 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/rocketpool-cli/wallet" "github.com/rocket-pool/smartnode/shared/services/rocketpool" - "github.com/rocket-pool/smartnode/shared/utils/cli/migration" - "github.com/urfave/cli" + "github.com/rocket-pool/smartnode/shared/utils/cli/color" + "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func importKey(c *cli.Context, minipoolAddress common.Address) error { +func importKey(mnemonic string, noRestart, yes bool, minipoolAddress common.Address) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -22,16 +22,57 @@ func importKey(c *cli.Context, minipoolAddress common.Address) error { fmt.Printf("This will allow you to import the externally-created private key for the validator associated with minipool %s so it can be managed by the Smart Node's Validator Client instead of your externally-managed Validator Client.\n\n", minipoolAddress.Hex()) // Get the mnemonic - mnemonic := "" - if c.IsSet("mnemonic") { - mnemonic = c.String("mnemonic") - } else { + if mnemonic == "" { mnemonic = wallet.PromptMnemonic() } - success := migration.ImportKey(c, rp, minipoolAddress, mnemonic) - if !success { - fmt.Println("Importing the key failed.\nYou can try again later by using `rocketpool minipool import-key`.") + // Print a warning and prompt for confirmation of anti-slashing + color.RedPrintln("WARNING:") + color.RedPrintln("Before doing this, you **MUST** do the following:") + color.RedPrintln("1. Remove this key from your existing Validator Client used for solo staking") + color.RedPrintln("2. Restart it so that it is no longer validating with that key") + color.RedPrintln("3. Wait for 15 minutes so it has missed at least two attestations") + color.RedPrintln("Failure to do this **will result in your validator being SLASHED**.") + fmt.Println() + + if !prompt.Confirm("Have you removed the key from your own Validator Client, restarted it, and waited long enough for your validator to miss at least two attestations?") { + fmt.Println("Cancelled.") + return nil + } + + // Get the mnemonic + if mnemonic == "" { + mnemonic = wallet.PromptMnemonic() + } + + // Import the key + fmt.Printf("Importing validator key... ") + _, err = rp.ImportKey(minipoolAddress, mnemonic) + if err != nil { + fmt.Printf("error importing validator key: %s\n", err.Error()) + fmt.Println("Importing the key failed.") + fmt.Println("You can try again later by using `rocketpool minipool import-key`.") + return nil + } + fmt.Println("done!") + + if noRestart { + return nil + } + + if yes || prompt.Confirm("Would you like to restart the Smart Node's Validator Client now so it loads your validator's key?") { + // Restart the VC + fmt.Print("Restarting Validator Client... ") + _, err := rp.RestartVc() + if err != nil { + fmt.Println("failed!") + color.YellowPrintf("WARNING: error restarting validator client: %s\n", err.Error()) + fmt.Println() + color.YellowPrintln("Please restart it manually so it picks up the new validator key for your minipool.") + return nil + } + fmt.Println("done!") + fmt.Println() } return nil diff --git a/rocketpool-cli/minipool/promote.go b/rocketpool-cli/minipool/promote.go index 47743f9dd..4fe2eb3d2 100644 --- a/rocketpool-cli/minipool/promote.go +++ b/rocketpool-cli/minipool/promote.go @@ -6,7 +6,6 @@ import ( "github.com/ethereum/go-ethereum/common" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func promoteMinipools(c *cli.Context) error { +func promoteMinipools(minipool string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,7 +45,7 @@ func promoteMinipools(c *cli.Context) error { // Get selected minipools var selectedMinipools []api.MinipoolDetails - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(promotableMinipools)+1) @@ -66,10 +65,10 @@ func promoteMinipools(c *cli.Context) error { } else { // Get matching minipools - if c.String("minipool") == "all" { + if minipool == "all" { selectedMinipools = promotableMinipools } else { - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for _, minipool := range promotableMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipools = []api.MinipoolDetails{minipool} @@ -102,13 +101,13 @@ func promoteMinipools(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to promote %d minipools?", len(selectedMinipools))) { + if !(yes || prompt.Confirm("Are you sure you want to promote %d minipools?", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/refund.go b/rocketpool-cli/minipool/refund.go index 5090cd6ff..fd70c647d 100644 --- a/rocketpool-cli/minipool/refund.go +++ b/rocketpool-cli/minipool/refund.go @@ -7,7 +7,6 @@ import ( "github.com/ethereum/go-ethereum/common" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -17,10 +16,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func refundMinipools(c *cli.Context) error { +func refundMinipools(minipool string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -48,7 +47,7 @@ func refundMinipools(c *cli.Context) error { // Get selected minipools var selectedMinipools []api.MinipoolDetails - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(refundableMinipools)+1) @@ -68,10 +67,10 @@ func refundMinipools(c *cli.Context) error { } else { // Get matching minipools - if c.String("minipool") == "all" { + if minipool == "all" { selectedMinipools = refundableMinipools } else { - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for _, minipool := range refundableMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipools = []api.MinipoolDetails{minipool} @@ -104,13 +103,13 @@ func refundMinipools(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to refund %d minipools?", len(selectedMinipools))) { + if !(yes || prompt.Confirm("Are you sure you want to refund %d minipools?", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/rescue-dissolved.go b/rocketpool-cli/minipool/rescue-dissolved.go index ab516af16..9c7369cf0 100644 --- a/rocketpool-cli/minipool/rescue-dissolved.go +++ b/rocketpool-cli/minipool/rescue-dissolved.go @@ -9,7 +9,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/beacon" "github.com/rocket-pool/smartnode/shared/services/gas" @@ -21,10 +20,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func rescueDissolved(c *cli.Context) error { +func rescueDissolved(minipool string, amount string, noSend bool, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -42,10 +41,10 @@ func rescueDissolved(c *cli.Context) error { // Validate the amount var depositAmount *big.Int - if c.String("amount") != "" { - depositAmountEth, err := strconv.ParseFloat(c.String("amount"), 64) + if amount != "" { + depositAmountEth, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid deposit amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid deposit amount '%s': %w", amount, err) } if depositAmountEth < 1 { return fmt.Errorf("The minimum amount you can deposit to the Beacon deposit contract is 1 ETH.") @@ -128,7 +127,7 @@ func rescueDissolved(c *cli.Context) error { var selectedMinipool *api.MinipoolRescueDissolvedDetails var rescueAmount *big.Int var rescueAmountFloat float64 - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(rescuableMinipools)) @@ -152,7 +151,7 @@ func rescueDissolved(c *cli.Context) error { } else { // Get matching minipool - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for i, minipool := range rescuableMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipool = &rescuableMinipools[i] @@ -172,7 +171,7 @@ func rescueDissolved(c *cli.Context) error { // Get the amount to deposit var depositAmountFloat float64 - if c.String("amount") == "" { + if amount == "" { // Prompt for amount selection options := []string{ @@ -208,18 +207,18 @@ func rescueDissolved(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(selectedMinipool.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(selectedMinipool.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to deposit %.6f ETH to rescue minipool %s?", math.RoundDown(depositAmountFloat, 6), selectedMinipool.Address.Hex())) { + if !(yes || prompt.Confirm("Are you sure you want to deposit %.6f ETH to rescue minipool %s?", math.RoundDown(depositAmountFloat, 6), selectedMinipool.Address.Hex())) { fmt.Println("Cancelled.") return nil } - submit := !c.Bool("no-send") + submit := !noSend // Refund minipool response, err := rp.RescueDissolvedMinipool(selectedMinipool.Address, depositAmount, submit) diff --git a/rocketpool-cli/minipool/set-withdrawal-creds.go b/rocketpool-cli/minipool/set-withdrawal-creds.go index 664647326..ed07e3dab 100644 --- a/rocketpool-cli/minipool/set-withdrawal-creds.go +++ b/rocketpool-cli/minipool/set-withdrawal-creds.go @@ -6,14 +6,17 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/rocketpool-cli/wallet" "github.com/rocket-pool/smartnode/shared/services/rocketpool" - "github.com/rocket-pool/smartnode/shared/utils/cli/migration" - "github.com/urfave/cli" ) -func setWithdrawalCreds(c *cli.Context, minipoolAddress common.Address) error { +func printFailureMessage() { + fmt.Println("Your withdrawal credentials cannot be automatically changed at this time. Import aborted.") + fmt.Println("You can try again later by using `rocketpool minipool set-withdrawal-creds`.") +} + +func setWithdrawalCreds(mnemonic string, minipoolAddress common.Address) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -22,17 +25,31 @@ func setWithdrawalCreds(c *cli.Context, minipoolAddress common.Address) error { fmt.Printf("This will convert the withdrawal credentials for minipool %s's validator from the old 0x00 (BLS) value to the minipool address. This is meant for solo validator conversion **only**.\n\n", minipoolAddress.Hex()) // Get the mnemonic - mnemonic := "" - if c.IsSet("mnemonic") { - mnemonic = c.String("mnemonic") - } else { + if mnemonic == "" { mnemonic = wallet.PromptMnemonic() } - success := migration.ChangeWithdrawalCreds(rp, minipoolAddress, mnemonic) - if !success { - fmt.Println("Your withdrawal credentials cannot be automatically changed at this time. Import aborted.\nYou can try again later by using `rocketpool minipool set-withdrawal-creds`.") + // Check if the withdrawal creds can be changed + changeResponse, err := rp.CanChangeWithdrawalCredentials(minipoolAddress, mnemonic) + if err != nil { + fmt.Printf("Error checking if withdrawal creds can be migrated: %s\n", err.Error()) + printFailureMessage() + return nil + } + if !changeResponse.CanChange { + printFailureMessage() + return nil + } + + // Change the withdrawal creds + fmt.Print("Changing withdrawal credentials to the minipool address... ") + _, err = rp.ChangeWithdrawalCredentials(minipoolAddress, mnemonic) + if err != nil { + fmt.Printf("error changing withdrawal credentials: %s\n", err.Error()) + printFailureMessage() + return nil } + fmt.Println("done!") return nil } diff --git a/rocketpool-cli/minipool/stake.go b/rocketpool-cli/minipool/stake.go index fab83ac04..ba1631e8d 100644 --- a/rocketpool-cli/minipool/stake.go +++ b/rocketpool-cli/minipool/stake.go @@ -6,7 +6,6 @@ import ( "github.com/ethereum/go-ethereum/common" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func stakeMinipools(c *cli.Context) error { +func stakeMinipools(minipool string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,7 +45,7 @@ func stakeMinipools(c *cli.Context) error { // Get selected minipools var selectedMinipools []api.MinipoolDetails - if c.String("minipool") == "" { + if minipool == "" { // Prompt for minipool selection options := make([]string, len(stakeableMinipools)+1) @@ -66,10 +65,10 @@ func stakeMinipools(c *cli.Context) error { } else { // Get matching minipools - if c.String("minipool") == "all" { + if minipool == "all" { selectedMinipools = stakeableMinipools } else { - selectedAddress := common.HexToAddress(c.String("minipool")) + selectedAddress := common.HexToAddress(minipool) for _, minipool := range stakeableMinipools { if bytes.Equal(minipool.Address.Bytes(), selectedAddress.Bytes()) { selectedMinipools = []api.MinipoolDetails{minipool} @@ -102,7 +101,7 @@ func stakeMinipools(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } @@ -114,7 +113,7 @@ func stakeMinipools(c *cli.Context) error { fmt.Println() // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to stake %d minipools?", len(selectedMinipools))) { + if !(yes || prompt.Confirm("Are you sure you want to stake %d minipools?", len(selectedMinipools))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/minipool/status.go b/rocketpool-cli/minipool/status.go index f20523ac3..01b93f3bd 100644 --- a/rocketpool-cli/minipool/status.go +++ b/rocketpool-cli/minipool/status.go @@ -7,7 +7,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/types/api" @@ -17,10 +16,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func getStatus(c *cli.Context) error { +func getStatus(includeFinalized bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -71,7 +70,7 @@ func getStatus(c *cli.Context) error { } // Return if all minipools are finalized and they are hidden - if len(status.Minipools) == len(finalisedMinipools) && !c.Bool("include-finalized") { + if len(status.Minipools) == len(finalisedMinipools) && !includeFinalized { fmt.Println("All of this node's minipools have been finalized.\nTo show finalized minipools, re-run this command with the `-f` flag.") return nil } @@ -91,7 +90,7 @@ func getStatus(c *cli.Context) error { // Minipools for _, minipool := range minipools { - if !minipool.Finalised || c.Bool("include-finalized") { + if !minipool.Finalised || includeFinalized { printMinipoolDetails(minipool, status.LatestDelegate) } } @@ -100,7 +99,7 @@ func getStatus(c *cli.Context) error { } // Handle finalized minipools - if c.Bool("include-finalized") { + if includeFinalized { fmt.Printf("%d finalized minipool(s):\n", len(finalisedMinipools)) fmt.Println("") @@ -159,7 +158,7 @@ func printMinipoolDetails(minipool api.MinipoolDetails, latestDelegate common.Ad color.RedPrintf("Infractions: %d\n", minipool.Penalties) } fmt.Printf("Status: %s\n", minipool.Status.Status.String()) - fmt.Printf("Status updated: %s\n", minipool.Status.StatusTime.Format(TimeFormat)) + fmt.Printf("Status updated: %s\n", minipool.Status.StatusTime.Format(cliutils.TimeFormat)) fmt.Printf("Node fee: %f%%\n", minipool.Node.Fee*100) fmt.Printf("Node deposit: %.6f ETH\n", math.RoundDown(eth.WeiToEth(minipool.Node.DepositBalance), 6)) @@ -172,7 +171,7 @@ func printMinipoolDetails(minipool api.MinipoolDetails, latestDelegate common.Ad if minipool.Status.Status == types.Prelaunch || minipool.Status.Status == types.Staking { totalRewards := big.NewInt(0).Add(minipool.NodeShareOfETHBalance, minipool.Node.RefundBalance) if minipool.User.DepositAssigned { - fmt.Printf("RP ETH assigned: %s\n", minipool.User.DepositAssignedTime.Format(TimeFormat)) + fmt.Printf("RP ETH assigned: %s\n", minipool.User.DepositAssignedTime.Format(cliutils.TimeFormat)) fmt.Printf("RP deposit: %.6f ETH\n", math.RoundDown(eth.WeiToEth(minipool.User.DepositBalance), 6)) } else { fmt.Printf("RP ETH assigned: no\n") diff --git a/rocketpool-cli/minipool/utils.go b/rocketpool-cli/minipool/utils.go deleted file mode 100644 index ffa83e946..000000000 --- a/rocketpool-cli/minipool/utils.go +++ /dev/null @@ -1,4 +0,0 @@ -package minipool - -// Config -const TimeFormat = "2006-01-02, 15:04 -0700 MST" diff --git a/rocketpool-cli/minipool/vanity.go b/rocketpool-cli/minipool/vanity.go index 5c79e6170..924cabfae 100644 --- a/rocketpool-cli/minipool/vanity.go +++ b/rocketpool-cli/minipool/vanity.go @@ -12,24 +12,22 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func findVanitySalt(c *cli.Context) error { +func findVanitySalt(prefix string, saltFlag string, threads int, nodeAddressFlag string, amountFlag string) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() // Get the target prefix - prefix := c.String("prefix") if prefix == "" { prefix = prompt.Prompt("Please specify the address prefix you would like to search for (must start with 0x):", "^0x[0-9a-fA-F]+$", "Invalid hex string") } @@ -42,19 +40,17 @@ func findVanitySalt(c *cli.Context) error { } // Get the starting salt - saltString := c.String("salt") var salt *big.Int - if saltString == "" { + if saltFlag == "" { salt = big.NewInt(0) } else { - salt, success = big.NewInt(0).SetString(saltString, 0) + salt, success = big.NewInt(0).SetString(saltFlag, 0) if !success { return fmt.Errorf("Invalid starting salt: %s", salt) } } // Get the core count - threads := c.Int("threads") if threads == 0 { threads = runtime.GOMAXPROCS(0) } else if threads < 0 { @@ -64,16 +60,15 @@ func findVanitySalt(c *cli.Context) error { } // Get the node address - nodeAddressStr := c.String("node-address") - if nodeAddressStr == "" { - nodeAddressStr = "0" + if nodeAddressFlag == "" { + nodeAddressFlag = "0" } // Get deposit amount var amount float64 - if c.String("amount") != "" { + if amountFlag != "" { // Parse amount - if amount, err = cliutils.ValidatePositiveEthAmount("deposit", c.String("amount")); err != nil { + if amount, err = cliutils.ValidatePositiveEthAmount("deposit", amountFlag); err != nil { return err } } else { @@ -95,7 +90,7 @@ func findVanitySalt(c *cli.Context) error { amountWei := eth.EthToWei(amount) // Get the vanity generation artifacts - vanityArtifacts, err := rp.GetVanityArtifacts(amountWei, nodeAddressStr) + vanityArtifacts, err := rp.GetVanityArtifacts(amountWei, nodeAddressFlag) if err != nil { return err } diff --git a/rocketpool-cli/network/commands.go b/rocketpool-cli/network/commands.go index 24630bc74..13fc67f31 100644 --- a/rocketpool-cli/network/commands.go +++ b/rocketpool-cli/network/commands.go @@ -27,7 +27,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStats(c) + return getStats() }, }, @@ -45,7 +45,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getTimezones(c) + return getTimezones() }, }, @@ -63,7 +63,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getNodeFee(c) + return getNodeFee() }, }, @@ -81,7 +81,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getRplPrice(c) + return getRplPrice() }, }, @@ -112,9 +112,10 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } - // Run - return generateRewardsTree(c) - + if c.IsSet("index") { + return generateRewardsTree(c.Int64("index"), c.Bool("yes")) + } + return generateRewardsTree(-1, c.Bool("yes")) }, }, @@ -131,7 +132,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getActiveDAOProposals(c) + return getActiveDAOProposals() }, }, diff --git a/rocketpool-cli/network/dao-proposals.go b/rocketpool-cli/network/dao-proposals.go index bc335c817..4c3156cf7 100644 --- a/rocketpool-cli/network/dao-proposals.go +++ b/rocketpool-cli/network/dao-proposals.go @@ -11,12 +11,11 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" - "github.com/urfave/cli" ) -func getActiveDAOProposals(c *cli.Context) error { +func getActiveDAOProposals() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/network/generate-tree.go b/rocketpool-cli/network/generate-tree.go index 1a08ea33c..dc1dea585 100644 --- a/rocketpool-cli/network/generate-tree.go +++ b/rocketpool-cli/network/generate-tree.go @@ -7,17 +7,17 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) const ( signallingAddressLink string = "https://docs.rocketpool.net/pdao/participate#setting-your-snapshot-signalling-address" ) -func generateRewardsTree(c *cli.Context) error { +// indexFlag is -1 if not set, else the index to generate the tree for +func generateRewardsTree(indexFlag int64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,8 +46,8 @@ func generateRewardsTree(c *cli.Context) error { // Get the index var index uint64 - if c.IsSet("index") { - index = c.Uint64("index") + if indexFlag > -1 { + index = uint64(indexFlag) } else { indexString := prompt.Prompt("Which interval would you like to generate the Merkle rewards tree for?", "^\\d+$", "Invalid interval. Please provide a number.") index, err = strconv.ParseUint(indexString, 0, 64) @@ -67,7 +67,7 @@ func generateRewardsTree(c *cli.Context) error { // Confirm file overwrite if canResponse.TreeFileExists { - if c.Bool("yes") { + if yes { fmt.Println("Overwriting existing rewards file.") } else if !prompt.Confirm("You already have a rewards file for this interval. Would you like to overwrite it?") { fmt.Println("Cancelled.") @@ -84,7 +84,7 @@ func generateRewardsTree(c *cli.Context) error { fmt.Printf("Your request to generate the rewards tree for interval %d has been applied, and your `watchtower` container will begin the process during its next duty check (typically 5 minutes).\n", index) fmt.Println("You can follow its progress with", color.Green("`rocketpool service logs watchtower`.")) - if c.Bool("yes") || prompt.Confirm("Would you like to restart the watchtower container now, so it starts generating the file immediately?") { + if yes || prompt.Confirm("Would you like to restart the watchtower container now, so it starts generating the file immediately?") { container := fmt.Sprintf("%s_watchtower", cfg.Smartnode.ProjectName.Value.(string)) response, err := rp.RestartContainer(container) if err != nil { diff --git a/rocketpool-cli/network/node-fee.go b/rocketpool-cli/network/node-fee.go index 2ae767f2c..2de05a9d5 100644 --- a/rocketpool-cli/network/node-fee.go +++ b/rocketpool-cli/network/node-fee.go @@ -3,15 +3,13 @@ package network import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func getNodeFee(c *cli.Context) error { +func getNodeFee() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/network/rpl-price.go b/rocketpool-cli/network/rpl-price.go index c0ee8a94a..fce8932da 100644 --- a/rocketpool-cli/network/rpl-price.go +++ b/rocketpool-cli/network/rpl-price.go @@ -4,16 +4,15 @@ import ( "fmt" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/math" ) -func getRplPrice(c *cli.Context) error { +func getRplPrice() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/network/stats.go b/rocketpool-cli/network/stats.go index 1273beb4c..3bcac7b67 100644 --- a/rocketpool-cli/network/stats.go +++ b/rocketpool-cli/network/stats.go @@ -3,16 +3,14 @@ package network import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" ) -func getStats(c *cli.Context) error { +func getStats() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/network/timezones.go b/rocketpool-cli/network/timezones.go index 9e844efa7..48127dd10 100644 --- a/rocketpool-cli/network/timezones.go +++ b/rocketpool-cli/network/timezones.go @@ -4,15 +4,13 @@ import ( "fmt" "sort" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func getTimezones(c *cli.Context) error { +func getTimezones() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/node/allow-lock-rpl.go b/rocketpool-cli/node/allow-lock-rpl.go index 059dc12d5..af6200ec6 100644 --- a/rocketpool-cli/node/allow-lock-rpl.go +++ b/rocketpool-cli/node/allow-lock-rpl.go @@ -3,18 +3,16 @@ package node import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func setRPLLockingAllowed(c *cli.Context, allowedToLock bool) error { +func setRPLLockingAllowed(yes, allowedToLock bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -27,7 +25,7 @@ func setRPLLockingAllowed(c *cli.Context, allowedToLock bool) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } @@ -38,7 +36,7 @@ func setRPLLockingAllowed(c *cli.Context, allowedToLock bool) error { } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("%s", allowString)) { + if !(yes || prompt.Confirm("%s", allowString)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/claim-rewards.go b/rocketpool-cli/node/claim-rewards.go index 469311121..9f2654a6c 100644 --- a/rocketpool-cli/node/claim-rewards.go +++ b/rocketpool-cli/node/claim-rewards.go @@ -9,7 +9,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" rprewards "github.com/rocket-pool/smartnode/shared/services/rewards" @@ -20,10 +19,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func nodeClaimRewards(c *cli.Context) error { +func nodeClaimRewards(restakeAmountFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -140,7 +139,7 @@ func nodeClaimRewards(c *cli.Context) error { } for { indexSelection := "" - if !c.Bool("yes") { + if !yes { indexSelection = prompt.Prompt("Which intervals would you like to claim? Use a comma separated list (such as '1,2,3') or leave it blank to claim all intervals at once.", "^$|^\\d+(,\\d+)*$", "Invalid index selection") } @@ -198,7 +197,7 @@ func nodeClaimRewards(c *cli.Context) error { fmt.Printf("With this selection, you will claim %.6f RPL and %.6f ETH.\n\n", eth.WeiToEth(claimRpl), eth.WeiToEth(claimEth)) // Get restake amount - restakeAmountWei, err := getRestakeAmount(c, rewardsInfoResponse, claimRpl) + restakeAmountWei, err := getRestakeAmount(restakeAmountFlag, yes, rewardsInfoResponse, claimRpl) if err != nil { return err } @@ -211,7 +210,7 @@ func nodeClaimRewards(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canClaim.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canClaim.GasInfo, rp, yes) if err != nil { return err } @@ -222,14 +221,14 @@ func nodeClaimRewards(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canClaim.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canClaim.GasInfo, rp, yes) if err != nil { return err } } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to claim your rewards?")) { + if !(yes || prompt.Confirm("Are you sure you want to claim your rewards?")) { fmt.Println("Cancelled.") return nil } @@ -262,7 +261,7 @@ func nodeClaimRewards(c *cli.Context) error { } // Determine how much RPL to restake -func getRestakeAmount(c *cli.Context, rewardsInfoResponse api.NodeGetRewardsInfoResponse, claimRpl *big.Int) (*big.Int, error) { +func getRestakeAmount(restakeAmountFlag string, yes bool, rewardsInfoResponse api.NodeGetRewardsInfoResponse, claimRpl *big.Int) (*big.Int, error) { // Get the current collateral currentBondedCollateral := float64(0) @@ -293,7 +292,6 @@ func getRestakeAmount(c *cli.Context, rewardsInfoResponse api.NodeGetRewardsInfo // Handle restaking automation or prompts var restakeAmountWei *big.Int - restakeAmountFlag := c.String("restake-amount") if restakeAmountFlag == "all" { // Restake everything with no regard for collateral level @@ -313,7 +311,7 @@ func getRestakeAmount(c *cli.Context, rewardsInfoResponse api.NodeGetRewardsInfo fmt.Printf("Automatically restaking %.6f RPL, which will bring you to a total of %.6f RPL staked (%.2f%% borrowed collateral, %.2f%% bonded collateral).\n", stakeAmount, total, totalBorrowedCollateral*100, totalBondedCollateral*100) restakeAmountWei = eth.EthToWei(stakeAmount) } - } else if c.Bool("yes") { + } else if yes { // Ignore automatic restaking if `-y` is specified but `-a` isn't fmt.Println("Automatic restaking is not requested.") restakeAmountWei = nil diff --git a/rocketpool-cli/node/claim-unclaimed-rewards.go b/rocketpool-cli/node/claim-unclaimed-rewards.go index fe2fdb0f7..f746ea3a0 100644 --- a/rocketpool-cli/node/claim-unclaimed-rewards.go +++ b/rocketpool-cli/node/claim-unclaimed-rewards.go @@ -11,13 +11,12 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) -func claimUnclaimedRewards(c *cli.Context) error { +func claimUnclaimedRewards(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -50,13 +49,13 @@ func claimUnclaimedRewards(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canClaim.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canClaim.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to claim %.6f ETH in unclaimed rewards?", math.RoundDown(eth.WeiToEth(status.UnclaimedRewards), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to claim %.6f ETH in unclaimed rewards?", math.RoundDown(eth.WeiToEth(status.UnclaimedRewards), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/commands.go b/rocketpool-cli/node/commands.go index 4028ab161..76b73755d 100644 --- a/rocketpool-cli/node/commands.go +++ b/rocketpool-cli/node/commands.go @@ -31,7 +31,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -49,7 +49,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getSyncProgress(c) + return getSyncProgress() }, }, @@ -80,7 +80,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return registerNode(c) + return registerNode(c.String("timezone"), c.Bool("yes")) }, }, @@ -98,7 +98,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getRewards(c) + return getRewards(c.Bool("yes")) }, }, @@ -127,7 +127,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { withdrawalAddress := c.Args().Get(0) // Run - return setPrimaryWithdrawalAddress(c, withdrawalAddress) + return setPrimaryWithdrawalAddress(withdrawalAddress, c.Bool("yes"), c.Bool("force")) }, }, @@ -151,7 +151,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return confirmPrimaryWithdrawalAddress(c) + return confirmPrimaryWithdrawalAddress(c.Bool("yes")) }, }, @@ -180,7 +180,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { withdrawalAddress := c.Args().Get(0) // Run - return setRPLWithdrawalAddress(c, withdrawalAddress) + return setRPLWithdrawalAddress(withdrawalAddress, c.Bool("yes"), c.Bool("force")) }, }, @@ -204,7 +204,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return confirmRPLWithdrawalAddress(c) + return confirmRPLWithdrawalAddress(c.Bool("yes")) }, }, @@ -226,7 +226,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } // Run - return setRPLLockingAllowed(c, true) + return setRPLLockingAllowed(c.Bool("yes"), true) }, }, @@ -248,7 +248,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } // Run - return setRPLLockingAllowed(c, false) + return setRPLLockingAllowed(c.Bool("yes"), false) }, }, @@ -278,7 +278,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return setTimezoneLocation(c) + return setTimezoneLocation(c.String("timezone"), c.Bool("yes")) }, }, @@ -309,7 +309,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeSwapRpl(c) + return nodeSwapRpl(c.String("amount"), c.Bool("yes")) }, }, @@ -359,7 +359,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeStakeRpl(c) + return nodeStakeRpl(c.String("amount"), c.Bool("swap"), c.Bool("yes")) }, }, @@ -379,7 +379,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { addressOrENS := c.Args().Get(0) // Run - return addAddressToStakeRplWhitelist(c, addressOrENS) + return addAddressToStakeRplWhitelist(addressOrENS, c.Bool("yes")) }, }, @@ -399,7 +399,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { addressOrENS := c.Args().Get(0) // Run - return removeAddressFromStakeRplWhitelist(c, addressOrENS) + return removeAddressFromStakeRplWhitelist(addressOrENS, c.Bool("yes")) }, }, @@ -427,7 +427,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeClaimRewards(c) + return nodeClaimRewards(c.String("restake-amount"), c.Bool("yes")) }, }, @@ -462,7 +462,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeWithdrawRpl(c) + return nodeWithdrawRpl(c.String("amount"), c.Bool("yes")) }, }, @@ -496,7 +496,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeWithdrawEth(c) + return nodeWithdrawEth(c.String("amount"), c.Bool("yes")) }, }, @@ -531,7 +531,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeWithdrawCredit(c) + return nodeWithdrawCredit(c.String("amount"), c.Bool("yes")) }, }, @@ -571,7 +571,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return nodeSend(c, amount, sendAll, token, c.Args().Get(2)) + return nodeSend(amount, sendAll, token, c.Args().Get(2), c.Bool("yes")) }, }, @@ -595,7 +595,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return initializeFeeDistributor(c) + return initializeFeeDistributor(c.Bool("yes")) }, }, @@ -619,7 +619,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return distribute(c) + return distribute(c.Bool("yes")) }, }, @@ -643,7 +643,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return joinSmoothingPool(c) + return joinSmoothingPool(c.Bool("yes")) }, }, @@ -667,7 +667,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return leaveSmoothingPool(c) + return leaveSmoothingPool(c.Bool("yes")) }, }, @@ -685,7 +685,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { }, Action: func(c *cli.Context) error { // Run - return signMessage(c) + return signMessage(c.String("message")) }, }, @@ -711,7 +711,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return sendMessage(c, c.Args().Get(0), message) + return sendMessage(c.Args().Get(0), message, c.Bool("yes")) }, }, @@ -728,7 +728,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } // Run - return claimUnclaimedRewards(c) + return claimUnclaimedRewards(c.Bool("yes")) }, }, @@ -746,7 +746,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return provisionExpressTickets(c) + return provisionExpressTickets() }, Flags: []cli.Flag{ cli.BoolFlag{ diff --git a/rocketpool-cli/node/distributor.go b/rocketpool-cli/node/distributor.go index 57ba1d830..fc9ec2da5 100644 --- a/rocketpool-cli/node/distributor.go +++ b/rocketpool-cli/node/distributor.go @@ -3,8 +3,6 @@ package node import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/bindings/utils/eth" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -12,10 +10,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func initializeFeeDistributor(c *cli.Context) error { +func initializeFeeDistributor(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -31,7 +29,11 @@ func initializeFeeDistributor(c *cli.Context) error { return nil } - fmt.Println("This will create the \"fee distributor\" contract for your node, which captures priority fees and MEV after the merge for you.\n\nNOTE: you don't need to create the contract in order to be given those rewards - you only need it to *claim* those rewards to your withdrawal address.\nThe rewards can accumulate without initializing the contract.\nTherefore, we recommend you wait until the network's gas cost is low to initialize it.") + fmt.Println("This will create the \"fee distributor\" contract for your node, which captures priority fees and MEV after the merge for you.") + fmt.Println() + fmt.Println("NOTE: you don't need to create the contract in order to be given those rewards - you only need it to *claim* those rewards to your withdrawal address.") + fmt.Println("The rewards can accumulate without initializing the contract.") + fmt.Println("Therefore, we recommend you wait until the network's gas cost is low to initialize it.") // Get the gas estimate gasResponse, err := rp.GetInitializeFeeDistributorGas() @@ -40,7 +42,7 @@ func initializeFeeDistributor(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasResponse.GasInfo, rp, yes) if err != nil { return err } @@ -48,7 +50,7 @@ func initializeFeeDistributor(c *cli.Context) error { fmt.Printf("Your node's fee distributor contract will be created at address %s.\n", gasResponse.Distributor.Hex()) // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to initialize your fee distributor contract?")) { + if !(yes || prompt.Confirm("Are you sure you want to initialize your fee distributor contract?")) { fmt.Println("Cancelled.") return nil } @@ -71,10 +73,10 @@ func initializeFeeDistributor(c *cli.Context) error { } -func distribute(c *cli.Context) error { +func distribute(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -109,13 +111,13 @@ func distribute(c *cli.Context) error { fmt.Printf("\trETH pool stakers will receive %.6f ETH.\n\n", rEthShare) // Assign max fees - err = gas.AssignMaxFeeAndLimit(canDistributeResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canDistributeResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to distribute the ETH from your node's fee distributor?")) { + if !(yes || prompt.Confirm("Are you sure you want to distribute the ETH from your node's fee distributor?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/express-tickets.go b/rocketpool-cli/node/express-tickets.go index ab37980da..45100c4fb 100644 --- a/rocketpool-cli/node/express-tickets.go +++ b/rocketpool-cli/node/express-tickets.go @@ -5,13 +5,12 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" - "github.com/urfave/cli" ) -func provisionExpressTickets(c *cli.Context) error { +func provisionExpressTickets() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/node/primary-withdrawal-address.go b/rocketpool-cli/node/primary-withdrawal-address.go index 39ce420e4..abf51e83a 100644 --- a/rocketpool-cli/node/primary-withdrawal-address.go +++ b/rocketpool-cli/node/primary-withdrawal-address.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func setPrimaryWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) error { +func setPrimaryWithdrawalAddress(withdrawalAddressOrENS string, yes, force bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -44,7 +43,7 @@ func setPrimaryWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) // Print the "pending" disclaimer var confirm bool fmt.Println("You are about to change your primary withdrawal address. All future ETH rewards/refunds will be sent there.\nIf you haven't set your RPL withdrawal address, RPL rewards will be sent there as well.") - if !c.Bool("force") { + if !force { confirm = false fmt.Println("By default, this will put your new primary withdrawal address into a \"pending\" state.") fmt.Println("Rocket Pool will continue to use your old primary withdrawal address until you confirm that you own the new address via the Rocket Pool website.") @@ -78,7 +77,7 @@ func setPrimaryWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSendResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSendResponse.GasInfo, rp, yes) if err != nil { return err } @@ -104,13 +103,13 @@ func setPrimaryWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to set your node's primary withdrawal address to %s?", withdrawalAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to set your node's primary withdrawal address to %s?", withdrawalAddressString)) { fmt.Println("Cancelled.") return nil } @@ -128,7 +127,7 @@ func setPrimaryWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) } // Log & return - if !c.Bool("force") { + if !force { nodeManagerUrl := "" config, _, err := rp.LoadConfig() if err == nil { @@ -148,10 +147,10 @@ func setPrimaryWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) } -func confirmPrimaryWithdrawalAddress(c *cli.Context) error { +func confirmPrimaryWithdrawalAddress(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -164,13 +163,13 @@ func confirmPrimaryWithdrawalAddress(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to confirm your node's address as the new primary withdrawal address?")) { + if !(yes || prompt.Confirm("Are you sure you want to confirm your node's address as the new primary withdrawal address?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/register.go b/rocketpool-cli/node/register.go index 715369801..9ad94e46c 100644 --- a/rocketpool-cli/node/register.go +++ b/rocketpool-cli/node/register.go @@ -3,28 +3,23 @@ package node import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func registerNode(c *cli.Context) error { +func registerNode(timezoneLocation string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() // Prompt for timezone location - var timezoneLocation string - if c.String("timezone") != "" { - timezoneLocation = c.String("timezone") - } else { + if timezoneLocation == "" { timezoneLocation = promptTimezone() } @@ -45,13 +40,13 @@ func registerNode(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canRegister.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canRegister.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to register this node?")) { + if !(yes || prompt.Confirm("Are you sure you want to register this node?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/rewards.go b/rocketpool-cli/node/rewards.go index 83a3b0113..818e2aa10 100644 --- a/rocketpool-cli/node/rewards.go +++ b/rocketpool-cli/node/rewards.go @@ -5,8 +5,6 @@ import ( "math/big" "time" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/bindings/utils/eth" rprewards "github.com/rocket-pool/smartnode/shared/services/rewards" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +13,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func getRewards(c *cli.Context) error { +func getRewards(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -52,7 +50,7 @@ func getRewards(c *cli.Context) error { if len(missingIntervals) > 0 || len(invalidIntervals) > 0 { fmt.Println() color.LightBluePrintln("NOTE: If you would like to regenerate these tree files manually, please answer `n` to the prompt below and run `rocketpool network generate-rewards-tree` before claiming your rewards.") - if !prompt.Confirm("Would you like to download all missing rewards tree files now?") { + if !yes || !prompt.Confirm("Would you like to download all missing rewards tree files now?") { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/rpl-withdrawal-address.go b/rocketpool-cli/node/rpl-withdrawal-address.go index 542d71c88..45effcbac 100644 --- a/rocketpool-cli/node/rpl-withdrawal-address.go +++ b/rocketpool-cli/node/rpl-withdrawal-address.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/bindings/utils/eth" "github.com/rocket-pool/smartnode/shared/services/gas" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) error { +func setRPLWithdrawalAddress(withdrawalAddressOrENS string, yes, force bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -45,7 +44,7 @@ func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) erro // Print the "pending" disclaimer var confirm bool fmt.Println("You are about to change your RPL withdrawal address. All future RPL rewards/refunds will be sent there.") - if !c.Bool("force") { + if !force { confirm = false fmt.Println("By default, this will put your new RPL withdrawal address into a \"pending\" state.") fmt.Println("Rocket Pool will continue to use your old RPL withdrawal address (or your primary withdrawal address if your RPL withdrawal address has not been set) until you confirm that you own the new address via the Rocket Pool website.") @@ -90,7 +89,7 @@ func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) erro } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSendResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSendResponse.GasInfo, rp, yes) if err != nil { return err } @@ -116,7 +115,7 @@ func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) erro } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } @@ -125,7 +124,7 @@ func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) erro if canResponse.RPLStake.Cmp(common.Big0) == 1 { color.YellowPrintf("NOTE: You currently have %.6f RPL staked. Withdrawing it will *no longer* send it to your primary withdrawal address. It will be sent to the new RPL withdrawal address instead. Please verify you have control over that address before confirming this!\n", eth.WeiToEth(canResponse.RPLStake)) } - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to set your node's RPL withdrawal address to %s?", withdrawalAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to set your node's RPL withdrawal address to %s?", withdrawalAddressString)) { fmt.Println("Cancelled.") return nil } @@ -143,7 +142,7 @@ func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) erro } // Log & return - if !c.Bool("force") { + if !force { nodeManagerUrl := "" config, _, err := rp.LoadConfig() if err == nil { @@ -163,10 +162,10 @@ func setRPLWithdrawalAddress(c *cli.Context, withdrawalAddressOrENS string) erro } -func confirmRPLWithdrawalAddress(c *cli.Context) error { +func confirmRPLWithdrawalAddress(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -185,13 +184,13 @@ func confirmRPLWithdrawalAddress(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to confirm your node's address as the new RPL withdrawal address?")) { + if !(yes || prompt.Confirm("Are you sure you want to confirm your node's address as the new RPL withdrawal address?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/send-message.go b/rocketpool-cli/node/send-message.go index efe877a86..ffb84c2de 100644 --- a/rocketpool-cli/node/send-message.go +++ b/rocketpool-cli/node/send-message.go @@ -9,13 +9,12 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func sendMessage(c *cli.Context, toAddressOrENS string, message []byte) error { +func sendMessage(toAddressOrENS string, message []byte, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,13 +45,13 @@ func sendMessage(c *cli.Context, toAddressOrENS string, message []byte) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSend.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSend.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to send a message to %s?", toAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to send a message to %s?", toAddressString)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/send.go b/rocketpool-cli/node/send.go index eaab33cd1..db0aced36 100644 --- a/rocketpool-cli/node/send.go +++ b/rocketpool-cli/node/send.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -14,10 +13,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func nodeSend(c *cli.Context, amountRaw float64, sendAll bool, token string, toAddressOrENS string) error { +func nodeSend(amountRaw float64, sendAll bool, token string, toAddressOrENS string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -43,7 +42,7 @@ func nodeSend(c *cli.Context, amountRaw float64, sendAll bool, token string, toA // Handle "send all" mode if sendAll { - return nodeSendAll(c, rp, token, toAddress, toAddressString) + return nodeSendAll(rp, token, toAddress, toAddressString, yes) } // Check tokens can be sent @@ -74,20 +73,20 @@ func nodeSend(c *cli.Context, amountRaw float64, sendAll bool, token string, toA color.YellowPrintln("WARNING: Please confirm that the above token is the one you intend to send before confirming below!") fmt.Println() - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to send %.8f of %s to %s? This action cannot be undone!", amountRaw, tokenString, toAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to send %.8f of %s to %s? This action cannot be undone!", amountRaw, tokenString, toAddressString)) { fmt.Println("Cancelled.") return nil } } else { fmt.Printf("Node balance: %.8f %s\n\n", canSend.Balance, token) - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to send %.8f %s to %s? This action cannot be undone!", amountRaw, token, toAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to send %.8f %s to %s? This action cannot be undone!", amountRaw, token, toAddressString)) { fmt.Println("Cancelled.") return nil } } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSend.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSend.GasInfo, rp, yes) if err != nil { return err } @@ -120,7 +119,7 @@ func nodeSend(c *cli.Context, amountRaw float64, sendAll bool, token string, toA // nodeSendAll sends the entire balance of the specified token to the recipient. // For ETH, it reserves enough to cover the estimated maximum gas cost. -func nodeSendAll(c *cli.Context, rp *rocketpool.Client, token string, toAddress common.Address, toAddressString string) error { +func nodeSendAll(rp *rocketpool.Client, token string, toAddress common.Address, toAddressString string, yes bool) error { // Query balance and gas info using a zero amount canSend, err := rp.CanNodeSend(0, token, toAddress) @@ -145,7 +144,7 @@ func nodeSendAll(c *cli.Context, rp *rocketpool.Client, token string, toAddress fmt.Printf("For sending all ETH, we need to estimate the gas costs first.\n") // For ETH, determine gas settings first so we can subtract the gas cost from the balance. // This may prompt the user to select a gas price. - g, err := gas.GetMaxFeeAndLimit(canSend.GasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(canSend.GasInfo, rp, yes) if err != nil { return err } @@ -162,7 +161,7 @@ func nodeSendAll(c *cli.Context, rp *rocketpool.Client, token string, toAddress fmt.Printf("Gas reserve: %.8f ETH\n", gasCost) fmt.Printf("Send amount: %.8f ETH\n\n", amountRaw) - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to send %.8f ETH to %s? This action cannot be undone!", amountRaw, toAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to send %.8f ETH to %s? This action cannot be undone!", amountRaw, toAddressString)) { fmt.Println("Cancelled.") return nil } @@ -193,20 +192,20 @@ func nodeSendAll(c *cli.Context, rp *rocketpool.Client, token string, toAddress color.YellowPrintln("WARNING: Please confirm that the above token is the one you intend to send before confirming below!") fmt.Println() - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to send all %.8f of %s to %s? This action cannot be undone!", amountRaw, tokenString, toAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to send all %.8f of %s to %s? This action cannot be undone!", amountRaw, tokenString, toAddressString)) { fmt.Println("Cancelled.") return nil } } else { fmt.Printf("Node balance: %.8f %s\n\n", canSend.Balance, token) - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to send all %.8f %s to %s? This action cannot be undone!", amountRaw, token, toAddressString)) { + if !(yes || prompt.Confirm("Are you sure you want to send all %.8f %s to %s? This action cannot be undone!", amountRaw, token, toAddressString)) { fmt.Println("Cancelled.") return nil } } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSend.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSend.GasInfo, rp, yes) if err != nil { return err } diff --git a/rocketpool-cli/node/set-timezone.go b/rocketpool-cli/node/set-timezone.go index 19cd2ffaf..61806ace8 100644 --- a/rocketpool-cli/node/set-timezone.go +++ b/rocketpool-cli/node/set-timezone.go @@ -3,28 +3,23 @@ package node import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func setTimezoneLocation(c *cli.Context) error { +func setTimezoneLocation(timezoneLocation string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() // Prompt for timezone location - var timezoneLocation string - if c.String("timezone") != "" { - timezoneLocation = c.String("timezone") - } else { + if timezoneLocation == "" { timezoneLocation = promptTimezone() } @@ -35,13 +30,13 @@ func setTimezoneLocation(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to set your timezone?")) { + if !(yes || prompt.Confirm("Are you sure you want to set your timezone?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/sign-message.go b/rocketpool-cli/node/sign-message.go index ccaba9b18..c81025976 100644 --- a/rocketpool-cli/node/sign-message.go +++ b/rocketpool-cli/node/sign-message.go @@ -5,7 +5,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/goccy/go-json" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" @@ -20,10 +19,10 @@ type PersonalSignature struct { Version string `json:"version"` // beaconcha.in expects a string } -func signMessage(c *cli.Context) error { +func signMessage(message string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get & check wallet status @@ -37,7 +36,6 @@ func signMessage(c *cli.Context) error { return nil } - message := c.String("message") for message == "" { message = prompt.Prompt("Please enter the message you want to sign: (EIP-191 personal_sign)", "^.+$", "Please enter the message you want to sign: (EIP-191 personal_sign)") } diff --git a/rocketpool-cli/node/smoothing-pool.go b/rocketpool-cli/node/smoothing-pool.go index 358eeab63..c8cad11f5 100644 --- a/rocketpool-cli/node/smoothing-pool.go +++ b/rocketpool-cli/node/smoothing-pool.go @@ -3,8 +3,6 @@ package node import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" @@ -12,10 +10,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func joinSmoothingPool(c *cli.Context) error { +func joinSmoothingPool(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -52,7 +50,7 @@ func joinSmoothingPool(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } @@ -62,7 +60,7 @@ func joinSmoothingPool(c *cli.Context) error { fmt.Println() // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to join the Smoothing Pool?")) { + if !(yes || prompt.Confirm("Are you sure you want to join the Smoothing Pool?")) { fmt.Println("Cancelled.") return nil } @@ -85,10 +83,10 @@ func joinSmoothingPool(c *cli.Context) error { } -func leaveSmoothingPool(c *cli.Context) error { +func leaveSmoothingPool(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -125,13 +123,13 @@ func leaveSmoothingPool(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to leave the Smoothing Pool?")) { + if !(yes || prompt.Confirm("Are you sure you want to leave the Smoothing Pool?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/stake-rpl-whitelist.go b/rocketpool-cli/node/stake-rpl-whitelist.go index 5510d7ead..b15ac5aa0 100644 --- a/rocketpool-cli/node/stake-rpl-whitelist.go +++ b/rocketpool-cli/node/stake-rpl-whitelist.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -13,10 +12,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func addAddressToStakeRplWhitelist(c *cli.Context, addressOrENS string) error { +func addAddressToStakeRplWhitelist(addressOrENS string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,13 +45,13 @@ func addAddressToStakeRplWhitelist(c *cli.Context, addressOrENS string) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to allow %s to stake RPL for your node?", addressString)) { + if !(yes || prompt.Confirm("Are you sure you want to allow %s to stake RPL for your node?", addressString)) { fmt.Println("Cancelled.") return nil } @@ -74,10 +73,10 @@ func addAddressToStakeRplWhitelist(c *cli.Context, addressOrENS string) error { return nil } -func removeAddressFromStakeRplWhitelist(c *cli.Context, addressOrENS string) error { +func removeAddressFromStakeRplWhitelist(addressOrENS string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -107,13 +106,13 @@ func removeAddressFromStakeRplWhitelist(c *cli.Context, addressOrENS string) err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to remove %s from your RPL staking whitelist?", addressString)) { + if !(yes || prompt.Confirm("Are you sure you want to remove %s from your RPL staking whitelist?", addressString)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/stake-rpl.go b/rocketpool-cli/node/stake-rpl.go index c205e3198..7d62f1497 100644 --- a/rocketpool-cli/node/stake-rpl.go +++ b/rocketpool-cli/node/stake-rpl.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -21,10 +20,10 @@ const ( stakeRPLDisclaimer = "NOTE: By staking RPL, you become a member of the Rocket Pool pDAO. Stay informed on governance proposals by joining the Rocket Pool Discord." ) -func nodeStakeRpl(c *cli.Context) error { +func nodeStakeRpl(amount string, swap bool, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -47,7 +46,7 @@ func nodeStakeRpl(c *cli.Context) error { } // If a custom nonce is set, print the multi-transaction warning - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { cliutils.PrintMultiTransactionNonceWarning() } @@ -56,7 +55,7 @@ func nodeStakeRpl(c *cli.Context) error { if status.AccountBalances.FixedSupplyRPL.Cmp(big.NewInt(0)) > 0 { // Confirm swapping RPL - if c.Bool("swap") || prompt.Confirm("The node has a balance of %.6f old RPL. Would you like to swap it for new RPL before staking?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6)) { + if swap || prompt.Confirm("The node has a balance of %.6f old RPL. Would you like to swap it for new RPL before staking?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6)) { // Check allowance allowance, err := rp.GetNodeSwapRplAllowance() @@ -69,7 +68,7 @@ func nodeStakeRpl(c *cli.Context) error { fmt.Println("This only needs to be done once for your node.") // If a custom nonce is set, print the multi-transaction warning - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { cliutils.PrintMultiTransactionNonceWarning() } @@ -84,13 +83,13 @@ func nodeStakeRpl(c *cli.Context) error { return err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Do you want to let the new RPL contract interact with your legacy RPL?")) { + if !(yes || prompt.Confirm("Do you want to let the new RPL contract interact with your legacy RPL?")) { fmt.Println("Cancelled.") return nil } @@ -109,7 +108,7 @@ func nodeStakeRpl(c *cli.Context) error { fmt.Println("Successfully approved access to legacy RPL.") // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } } @@ -128,13 +127,13 @@ func nodeStakeRpl(c *cli.Context) error { } fmt.Println("RPL Swap Gas Info:") // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSwap.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSwap.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to swap %.6f old RPL for new RPL?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to swap %.6f old RPL for new RPL?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6))) { fmt.Println("Cancelled.") return nil } @@ -156,7 +155,7 @@ func nodeStakeRpl(c *cli.Context) error { fmt.Println("") // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } @@ -180,19 +179,19 @@ func nodeStakeRpl(c *cli.Context) error { ethBorrowed = new(big.Int).Sub(eth.EthToWei(32), status.ReducedBond) // Amount flag custom percentage input - if strings.HasSuffix(c.String("amount"), "%") { - fmt.Sscanf(c.String("amount"), "%f%%", &stakePercent) + if strings.HasSuffix(amount, "%") { + fmt.Sscanf(amount, "%f%%", &stakePercent) amountWei = rplStakePerValidator(ethBorrowed, eth.EthToWei(stakePercent/100), rplPrice.RplPrice) - } else if c.String("amount") == "all" { + } else if amount == "all" { // Set amount to node's entire RPL balance amountWei = &rplBalance - } else if c.String("amount") != "" { + } else if amount != "" { // Parse amount - stakeAmount, err := strconv.ParseFloat(c.String("amount"), 64) + stakeAmount, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid stake amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid stake amount '%s': %w", amount, err) } amountWei = eth.EthToWei(stakeAmount) @@ -252,7 +251,7 @@ func nodeStakeRpl(c *cli.Context) error { fmt.Println("This only needs to be done once for your node.") // If a custom nonce is set, print the multi-transaction warning - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { cliutils.PrintMultiTransactionNonceWarning() } @@ -267,13 +266,13 @@ func nodeStakeRpl(c *cli.Context) error { return err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Do you want to let the staking contract interact with your RPL?")) { + if !(yes || prompt.Confirm("Do you want to let the staking contract interact with your RPL?")) { fmt.Println("Cancelled.") return nil } @@ -292,7 +291,7 @@ func nodeStakeRpl(c *cli.Context) error { fmt.Println("Successfully approved staking access to RPL.") // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } } @@ -312,13 +311,13 @@ func nodeStakeRpl(c *cli.Context) error { fmt.Println("RPL Stake Gas Info:") // Assign max fees - err = gas.AssignMaxFeeAndLimit(canStake.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canStake.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to stake %.6f RPL? You may request to unstake your staked RPL at any time. The unstaked RPL will be withdrawable after an unstaking period of %s.", + if !(yes || prompt.Confirm("Are you sure you want to stake %.6f RPL? You may request to unstake your staked RPL at any time. The unstaked RPL will be withdrawable after an unstaking period of %s.", math.RoundDown(eth.WeiToEth(amountWei), 6), status.UnstakingPeriodDuration)) { fmt.Println("Cancelled.") diff --git a/rocketpool-cli/node/status.go b/rocketpool-cli/node/status.go index 06e83b23a..7e5300d59 100644 --- a/rocketpool-cli/node/status.go +++ b/rocketpool-cli/node/status.go @@ -10,7 +10,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/addons/rescue_node" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -24,10 +23,10 @@ const ( signallingAddressLink string = "https://docs.rocketpool.net/pdao/participate#setting-your-snapshot-signalling-address" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -336,7 +335,7 @@ func getStatus(c *cli.Context) error { // Check if unstaking period passed considering the last unstake time unstakingPeriodEnd = status.LastRPLUnstakeTime.Add(status.UnstakingPeriodDuration) if unstakingPeriodEnd.After(status.LatestBlockTime) { - fmt.Printf("Your node has %.6f RPL unstaking. That amount will be withdrawable on %s.\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6), unstakingPeriodEnd.Format(TimeFormat)) + fmt.Printf("Your node has %.6f RPL unstaking. That amount will be withdrawable on %s.\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6), unstakingPeriodEnd.Format(cliutils.TimeFormat)) } else { fmt.Printf("Your node has %.6f RPL unstaked. That amount is currently withdrawable.\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6)) } diff --git a/rocketpool-cli/node/swap-rpl.go b/rocketpool-cli/node/swap-rpl.go index 45e2ce795..395243836 100644 --- a/rocketpool-cli/node/swap-rpl.go +++ b/rocketpool-cli/node/swap-rpl.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func nodeSwapRpl(c *cli.Context) error { +func nodeSwapRpl(amount string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -26,7 +25,7 @@ func nodeSwapRpl(c *cli.Context) error { // Get swap amount var amountWei *big.Int - if c.String("amount") == "all" { + if amount == "all" { // Set amount to node's entire fixed-supply RPL balance status, err := rp.NodeStatus() @@ -35,12 +34,12 @@ func nodeSwapRpl(c *cli.Context) error { } amountWei = status.AccountBalances.FixedSupplyRPL - } else if c.String("amount") != "" { + } else if amount != "" { // Parse amount - swapAmount, err := strconv.ParseFloat(c.String("amount"), 64) + swapAmount, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid swap amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid swap amount '%s': %w", amount, err) } amountWei = eth.EthToWei(swapAmount) @@ -81,7 +80,7 @@ func nodeSwapRpl(c *cli.Context) error { fmt.Println("This only needs to be done once for your node.") // If a custom nonce is set, print the multi-transaction warning - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { cliutils.PrintMultiTransactionNonceWarning() } @@ -96,13 +95,13 @@ func nodeSwapRpl(c *cli.Context) error { return err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Do you want to let the new RPL contract interact with your legacy RPL?")) { + if !(yes || prompt.Confirm("Do you want to let the new RPL contract interact with your legacy RPL?")) { fmt.Println("Cancelled.") return nil } @@ -121,7 +120,7 @@ func nodeSwapRpl(c *cli.Context) error { fmt.Println("Successfully approved access to legacy RPL.") // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } } @@ -140,13 +139,13 @@ func nodeSwapRpl(c *cli.Context) error { } fmt.Println("RPL Swap Gas Info:") // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSwap.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSwap.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to swap %.6f old RPL for new RPL?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to swap %.6f old RPL for new RPL?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/sync.go b/rocketpool-cli/node/sync.go index 471ca0490..f6fca0b13 100644 --- a/rocketpool-cli/node/sync.go +++ b/rocketpool-cli/node/sync.go @@ -5,8 +5,6 @@ import ( "strings" "time" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/types/api" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" @@ -48,10 +46,10 @@ func printSyncProgress(status *api.ClientManagerStatus, name string) { printClientStatus(&status.FallbackClientStatus, fmt.Sprintf("fallback %s client", name)) } -func getSyncProgress(c *cli.Context) error { +func getSyncProgress() error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config diff --git a/rocketpool-cli/node/withdraw-credit.go b/rocketpool-cli/node/withdraw-credit.go index 2b035e647..298db58bf 100644 --- a/rocketpool-cli/node/withdraw-credit.go +++ b/rocketpool-cli/node/withdraw-credit.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func nodeWithdrawCredit(c *cli.Context) error { +func nodeWithdrawCredit(amount string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -37,17 +36,17 @@ func nodeWithdrawCredit(c *cli.Context) error { // Get withdrawal amount var amountWei *big.Int - if c.String("amount") == "max" { + if amount == "max" { // Set amount to maximum withdrawable amount amountWei = status.CreditBalance - } else if c.String("amount") != "" { + } else if amount != "" { // Parse amount - withdrawalAmount, err := strconv.ParseFloat(c.String("amount"), 64) + withdrawalAmount, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid withdrawal amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid withdrawal amount '%s': %w", amount, err) } amountWei = eth.EthToWei(withdrawalAmount) @@ -85,13 +84,13 @@ func nodeWithdrawCredit(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to withdraw %.6f of credit?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to withdraw %.6f of credit?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/withdraw-eth.go b/rocketpool-cli/node/withdraw-eth.go index d879b0744..7051d195c 100644 --- a/rocketpool-cli/node/withdraw-eth.go +++ b/rocketpool-cli/node/withdraw-eth.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func nodeWithdrawEth(c *cli.Context) error { +func nodeWithdrawEth(amount string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -26,7 +25,7 @@ func nodeWithdrawEth(c *cli.Context) error { // Get withdrawal amount var amountWei *big.Int - if c.String("amount") == "max" { + if amount == "max" { // Get node status status, err := rp.NodeStatus() @@ -37,12 +36,12 @@ func nodeWithdrawEth(c *cli.Context) error { // Set amount to maximum withdrawable amount amountWei = status.EthOnBehalfBalance - } else if c.String("amount") != "" { + } else if amount != "" { // Parse amount - withdrawalAmount, err := strconv.ParseFloat(c.String("amount"), 64) + withdrawalAmount, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid withdrawal amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid withdrawal amount '%s': %w", amount, err) } amountWei = eth.EthToWei(withdrawalAmount) @@ -89,13 +88,13 @@ func nodeWithdrawEth(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to withdraw %.6f ETH?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to withdraw %.6f ETH?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/node/withdraw-rpl.go b/rocketpool-cli/node/withdraw-rpl.go index 71e504d49..7d5164c65 100644 --- a/rocketpool-cli/node/withdraw-rpl.go +++ b/rocketpool-cli/node/withdraw-rpl.go @@ -8,7 +8,6 @@ import ( "time" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -18,12 +17,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -const TimeFormat = "2006-01-02, 15:04 -0700 MST" - -func nodeWithdrawRpl(c *cli.Context) error { +func nodeWithdrawRpl(amount string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -72,7 +69,7 @@ func nodeWithdrawRpl(c *cli.Context) error { // Print unstaking RPL details if !cooldownPassed && hasUnstakingRPL { - fmt.Printf("You have %.6f RPL currently unstaking until %s (%s from now).\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6), unstakingPeriodEnd.Format(TimeFormat), timeUntilUnstakingPeriodEnd.String()) + fmt.Printf("You have %.6f RPL currently unstaking until %s (%s from now).\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6), unstakingPeriodEnd.Format(cliutils.TimeFormat), timeUntilUnstakingPeriodEnd.String()) } else { fmt.Printf("You have %.6f RPL unstaked and ready to be withdrawn to your RPL withdrawal address.\n", eth.WeiToEth(status.UnstakingRPL)) } @@ -103,13 +100,13 @@ func nodeWithdrawRpl(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to withdraw %.6f staked RPL? This may decrease your node's RPL rewards.", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to withdraw %.6f staked RPL? This may decrease your node's RPL rewards.", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6))) { fmt.Println("Cancelled.") return nil } @@ -139,7 +136,7 @@ func nodeWithdrawRpl(c *cli.Context) error { } // Inform users that the unstaking period will reset if they make another unstaking request if !cooldownPassed && hasUnstakingRPL { - fmt.Printf("You have %.6f RPL currently unstaking until %s (%s from now).\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6), unstakingPeriodEnd.Format(TimeFormat), timeUntilUnstakingPeriodEnd.String()) + fmt.Printf("You have %.6f RPL currently unstaking until %s (%s from now).\n", math.RoundDown(eth.WeiToEth(status.UnstakingRPL), 6), unstakingPeriodEnd.Format(cliutils.TimeFormat), timeUntilUnstakingPeriodEnd.String()) color.YellowPrintln("Requesting to unstake additional RPL will reset the unstaking period.") color.YellowPrintf("The unstaking period is %s.\n", unstakingDurationString) @@ -206,13 +203,13 @@ func nodeWithdrawRpl(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to unstake %.6f RPL?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to unstake %.6f RPL?", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } @@ -302,13 +299,13 @@ func nodeWithdrawRpl(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canUnstakeLegacyRpl.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canUnstakeLegacyRpl.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to unstake %.6f legacy RPL? This may decrease your node's RPL rewards.", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to unstake %.6f legacy RPL? This may decrease your node's RPL rewards.", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } @@ -335,7 +332,7 @@ func nodeWithdrawRpl(c *cli.Context) error { // Get withdrawal mount var amountWei *big.Int - if c.String("amount") == "max" { + if amount == "max" { // Set amount to maximum withdrawable amount var maxAmount big.Int @@ -344,12 +341,12 @@ func nodeWithdrawRpl(c *cli.Context) error { } amountWei = &maxAmount - } else if c.String("amount") != "" { + } else if amount != "" { // Parse amount - withdrawalAmount, err := strconv.ParseFloat(c.String("amount"), 64) + withdrawalAmount, err := strconv.ParseFloat(amount, 64) if err != nil { - return fmt.Errorf("Invalid withdrawal amount '%s': %w", c.String("amount"), err) + return fmt.Errorf("Invalid withdrawal amount '%s': %w", amount, err) } amountWei = eth.EthToWei(withdrawalAmount) @@ -413,13 +410,13 @@ func nodeWithdrawRpl(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canWithdraw.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to withdraw %.6f staked RPL? This may decrease your node's RPL rewards.", math.RoundDown(eth.WeiToEth(amountWei), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to withdraw %.6f staked RPL? This may decrease your node's RPL rewards.", math.RoundDown(eth.WeiToEth(amountWei), 6))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/cancel-proposal.go b/rocketpool-cli/odao/cancel-proposal.go index 785cf3b37..15586a0b8 100644 --- a/rocketpool-cli/odao/cancel-proposal.go +++ b/rocketpool-cli/odao/cancel-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func cancelProposal(c *cli.Context) error { +func cancelProposal(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -52,12 +51,12 @@ func cancelProposal(c *cli.Context) error { // Get selected proposal var selectedProposal dao.ProposalDetails - if c.String("proposal") != "" { + if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -91,13 +90,13 @@ func cancelProposal(c *cli.Context) error { return err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to cancel proposal %d?", selectedProposal.ID)) { + if !(yes || prompt.Confirm("Are you sure you want to cancel proposal %d?", selectedProposal.ID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/commands.go b/rocketpool-cli/odao/commands.go index d349f9e59..8c822f9c6 100644 --- a/rocketpool-cli/odao/commands.go +++ b/rocketpool-cli/odao/commands.go @@ -27,7 +27,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -45,7 +45,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getMembers(c) + return getMembers() }, }, @@ -58,7 +58,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run - return getMemberSettings(c) + return getMemberSettings() }, }, @@ -71,7 +71,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run - return getProposalSettings(c) + return getProposalSettings() }, }, @@ -84,7 +84,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run - return getMinipoolSettings(c) + return getMinipoolSettings() }, }, @@ -118,7 +118,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return penaliseMegapool(c, megapoolAddress, block) + return penaliseMegapool(megapoolAddress, block, c.Bool("yes")) }, }, @@ -156,7 +156,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeInvite(c, memberAddress, memberId, c.Args().Get(2)) + return proposeInvite(memberAddress, memberId, c.Args().Get(2), c.Bool("yes")) }, }, @@ -174,7 +174,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeLeave(c) + return proposeLeave(c.Bool("yes")) }, }, @@ -214,7 +214,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeKick(c) + return proposeKick(c.String("member"), c.String("fine"), c.Bool("yes")) }, }, @@ -244,7 +244,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMembersQuorum(c, quorumPercent) + return proposeSettingMembersQuorum(quorumPercent, c.Bool("yes")) }, }, @@ -265,7 +265,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMembersRplBond(c, bondAmountEth) + return proposeSettingMembersRplBond(bondAmountEth, c.Bool("yes")) }, }, @@ -286,7 +286,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolUnbondedMax(c, unbondedMinipoolMax) + return proposeSettingMinipoolUnbondedMax(unbondedMinipoolMax, c.Bool("yes")) }, }, @@ -303,7 +303,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalCooldown(c, c.Args().Get(0)) + return proposeSettingProposalCooldown(c.Args().Get(0), c.Bool("yes")) }, }, @@ -320,7 +320,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalVoteTimespan(c, c.Args().Get(0)) + return proposeSettingProposalVoteTimespan(c.Args().Get(0), c.Bool("yes")) }, }, @@ -337,7 +337,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalVoteDelayTimespan(c, c.Args().Get(0)) + return proposeSettingProposalVoteDelayTimespan(c.Args().Get(0), c.Bool("yes")) }, }, @@ -354,7 +354,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalExecuteTimespan(c, c.Args().Get(0)) + return proposeSettingProposalExecuteTimespan(c.Args().Get(0), c.Bool("yes")) }, }, @@ -371,7 +371,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalActionTimespan(c, c.Args().Get(0)) + return proposeSettingProposalActionTimespan(c.Args().Get(0), c.Bool("yes")) }, }, @@ -388,7 +388,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingScrubPeriod(c, c.Args().Get(0)) + return proposeSettingScrubPeriod(c.Args().Get(0), c.Bool("yes")) }, }, @@ -405,7 +405,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingPromotionScrubPeriod(c, c.Args().Get(0)) + return proposeSettingPromotionScrubPeriod(c.Args().Get(0), c.Bool("yes")) }, }, @@ -426,7 +426,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingScrubPenaltyEnabled(c, enabled) + return proposeSettingScrubPenaltyEnabled(enabled, c.Bool("yes")) }, }, @@ -443,7 +443,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingBondReductionWindowStart(c, c.Args().Get(0)) + return proposeSettingBondReductionWindowStart(c.Args().Get(0), c.Bool("yes")) }, }, @@ -460,7 +460,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingBondReductionWindowLength(c, c.Args().Get(0)) + return proposeSettingBondReductionWindowLength(c.Args().Get(0), c.Bool("yes")) }, }, @@ -495,7 +495,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getProposals(c, c.String("states")) + return getProposals(c.String("states")) }, }, @@ -518,7 +518,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getProposal(c, id) + return getProposal(id) }, }, @@ -549,7 +549,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return cancelProposal(c) + return cancelProposal(c.String("proposal"), c.Bool("yes")) }, }, @@ -593,7 +593,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return voteOnProposal(c) + return voteOnProposal(c.String("proposal"), c.String("support"), c.Bool("yes")) }, }, @@ -624,7 +624,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return executeProposal(c) + return executeProposal(c.String("proposal"), c.Bool("yes")) }, }, @@ -654,7 +654,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return join(c) + return join(c.Bool("yes"), c.Bool("swap")) }, }, @@ -689,7 +689,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return leave(c) + return leave(c.String("refund-address"), c.Bool("yes")) }, }, @@ -705,7 +705,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Usage: "Get the upgrade proposals", UsageText: "rocketpool odao upgrade get-upgrade-proposals", Action: func(c *cli.Context) error { - return getUpgradeProposals(c) + return getUpgradeProposals() }, }, { @@ -714,7 +714,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Usage: "Execute an upgrade", UsageText: "rocketpool odao upgrade execute-upgrade upgrade-proposal-id", Action: func(c *cli.Context) error { - return executeUpgrade(c) + return executeUpgrade(c.String("proposal"), c.Bool("yes")) }, }, }, diff --git a/rocketpool-cli/odao/execute-proposal.go b/rocketpool-cli/odao/execute-proposal.go index 53fb68a3d..08c0fb184 100644 --- a/rocketpool-cli/odao/execute-proposal.go +++ b/rocketpool-cli/odao/execute-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func executeProposal(c *cli.Context) error { +func executeProposal(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,17 +45,17 @@ func executeProposal(c *cli.Context) error { // Get selected proposal var selectedProposals []dao.ProposalDetails - if c.String("proposal") == "all" { + if proposal == "all" { // Select all proposals selectedProposals = executableProposals - } else if c.String("proposal") != "" { + } else if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -110,13 +109,13 @@ func executeProposal(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { + if !(yes || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/execute-upgrade.go b/rocketpool-cli/odao/execute-upgrade.go index f8b4d7630..f5bcac531 100644 --- a/rocketpool-cli/odao/execute-upgrade.go +++ b/rocketpool-cli/odao/execute-upgrade.go @@ -9,7 +9,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao/upgrades" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -17,10 +16,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func getUpgradeProposals(c *cli.Context) error { +func getUpgradeProposals() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -54,10 +53,10 @@ func getUpgradeProposals(c *cli.Context) error { return nil } -func executeUpgrade(c *cli.Context) error { +func executeUpgrade(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -101,17 +100,17 @@ func executeUpgrade(c *cli.Context) error { // Get selected proposal var selectedProposals []upgrades.UpgradeProposalDetails - if c.String("proposal") == "all" { + if proposal == "all" { // Select all proposals selectedProposals = executableProposals - } else if c.String("proposal") != "" { + } else if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -165,13 +164,13 @@ func executeUpgrade(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Get max fees - g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + g, err := gas.GetMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { + if !(yes || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/get-settings.go b/rocketpool-cli/odao/get-settings.go index 0a90c1378..957211318 100644 --- a/rocketpool-cli/odao/get-settings.go +++ b/rocketpool-cli/odao/get-settings.go @@ -4,16 +4,14 @@ import ( "fmt" "time" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/bindings/utils/eth" "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func getMemberSettings(c *cli.Context) error { +func getMemberSettings() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -36,10 +34,10 @@ func getMemberSettings(c *cli.Context) error { } -func getProposalSettings(c *cli.Context) error { +func getProposalSettings() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -61,10 +59,10 @@ func getProposalSettings(c *cli.Context) error { } -func getMinipoolSettings(c *cli.Context) error { +func getMinipoolSettings() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/odao/join.go b/rocketpool-cli/odao/join.go index b239d799d..5ad56fa16 100644 --- a/rocketpool-cli/odao/join.go +++ b/rocketpool-cli/odao/join.go @@ -5,7 +5,6 @@ import ( "math/big" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -14,10 +13,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func join(c *cli.Context) error { +func join(yes bool, swap bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -30,7 +29,7 @@ func join(c *cli.Context) error { } // If a custom nonce is set, print the multi-transaction warning - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { cliutils.PrintMultiTransactionNonceWarning() } @@ -38,7 +37,7 @@ func join(c *cli.Context) error { if status.AccountBalances.FixedSupplyRPL.Cmp(big.NewInt(0)) > 0 { // Confirm swapping RPL - if c.Bool("swap") || prompt.Confirm("The node has a balance of %.6f old RPL. Would you like to swap it for new RPL before transferring your bond?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6)) { + if swap || prompt.Confirm("The node has a balance of %.6f old RPL. Would you like to swap it for new RPL before transferring your bond?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6)) { // Check allowance allowance, err := rp.GetNodeSwapRplAllowance() @@ -51,7 +50,7 @@ func join(c *cli.Context) error { fmt.Println("This only needs to be done once for your node.") // If a custom nonce is set, print the multi-transaction warning - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { cliutils.PrintMultiTransactionNonceWarning() } @@ -66,13 +65,13 @@ func join(c *cli.Context) error { return err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(approvalGas.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Do you want to let the new RPL contract interact with your legacy RPL?")) { + if !(yes || prompt.Confirm("Do you want to let the new RPL contract interact with your legacy RPL?")) { fmt.Println("Cancelled.") return nil } @@ -91,7 +90,7 @@ func join(c *cli.Context) error { fmt.Println("Successfully approved access to legacy RPL.") // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } } @@ -110,13 +109,13 @@ func join(c *cli.Context) error { } fmt.Println("RPL Swap Gas Info:") // Assign max fees - err = gas.AssignMaxFeeAndLimit(canSwap.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canSwap.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to swap %.6f old RPL for new RPL?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6))) { + if !(yes || prompt.Confirm("Are you sure you want to swap %.6f old RPL for new RPL?", math.RoundDown(eth.WeiToEth(status.AccountBalances.FixedSupplyRPL), 6))) { fmt.Println("Cancelled.") return nil } @@ -138,7 +137,7 @@ func join(c *cli.Context) error { fmt.Println("") // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } } @@ -165,14 +164,14 @@ func join(c *cli.Context) error { // Display gas estimate // Assign max fees - err = gas.AssignMaxFeeAndLimit(canJoin.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canJoin.GasInfo, rp, yes) if err != nil { return err } rp.PrintMultiTxWarning() // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to join the oracle DAO? Your RPL bond will be locked until you leave.")) { + if !(yes || prompt.Confirm("Are you sure you want to join the oracle DAO? Your RPL bond will be locked until you leave.")) { fmt.Println("Cancelled.") return nil } @@ -187,7 +186,7 @@ func join(c *cli.Context) error { cliutils.PrintTransactionHashNoCancel(rp, hash) // If a custom nonce is set, increment it for the next transaction - if c.GlobalUint64("nonce") != 0 { + if rocketpool.Defaults.CustomNonce != nil { rp.IncrementCustomNonce() } diff --git a/rocketpool-cli/odao/leave.go b/rocketpool-cli/odao/leave.go index 5a986424d..6d23c38ea 100644 --- a/rocketpool-cli/odao/leave.go +++ b/rocketpool-cli/odao/leave.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -12,10 +11,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func leave(c *cli.Context) error { +func leave(refundAddress string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -23,7 +22,7 @@ func leave(c *cli.Context) error { // Get the RPL bond refund address var bondRefundAddress common.Address - if c.String("refund-address") == "node" { + if refundAddress == "node" { // Set bond refund address to node address wallet, err := rp.WalletStatus() @@ -32,10 +31,10 @@ func leave(c *cli.Context) error { } bondRefundAddress = wallet.AccountAddress - } else if c.String("refund-address") != "" { + } else if refundAddress != "" { // Parse bond refund address - bondRefundAddress = common.HexToAddress(c.String("refund-address")) + bondRefundAddress = common.HexToAddress(refundAddress) } else { @@ -75,13 +74,13 @@ func leave(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canLeave.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canLeave.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to leave the oracle DAO and refund your RPL bond to %s? This action cannot be undone!", bondRefundAddress.Hex())) { + if !(yes || prompt.Confirm("Are you sure you want to leave the oracle DAO and refund your RPL bond to %s? This action cannot be undone!", bondRefundAddress.Hex())) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/members.go b/rocketpool-cli/odao/members.go index f0af1ef0a..05ace9635 100644 --- a/rocketpool-cli/odao/members.go +++ b/rocketpool-cli/odao/members.go @@ -4,17 +4,16 @@ import ( "fmt" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/math" ) -func getMembers(c *cli.Context) error { +func getMembers() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/odao/penalise-megapool.go b/rocketpool-cli/odao/penalise-megapool.go index 75b18f8c1..1d5b07e7d 100644 --- a/rocketpool-cli/odao/penalise-megapool.go +++ b/rocketpool-cli/odao/penalise-megapool.go @@ -12,12 +12,11 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/math" - "github.com/urfave/cli" ) -func penaliseMegapool(c *cli.Context, megapoolAddress common.Address, block *big.Int) error { +func penaliseMegapool(megapoolAddress common.Address, block *big.Int, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -43,13 +42,13 @@ func penaliseMegapool(c *cli.Context, megapoolAddress common.Address, block *big } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPenalise.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPenalise.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to penalise %.6f megapool %s at block %s?", math.RoundDown(eth.WeiToEth(amountWei), 6), megapoolAddress, block)) { + if !(yes || prompt.Confirm("Are you sure you want to penalise %.6f megapool %s at block %s?", math.RoundDown(eth.WeiToEth(amountWei), 6), megapoolAddress, block)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/proposals.go b/rocketpool-cli/odao/proposals.go index e4c65e008..e61651c03 100644 --- a/rocketpool-cli/odao/proposals.go +++ b/rocketpool-cli/odao/proposals.go @@ -9,7 +9,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" @@ -26,10 +25,10 @@ func filterProposalState(state string, stateFilter string) bool { return !slices.Contains(filterStates, state) } -func getProposals(c *cli.Context, stateFilter string) error { +func getProposals(stateFilter string) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -103,9 +102,9 @@ func getProposals(c *cli.Context, stateFilter string) error { } -func getProposal(c *cli.Context, id uint64) error { +func getProposal(id uint64) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/odao/propose-invite.go b/rocketpool-cli/odao/propose-invite.go index 3b3856c47..eac4768b4 100644 --- a/rocketpool-cli/odao/propose-invite.go +++ b/rocketpool-cli/odao/propose-invite.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -12,10 +11,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func proposeInvite(c *cli.Context, memberAddress common.Address, memberId, memberUrl string) error { +func proposeInvite(memberAddress common.Address, memberId, memberUrl string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -38,13 +37,13 @@ func proposeInvite(c *cli.Context, memberAddress common.Address, memberId, membe } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/propose-kick.go b/rocketpool-cli/odao/propose-kick.go index 66f172d87..47af0f999 100644 --- a/rocketpool-cli/odao/propose-kick.go +++ b/rocketpool-cli/odao/propose-kick.go @@ -9,7 +9,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/dao/trustednode" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -18,10 +17,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/math" ) -func proposeKick(c *cli.Context) error { +func proposeKick(member, fine string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -35,10 +34,10 @@ func proposeKick(c *cli.Context) error { // Get member to propose kicking var selectedMember trustednode.MemberDetails - if c.String("member") != "" { + if member != "" { // Get matching member - selectedAddress := common.HexToAddress(c.String("member")) + selectedAddress := common.HexToAddress(member) for _, member := range members.Members { if bytes.Equal(member.Address.Bytes(), selectedAddress.Bytes()) { selectedMember = member @@ -63,17 +62,17 @@ func proposeKick(c *cli.Context) error { // Get fine amount var fineAmountWei *big.Int - if c.String("fine") == "max" { + if fine == "max" { // Set fine amount to member's entire RPL bond fineAmountWei = selectedMember.RPLBondAmount - } else if c.String("fine") != "" { + } else if fine != "" { // Parse amount - fineAmount, err := strconv.ParseFloat(c.String("fine"), 64) + fineAmount, err := strconv.ParseFloat(fine, 64) if err != nil { - return fmt.Errorf("Invalid fine amount '%s': %w", c.String("fine"), err) + return fmt.Errorf("Invalid fine amount '%s': %w", fine, err) } fineAmountWei = eth.EthToWei(fineAmount) @@ -106,13 +105,13 @@ func proposeKick(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/propose-leave.go b/rocketpool-cli/odao/propose-leave.go index af5d43b10..5fcad2862 100644 --- a/rocketpool-cli/odao/propose-leave.go +++ b/rocketpool-cli/odao/propose-leave.go @@ -3,18 +3,16 @@ package odao import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func proposeLeave(c *cli.Context) error { +func proposeLeave(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -36,13 +34,13 @@ func proposeLeave(c *cli.Context) error { return nil } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/propose-settings.go b/rocketpool-cli/odao/propose-settings.go index 9a96d9210..9160eb936 100644 --- a/rocketpool-cli/odao/propose-settings.go +++ b/rocketpool-cli/odao/propose-settings.go @@ -5,7 +5,6 @@ import ( "time" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -13,10 +12,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func proposeSettingMembersQuorum(c *cli.Context, quorumPercent float64) error { +func proposeSettingMembersQuorum(quorumPercent float64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -36,13 +35,13 @@ func proposeSettingMembersQuorum(c *cli.Context, quorumPercent float64) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -65,10 +64,10 @@ func proposeSettingMembersQuorum(c *cli.Context, quorumPercent float64) error { } -func proposeSettingMembersRplBond(c *cli.Context, bondAmountEth float64) error { +func proposeSettingMembersRplBond(bondAmountEth float64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -88,13 +87,13 @@ func proposeSettingMembersRplBond(c *cli.Context, bondAmountEth float64) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -117,10 +116,10 @@ func proposeSettingMembersRplBond(c *cli.Context, bondAmountEth float64) error { } -func proposeSettingMinipoolUnbondedMax(c *cli.Context, unbondedMinipoolMax uint64) error { +func proposeSettingMinipoolUnbondedMax(unbondedMinipoolMax uint64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -140,13 +139,13 @@ func proposeSettingMinipoolUnbondedMax(c *cli.Context, unbondedMinipoolMax uint6 } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -169,10 +168,10 @@ func proposeSettingMinipoolUnbondedMax(c *cli.Context, unbondedMinipoolMax uint6 } -func proposeSettingProposalCooldown(c *cli.Context, proposalCooldownTimespan string) error { +func proposeSettingProposalCooldown(proposalCooldownTimespan string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -199,13 +198,13 @@ func proposeSettingProposalCooldown(c *cli.Context, proposalCooldownTimespan str } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -228,10 +227,10 @@ func proposeSettingProposalCooldown(c *cli.Context, proposalCooldownTimespan str } -func proposeSettingProposalVoteTimespan(c *cli.Context, proposalVoteTimespan string) error { +func proposeSettingProposalVoteTimespan(proposalVoteTimespan string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -258,13 +257,13 @@ func proposeSettingProposalVoteTimespan(c *cli.Context, proposalVoteTimespan str } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -287,10 +286,10 @@ func proposeSettingProposalVoteTimespan(c *cli.Context, proposalVoteTimespan str } -func proposeSettingProposalVoteDelayTimespan(c *cli.Context, proposalDelayTimespan string) error { +func proposeSettingProposalVoteDelayTimespan(proposalDelayTimespan string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -317,13 +316,13 @@ func proposeSettingProposalVoteDelayTimespan(c *cli.Context, proposalDelayTimesp } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -346,10 +345,10 @@ func proposeSettingProposalVoteDelayTimespan(c *cli.Context, proposalDelayTimesp } -func proposeSettingProposalExecuteTimespan(c *cli.Context, proposalExecuteTimespan string) error { +func proposeSettingProposalExecuteTimespan(proposalExecuteTimespan string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -376,13 +375,13 @@ func proposeSettingProposalExecuteTimespan(c *cli.Context, proposalExecuteTimesp } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -405,10 +404,10 @@ func proposeSettingProposalExecuteTimespan(c *cli.Context, proposalExecuteTimesp } -func proposeSettingProposalActionTimespan(c *cli.Context, proposalActionTimespan string) error { +func proposeSettingProposalActionTimespan(proposalActionTimespan string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -435,13 +434,13 @@ func proposeSettingProposalActionTimespan(c *cli.Context, proposalActionTimespan } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -464,10 +463,10 @@ func proposeSettingProposalActionTimespan(c *cli.Context, proposalActionTimespan } -func proposeSettingScrubPeriod(c *cli.Context, scrubPeriod string) error { +func proposeSettingScrubPeriod(scrubPeriod string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -494,13 +493,13 @@ func proposeSettingScrubPeriod(c *cli.Context, scrubPeriod string) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -523,10 +522,10 @@ func proposeSettingScrubPeriod(c *cli.Context, scrubPeriod string) error { } -func proposeSettingPromotionScrubPeriod(c *cli.Context, scrubPeriod string) error { +func proposeSettingPromotionScrubPeriod(scrubPeriod string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -553,13 +552,13 @@ func proposeSettingPromotionScrubPeriod(c *cli.Context, scrubPeriod string) erro } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -582,10 +581,10 @@ func proposeSettingPromotionScrubPeriod(c *cli.Context, scrubPeriod string) erro } -func proposeSettingScrubPenaltyEnabled(c *cli.Context, enabled bool) error { +func proposeSettingScrubPenaltyEnabled(enabled bool, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -605,13 +604,13 @@ func proposeSettingScrubPenaltyEnabled(c *cli.Context, enabled bool) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -634,10 +633,10 @@ func proposeSettingScrubPenaltyEnabled(c *cli.Context, enabled bool) error { } -func proposeSettingBondReductionWindowStart(c *cli.Context, windowStart string) error { +func proposeSettingBondReductionWindowStart(windowStart string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -664,13 +663,13 @@ func proposeSettingBondReductionWindowStart(c *cli.Context, windowStart string) } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } @@ -693,10 +692,10 @@ func proposeSettingBondReductionWindowStart(c *cli.Context, windowStart string) } -func proposeSettingBondReductionWindowLength(c *cli.Context, windowLength string) error { +func proposeSettingBondReductionWindowLength(windowLength string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -723,13 +722,13 @@ func proposeSettingBondReductionWindowLength(c *cli.Context, windowLength string } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/odao/status.go b/rocketpool-cli/odao/status.go index 38c816f0d..af19c0138 100644 --- a/rocketpool-cli/odao/status.go +++ b/rocketpool-cli/odao/status.go @@ -3,15 +3,13 @@ package odao import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/odao/vote-proposal.go b/rocketpool-cli/odao/vote-proposal.go index acfe2543e..38c433e0b 100644 --- a/rocketpool-cli/odao/vote-proposal.go +++ b/rocketpool-cli/odao/vote-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func voteOnProposal(c *cli.Context) error { +func voteOnProposal(proposal string, supportFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -52,12 +51,12 @@ func voteOnProposal(c *cli.Context) error { // Get selected proposal var selectedProposal dao.ProposalDetails - if c.String("proposal") != "" { + if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -104,11 +103,11 @@ func voteOnProposal(c *cli.Context) error { // Get support status var support bool var supportLabel string - if c.String("support") != "" { + if supportFlag != "" { // Parse support status var err error - support, err = cliutils.ValidateBool("support", c.String("support")) + support, err = cliutils.ValidateBool("support", supportFlag) if err != nil { return err } @@ -139,13 +138,13 @@ func voteOnProposal(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canVote.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canVote.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to vote %s proposal %d? Your vote cannot be changed later.", supportLabel, selectedProposal.ID)) { + if !(yes || prompt.Confirm("Are you sure you want to vote %s proposal %d? Your vote cannot be changed later.", supportLabel, selectedProposal.ID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/claim-bonds.go b/rocketpool-cli/pdao/claim-bonds.go index bfed61c56..fa6debc9e 100644 --- a/rocketpool-cli/pdao/claim-bonds.go +++ b/rocketpool-cli/pdao/claim-bonds.go @@ -7,7 +7,6 @@ import ( rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func claimBonds(c *cli.Context) error { +func claimBonds(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -40,17 +39,17 @@ func claimBonds(c *cli.Context) error { // Get selected proposal var selectedClaims []api.BondClaimResult - if c.String("proposal") == "all" { + if proposal == "all" { // Select all proposals selectedClaims = claimableBonds - } else if c.String("proposal") != "" { + } else if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -104,13 +103,13 @@ func claimBonds(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to claim bonds and rewards from %d proposals?", len(selectedClaims))) { + if !(yes || prompt.Confirm("Are you sure you want to claim bonds and rewards from %d proposals?", len(selectedClaims))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/commands.go b/rocketpool-cli/pdao/commands.go index af39f07ae..4e42641d5 100644 --- a/rocketpool-cli/pdao/commands.go +++ b/rocketpool-cli/pdao/commands.go @@ -39,7 +39,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run - return getStatus(c) + return getStatus() }, }, @@ -52,7 +52,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run - return getSettings(c) + return getSettings() }, }, @@ -65,7 +65,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run - return getRewardsPercentages(c) + return getRewardsPercentages() }, }, @@ -96,7 +96,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return setSignallingAddress(c, snapshotAddress, signature) + return setSignallingAddress(snapshotAddress, signature, c.Bool("yes")) }, }, @@ -120,7 +120,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return clearSignallingAddress(c) + return clearSignallingAddress(c.Bool("yes")) }, }, @@ -144,7 +144,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } delegate := c.Args().Get(0) // Run - return pdaoSetVotingDelegate(c, delegate) + return pdaoSetVotingDelegate(delegate, c.Bool("yes")) }, }, @@ -172,7 +172,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return claimBonds(c) + return claimBonds(c.String("proposal"), c.Bool("yes")) }, }, @@ -218,7 +218,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeRewardsPercentages(c) + return proposeRewardsPercentages(c.Bool("raw"), c.String("node"), c.String("odao"), c.String("pdao"), c.Bool("yes")) }, }, @@ -262,7 +262,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeOneTimeSpend(c) + return proposeOneTimeSpend(c.String("invoice-id"), c.String("recipient"), c.String("amount"), c.String("custom-message"), c.Bool("raw"), c.Bool("yes")) }, }, @@ -318,7 +318,15 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeRecurringSpend(c) + return proposeRecurringSpend( + c.Bool("raw"), + c.String("contract-name"), + c.String("recipient"), + c.String("amount-per-period"), + c.Uint64("start-time"), + c.String("period-length"), + c.Uint64("number-of-periods"), + c.String("custom-message"), c.Bool("yes")) }, }, @@ -370,8 +378,16 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeRecurringSpendUpdate(c) - + return proposeRecurringSpendUpdate( + c.Bool("raw"), + c.String("contract-name"), + c.String("recipient"), + c.String("amount-per-period"), + c.String("period-length"), + c.Uint64("number-of-periods"), + c.String("custom-message"), + c.Bool("yes"), + ) }, }, @@ -408,7 +424,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSecurityCouncilInvite(c) + return proposeSecurityCouncilInvite(c.String("id"), c.String("address"), c.Bool("yes")) }, }, @@ -436,7 +452,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSecurityCouncilKick(c) + return proposeSecurityCouncilKick(c.String("addresses"), c.Bool("yes")) }, }, @@ -472,7 +488,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSecurityCouncilReplace(c) + return proposeSecurityCouncilReplace(c.String("existing-address"), c.String("new-id"), c.String("new-address"), c.Bool("yes")) }, }, @@ -514,7 +530,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingAuctionIsCreateLotEnabled(c, value) + return proposeSettingAuctionIsCreateLotEnabled(value, c.Bool("yes")) }, }, @@ -542,7 +558,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingAuctionIsBidOnLotEnabled(c, value) + return proposeSettingAuctionIsBidOnLotEnabled(value, c.Bool("yes")) }, }, @@ -568,13 +584,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingAuctionLotMinimumEthValue(c, value) + return proposeSettingAuctionLotMinimumEthValue(value, c.Bool("yes")) }, }, @@ -600,13 +616,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingAuctionLotMaximumEthValue(c, value) + return proposeSettingAuctionLotMaximumEthValue(value, c.Bool("yes")) }, }, @@ -634,7 +650,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingAuctionLotDuration(c, value) + return proposeSettingAuctionLotDuration(value, c.Bool("yes")) }, }, @@ -660,13 +676,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingAuctionLotStartingPriceRatio(c, value) + return proposeSettingAuctionLotStartingPriceRatio(value, c.Bool("yes")) }, }, @@ -692,13 +708,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingAuctionLotReservePriceRatio(c, value) + return proposeSettingAuctionLotReservePriceRatio(value, c.Bool("yes")) }, }, @@ -734,7 +750,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositIsDepositingEnabled(c, value) + return proposeSettingDepositIsDepositingEnabled(value, c.Bool("yes")) }, }, @@ -762,7 +778,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositAreDepositAssignmentsEnabled(c, value) + return proposeSettingDepositAreDepositAssignmentsEnabled(value, c.Bool("yes")) }, }, @@ -788,13 +804,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingDepositMinimumDeposit(c, value) + return proposeSettingDepositMinimumDeposit(value, c.Bool("yes")) }, }, @@ -820,13 +836,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingDepositMaximumDepositPoolSize(c, value) + return proposeSettingDepositMaximumDepositPoolSize(value, c.Bool("yes")) }, }, @@ -854,7 +870,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositMaximumAssignmentsPerDeposit(c, value) + return proposeSettingDepositMaximumAssignmentsPerDeposit(value, c.Bool("yes")) }, }, @@ -882,7 +898,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositMaximumSocialisedAssignmentsPerDeposit(c, value) + return proposeSettingDepositMaximumSocialisedAssignmentsPerDeposit(value, c.Bool("yes")) }, }, @@ -908,13 +924,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingDepositDepositFee(c, value) + return proposeSettingDepositDepositFee(value, c.Bool("yes")) }, }, @@ -941,7 +957,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositExpressQueueRate(c, value) + return proposeSettingDepositExpressQueueRate(value, c.Bool("yes")) }, }, @@ -968,7 +984,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositExpressQueueTicketsBaseProvision(c, value) + return proposeSettingDepositExpressQueueTicketsBaseProvision(value, c.Bool("yes")) }, }, @@ -1004,7 +1020,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolIsSubmitWithdrawableEnabled(c, value) + return proposeSettingMinipoolIsSubmitWithdrawableEnabled(value, c.Bool("yes")) }, }, @@ -1032,7 +1048,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolLaunchTimeout(c, value) + return proposeSettingMinipoolLaunchTimeout(value, c.Bool("yes")) }, }, @@ -1060,7 +1076,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolIsBondReductionEnabled(c, value) + return proposeSettingMinipoolIsBondReductionEnabled(value, c.Bool("yes")) }, }, @@ -1088,7 +1104,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolMaximumCount(c, value) + return proposeSettingMinipoolMaximumCount(value, c.Bool("yes")) }, }, @@ -1116,7 +1132,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolUserDistributeWindowStart(c, value) + return proposeSettingMinipoolUserDistributeWindowStart(value, c.Bool("yes")) }, }, @@ -1144,7 +1160,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolUserDistributeWindowLength(c, value) + return proposeSettingMinipoolUserDistributeWindowLength(value, c.Bool("yes")) }, }, @@ -1178,13 +1194,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkOracleDaoConsensusThreshold(c, value) + return proposeSettingNetworkOracleDaoConsensusThreshold(value, c.Bool("yes")) }, }, @@ -1210,13 +1226,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkNodePenaltyThreshold(c, value) + return proposeSettingNetworkNodePenaltyThreshold(value, c.Bool("yes")) }, }, @@ -1242,13 +1258,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkPerPenaltyRate(c, value) + return proposeSettingNetworkPerPenaltyRate(value, c.Bool("yes")) }, }, @@ -1276,7 +1292,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkIsSubmitBalancesEnabled(c, value) + return proposeSettingNetworkIsSubmitBalancesEnabled(value, c.Bool("yes")) }, }, @@ -1304,7 +1320,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkSubmitBalancesFrequency(c, value) + return proposeSettingNetworkSubmitBalancesFrequency(value, c.Bool("yes")) }, }, @@ -1332,7 +1348,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkIsSubmitPricesEnabled(c, value) + return proposeSettingNetworkIsSubmitPricesEnabled(value, c.Bool("yes")) }, }, @@ -1360,7 +1376,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkSubmitPricesFrequency(c, value) + return proposeSettingNetworkSubmitPricesFrequency(value, c.Bool("yes")) }, }, @@ -1386,13 +1402,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkMinimumNodeFee(c, value) + return proposeSettingNetworkMinimumNodeFee(value, c.Bool("yes")) }, }, @@ -1418,13 +1434,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkTargetNodeFee(c, value) + return proposeSettingNetworkTargetNodeFee(value, c.Bool("yes")) }, }, @@ -1450,13 +1466,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkMaximumNodeFee(c, value) + return proposeSettingNetworkMaximumNodeFee(value, c.Bool("yes")) }, }, @@ -1482,13 +1498,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkNodeFeeDemandRange(c, value) + return proposeSettingNetworkNodeFeeDemandRange(value, c.Bool("yes")) }, }, @@ -1514,13 +1530,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNetworkTargetRethCollateralRate(c, value) + return proposeSettingNetworkTargetRethCollateralRate(value, c.Bool("yes")) }, }, @@ -1548,7 +1564,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkIsSubmitRewardsEnabled(c, value) + return proposeSettingNetworkIsSubmitRewardsEnabled(value, c.Bool("yes")) }, }, @@ -1575,7 +1591,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { return err } // Run - return setAllowListedControllers(c) + return setAllowListedControllers(c.String("addressList"), c.Bool("yes")) }, }, @@ -1601,13 +1617,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNodeCommissionShare(c, value) + return proposeSettingNodeCommissionShare(value, c.Bool("yes")) }, }, @@ -1633,13 +1649,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNodeCommissionShareSecurityCouncilAdder(c, value) + return proposeSettingNodeCommissionShareSecurityCouncilAdder(value, c.Bool("yes")) }, }, @@ -1665,13 +1681,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingVoterShare(c, value) + return proposeSettingVoterShare(value, c.Bool("yes")) }, }, @@ -1697,13 +1713,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingPDAOShare(c, value) + return proposeSettingPDAOShare(value, c.Bool("yes")) }, }, @@ -1729,13 +1745,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeMaxNodeShareSecurityCouncilAdder(c, value) + return proposeMaxNodeShareSecurityCouncilAdder(value, c.Bool("yes")) }, }, @@ -1761,13 +1777,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeMaxRethBalanceDelta(c, value) + return proposeMaxRethBalanceDelta(value, c.Bool("yes")) }, }, @@ -1803,7 +1819,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeIsRegistrationEnabled(c, value) + return proposeSettingNodeIsRegistrationEnabled(value, c.Bool("yes")) }, }, @@ -1831,7 +1847,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeIsSmoothingPoolRegistrationEnabled(c, value) + return proposeSettingNodeIsSmoothingPoolRegistrationEnabled(value, c.Bool("yes")) }, }, @@ -1859,7 +1875,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeIsDepositingEnabled(c, value) + return proposeSettingNodeIsDepositingEnabled(value, c.Bool("yes")) }, }, @@ -1887,7 +1903,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeAreVacantMinipoolsEnabled(c, value) + return proposeSettingNodeAreVacantMinipoolsEnabled(value, c.Bool("yes")) }, }, @@ -1913,13 +1929,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNodeMinimumPerMinipoolStake(c, value) + return proposeSettingNodeMinimumPerMinipoolStake(value, c.Bool("yes")) }, }, @@ -1945,13 +1961,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNodeMaximumPerMinipoolStake(c, value) + return proposeSettingNodeMaximumPerMinipoolStake(value, c.Bool("yes")) }, }, @@ -1977,13 +1993,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNodeMinimumLegacyRplStake(c, value) + return proposeSettingNodeMinimumLegacyRplStake(value, c.Bool("yes")) }, }, @@ -2009,13 +2025,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingReducedBond(c, value) + return proposeSettingReducedBond(value, c.Bool("yes")) }, }, @@ -2043,7 +2059,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeUnstakingPeriod(c, value) + return proposeSettingNodeUnstakingPeriod(value, c.Bool("yes")) }, }, @@ -2079,7 +2095,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalsVotePhase1Time(c, value) + return proposeSettingProposalsVotePhase1Time(value, c.Bool("yes")) }, }, @@ -2107,7 +2123,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalsVotePhase2Time(c, value) + return proposeSettingProposalsVotePhase2Time(value, c.Bool("yes")) }, }, @@ -2135,7 +2151,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalsVoteDelayTime(c, value) + return proposeSettingProposalsVoteDelayTime(value, c.Bool("yes")) }, }, @@ -2163,7 +2179,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalsExecuteTime(c, value) + return proposeSettingProposalsExecuteTime(value, c.Bool("yes")) }, }, @@ -2189,13 +2205,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingProposalsProposalBond(c, value) + return proposeSettingProposalsProposalBond(value, c.Bool("yes")) }, }, @@ -2221,13 +2237,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingProposalsChallengeBond(c, value) + return proposeSettingProposalsChallengeBond(value, c.Bool("yes")) }, }, @@ -2255,7 +2271,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalsChallengePeriod(c, value) + return proposeSettingProposalsChallengePeriod(value, c.Bool("yes")) }, }, @@ -2281,13 +2297,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingProposalsQuorum(c, value) + return proposeSettingProposalsQuorum(value, c.Bool("yes")) }, }, @@ -2313,13 +2329,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingProposalsVetoQuorum(c, value) + return proposeSettingProposalsVetoQuorum(value, c.Bool("yes")) }, }, @@ -2347,7 +2363,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingProposalsMaxBlockAge(c, value) + return proposeSettingProposalsMaxBlockAge(value, c.Bool("yes")) }, }, @@ -2383,7 +2399,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingRewardsIntervalPeriods(c, value) + return proposeSettingRewardsIntervalPeriods(value, c.Bool("yes")) }, }, @@ -2417,13 +2433,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingSecurityMembersQuorum(c, value) + return proposeSettingSecurityMembersQuorum(value, c.Bool("yes")) }, }, @@ -2451,7 +2467,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingSecurityMembersLeaveTime(c, value) + return proposeSettingSecurityMembersLeaveTime(value, c.Bool("yes")) }, }, @@ -2479,7 +2495,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingSecurityProposalVoteTime(c, value) + return proposeSettingSecurityProposalVoteTime(value, c.Bool("yes")) }, }, @@ -2507,7 +2523,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingSecurityProposalExecuteTime(c, value) + return proposeSettingSecurityProposalExecuteTime(value, c.Bool("yes")) }, }, @@ -2535,7 +2551,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingSecurityProposalActionTime(c, value) + return proposeSettingSecurityProposalActionTime(value, c.Bool("yes")) }, }, @@ -2571,7 +2587,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMegapoolTimeBeforeDissolve(c, value) + return proposeSettingMegapoolTimeBeforeDissolve(value, c.Bool("yes")) }, }, @@ -2597,13 +2613,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingMaximumMegapoolEthPenalty(c, value) + return proposeSettingMaximumMegapoolEthPenalty(value, c.Bool("yes")) }, }, @@ -2631,7 +2647,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMegapoolNotifyThreshold(c, value) + return proposeSettingMegapoolNotifyThreshold(value, c.Bool("yes")) }, }, @@ -2657,13 +2673,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingMegapoolLateNotifyFine(c, value) + return proposeSettingMegapoolLateNotifyFine(value, c.Bool("yes")) }, }, @@ -2685,13 +2701,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), false) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), false, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingMegapoolDissolvePenalty(c, value) + return proposeSettingMegapoolDissolvePenalty(value, c.Bool("yes")) }, }, @@ -2718,7 +2734,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMegapoolUserDistributeDelay(c, value) + return proposeSettingMegapoolUserDistributeDelay(value, c.Bool("yes")) }, }, @@ -2745,7 +2761,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMegapoolUserDistributeDelayWithShortfall(c, value) + return proposeSettingMegapoolUserDistributeDelayWithShortfall(value, c.Bool("yes")) }, }, @@ -2771,13 +2787,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingProposalsVetoQuorum(c, value) + return proposeSettingPenaltyThreshold(value, c.Bool("yes")) }, }, @@ -2814,7 +2830,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getProposals(c, c.String("states")) + return getProposals(c.String("states")) }, }, @@ -2837,7 +2853,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getProposal(c, id) + return getProposal(id) }, }, @@ -2869,7 +2885,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return voteOnProposal(c) + return voteOnProposal(c.String("proposal"), c.String("vote-direction"), c.Bool("yes")) }, }, @@ -2903,7 +2919,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return executeProposal(c) + return executeProposal(c.String("proposal"), c.Bool("yes")) }, }, @@ -2935,7 +2951,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return defeatProposal(c, proposalId, index) + return defeatProposal(proposalId, index, c.Bool("yes")) }, }, @@ -2963,7 +2979,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return finalizeProposal(c, proposalId) + return finalizeProposal(proposalId, c.Bool("yes")) }, }, diff --git a/rocketpool-cli/pdao/defeat-proposal.go b/rocketpool-cli/pdao/defeat-proposal.go index 23682b696..8ab87f8aa 100644 --- a/rocketpool-cli/pdao/defeat-proposal.go +++ b/rocketpool-cli/pdao/defeat-proposal.go @@ -3,17 +3,15 @@ package pdao import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func defeatProposal(c *cli.Context, proposalID uint64, challengedIndex uint64) error { +func defeatProposal(proposalID uint64, challengedIndex uint64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -42,13 +40,13 @@ func defeatProposal(c *cli.Context, proposalID uint64, challengedIndex uint64) e } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to defeat proposal %d?", proposalID)) { + if !(yes || prompt.Confirm("Are you sure you want to defeat proposal %d?", proposalID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/execute-proposal.go b/rocketpool-cli/pdao/execute-proposal.go index 5d2c5c221..0d4ba3657 100644 --- a/rocketpool-cli/pdao/execute-proposal.go +++ b/rocketpool-cli/pdao/execute-proposal.go @@ -7,7 +7,6 @@ import ( rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/strings" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func executeProposal(c *cli.Context) error { +func executeProposal(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -47,17 +46,17 @@ func executeProposal(c *cli.Context) error { // Get selected proposal var selectedProposals []api.PDAOProposalWithNodeVoteDirection - if c.String("proposal") == "all" { + if proposal == "all" { // Select all proposals selectedProposals = executableProposals - } else if c.String("proposal") != "" { + } else if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -115,13 +114,13 @@ func executeProposal(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { + if !(yes || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/finalize-proposal.go b/rocketpool-cli/pdao/finalize-proposal.go index 349892f8a..cf7376115 100644 --- a/rocketpool-cli/pdao/finalize-proposal.go +++ b/rocketpool-cli/pdao/finalize-proposal.go @@ -3,17 +3,15 @@ package pdao import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func finalizeProposal(c *cli.Context, proposalID uint64) error { +func finalizeProposal(proposalID uint64, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -39,13 +37,13 @@ func finalizeProposal(c *cli.Context, proposalID uint64) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to finalize proposal %d?", proposalID)) { + if !(yes || prompt.Confirm("Are you sure you want to finalize proposal %d?", proposalID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/get-settings.go b/rocketpool-cli/pdao/get-settings.go index 3b1e04e95..e86261183 100644 --- a/rocketpool-cli/pdao/get-settings.go +++ b/rocketpool-cli/pdao/get-settings.go @@ -3,15 +3,13 @@ package pdao import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/bindings/utils/eth" "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func getSettings(c *cli.Context) error { +func getSettings() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/pdao/invite-sc.go b/rocketpool-cli/pdao/invite-sc.go index 1baa5a897..11a3712e5 100644 --- a/rocketpool-cli/pdao/invite-sc.go +++ b/rocketpool-cli/pdao/invite-sc.go @@ -7,19 +7,17 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func proposeSecurityCouncilInvite(c *cli.Context) error { +func proposeSecurityCouncilInvite(id string, addressFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() // Get the ID - id := c.String("id") if id == "" { id = prompt.Prompt("Please enter an ID for the member you'd like to invite: (no spaces)", "^\\S+$", "Invalid ID") } @@ -29,11 +27,10 @@ func proposeSecurityCouncilInvite(c *cli.Context) error { } // Get the address - addressString := c.String("address") - if addressString == "" { - addressString = prompt.Prompt("Please enter the member's address:", "^0x[0-9a-fA-F]{40}$", "Invalid member address") + if addressFlag == "" { + addressFlag = prompt.Prompt("Please enter the member's address:", "^0x[0-9a-fA-F]{40}$", "Invalid member address") } - address, err := cliutils.ValidateAddress("address", addressString) + address, err := cliutils.ValidateAddress("address", addressFlag) if err != nil { return err } @@ -55,13 +52,13 @@ func proposeSecurityCouncilInvite(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose inviting %s (%s) to the security council?", id, address.Hex())) { + if !(yes || prompt.Confirm("Are you sure you want to propose inviting %s (%s) to the security council?", id, address.Hex())) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/kick-sc.go b/rocketpool-cli/pdao/kick-sc.go index a177f9bbb..c04c0ed2a 100644 --- a/rocketpool-cli/pdao/kick-sc.go +++ b/rocketpool-cli/pdao/kick-sc.go @@ -11,12 +11,11 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func proposeSecurityCouncilKick(c *cli.Context) error { +func proposeSecurityCouncilKick(addressesFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -30,8 +29,7 @@ func proposeSecurityCouncilKick(c *cli.Context) error { // Get the address var addresses []common.Address - addressesString := c.String("addresses") - if addressesString == "" { + if addressesFlag == "" { // Print the members if len(membersResponse.Members) == 0 { fmt.Printf("There are no security council members.") @@ -77,7 +75,7 @@ func proposeSecurityCouncilKick(c *cli.Context) error { } } } else { - addresses, err = cliutils.ValidateAddresses("addresses", addressesString) + addresses, err = cliutils.ValidateAddresses("addresses", addressesFlag) if err != nil { return err } @@ -112,13 +110,13 @@ func proposeSecurityCouncilKick(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose kicking %s (%s) from the security council?", *id, address.Hex())) { + if !(yes || prompt.Confirm("Are you sure you want to propose kicking %s (%s) from the security council?", *id, address.Hex())) { fmt.Println("Cancelled.") return nil } @@ -153,7 +151,7 @@ func proposeSecurityCouncilKick(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } @@ -165,7 +163,7 @@ func proposeSecurityCouncilKick(c *cli.Context) error { } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose kicking these members from the security council?\n%s", kickString)) { + if !(yes || prompt.Confirm("Are you sure you want to propose kicking these members from the security council?\n%s", kickString)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/one-time-spend.go b/rocketpool-cli/pdao/one-time-spend.go index e2a487d0b..1631791de 100644 --- a/rocketpool-cli/pdao/one-time-spend.go +++ b/rocketpool-cli/pdao/one-time-spend.go @@ -8,68 +8,61 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func proposeOneTimeSpend(c *cli.Context) error { +func proposeOneTimeSpend(invoiceIDFlag string, recipientFlag string, amountFlag string, customMessageFlag string, rawEnabled bool, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() - // Check for the raw flag - rawEnabled := c.Bool("raw") - // Get the invoice ID - invoiceID := c.String("invoice-id") - if invoiceID == "" { - invoiceID = prompt.Prompt("Please enter an invoice ID for this spend: ", "^\\s*\\S+\\s*$", "Invalid ID") + if invoiceIDFlag == "" { + invoiceIDFlag = prompt.Prompt("Please enter an invoice ID for this spend: ", "^\\s*\\S+\\s*$", "Invalid ID") } // Get the recipient - recipientString := c.String("recipient") - if recipientString == "" { - recipientString = prompt.Prompt("Please enter a recipient address for this spend:", "^0x[0-9a-fA-F]{40}$", "Invalid recipient address") + if recipientFlag == "" { + recipientFlag = prompt.Prompt("Please enter a recipient address for this spend:", "^0x[0-9a-fA-F]{40}$", "Invalid recipient address") } - recipient, err := cliutils.ValidateAddress("recipient", recipientString) + recipient, err := cliutils.ValidateAddress("recipient", recipientFlag) if err != nil { return err } // Get the amount string - amountString := c.String("amount") - if amountString == "" { + if amountFlag == "" { if rawEnabled { - amountString = prompt.Prompt(fmt.Sprintf("Please enter an amount of RPL to send to %s as a wei amount:", recipientString), "^[0-9]+$", "Invalid amount") + amountFlag = prompt.Prompt(fmt.Sprintf("Please enter an amount of RPL to send to %s as a wei amount:", recipientFlag), "^[0-9]+$", "Invalid amount") } else { - amountString = prompt.Prompt(fmt.Sprintf("Please enter an amount of RPL to send to %s:", recipientString), "^[0-9]+(\\.[0-9]+)?$", "Invalid amount") + amountFlag = prompt.Prompt(fmt.Sprintf("Please enter an amount of RPL to send to %s:", recipientFlag), "^[0-9]+(\\.[0-9]+)?$", "Invalid amount") } } // Parse the amount var amount *big.Int if rawEnabled { - amount, err = cliutils.ValidateBigInt("amount", amountString) + amount, err = cliutils.ValidateBigInt("amount", amountFlag) } else { - amount, err = cliutils.ValidateFloat(c, "amount", amountString, false) + amount, err = cliutils.ValidateFloat(rawEnabled, "amount", amountFlag, false, yes) } if err != nil { return err } // Get the custom message - message := c.String("custom-message") - if message == "" { + var message string + if customMessageFlag == "" { message = prompt.Prompt("Please enter a custom message for this one-time spend (no blank spaces):", "^\\S*$", "Invalid message") } if message == "" { - message = fmt.Sprintf("one-time-spend-for-invoice-%s", invoiceID) + message = fmt.Sprintf("one-time-spend-for-invoice-%s", invoiceIDFlag) } // Check submissions - canResponse, err := rp.PDAOCanProposeOneTimeSpend(invoiceID, recipient, amount, message) + canResponse, err := rp.PDAOCanProposeOneTimeSpend(invoiceIDFlag, recipient, amount, message) if err != nil { return err } @@ -82,24 +75,24 @@ func proposeOneTimeSpend(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose this one-time spend of the Protocol DAO treasury?")) { + if !(yes || prompt.Confirm("Are you sure you want to propose this one-time spend of the Protocol DAO treasury?")) { fmt.Println("Cancelled.") return nil } // Submit - response, err := rp.PDAOProposeOneTimeSpend(invoiceID, recipient, amount, canResponse.BlockNumber, message) + response, err := rp.PDAOProposeOneTimeSpend(invoiceIDFlag, recipient, amount, canResponse.BlockNumber, message) if err != nil { return err } - fmt.Printf("Proposing one-time spend...\n") + fmt.Println("Proposing one-time spend...") cliutils.PrintTransactionHash(rp, response.TxHash) if _, err = rp.WaitForTransaction(response.TxHash); err != nil { return err diff --git a/rocketpool-cli/pdao/percentages.go b/rocketpool-cli/pdao/percentages.go index 906e4c45a..6f74e1041 100644 --- a/rocketpool-cli/pdao/percentages.go +++ b/rocketpool-cli/pdao/percentages.go @@ -8,12 +8,11 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func getRewardsPercentages(c *cli.Context) error { +func getRewardsPercentages() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -32,19 +31,16 @@ func getRewardsPercentages(c *cli.Context) error { return nil } -func proposeRewardsPercentages(c *cli.Context) error { +func proposeRewardsPercentages(rawEnabled bool, nodeFlag string, odaoFlag string, pdaoFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() - // Check for the raw flag - rawEnabled := c.Bool("raw") - // Get the node op percent - nodeString := c.String("node") + nodeString := nodeFlag if nodeString == "" { if rawEnabled { nodeString = prompt.Prompt("Please enter the new rewards allocation for node operators (as an 18-decimal-fixed-point-integer (wei) value):", "^\\d+$", "Invalid amount") @@ -52,13 +48,13 @@ func proposeRewardsPercentages(c *cli.Context) error { nodeString = prompt.Prompt("Please enter the new rewards allocation for node operators as a percentage from 0 to 1:", "^\\d+(\\.\\d+)?$", "Invalid amount") } } - nodePercent, err := cliutils.ValidateFloat(c, "node-percent", nodeString, true) + nodePercent, err := cliutils.ValidateFloat(rawEnabled, "node-percent", nodeString, true, yes) if err != nil { return err } // Get the oDAO percent - odaoString := c.String("odao") + odaoString := odaoFlag if odaoString == "" { if rawEnabled { odaoString = prompt.Prompt("Please enter the new rewards allocation for the Oracle DAO (as an 18-decimal-fixed-point-integer (wei) value):", "^\\d+$", "Invalid amount") @@ -66,13 +62,13 @@ func proposeRewardsPercentages(c *cli.Context) error { odaoString = prompt.Prompt("Please enter the new rewards allocation for the Oracle DAO as a percentage from 0 to 1:", "^\\d+(\\.\\d+)?$", "Invalid amount") } } - odaoPercent, err := cliutils.ValidateFloat(c, "odao-percent", odaoString, true) + odaoPercent, err := cliutils.ValidateFloat(rawEnabled, "odao-percent", odaoString, true, yes) if err != nil { return err } // Get the pDAO percent - pdaoString := c.String("pdao") + pdaoString := pdaoFlag if pdaoString == "" { if rawEnabled { pdaoString = prompt.Prompt("Please enter the new rewards allocation for the Protocol DAO treasury (as an 18-decimal-fixed-point-integer (wei) value):", "^\\d+$", "Invalid amount") @@ -80,7 +76,7 @@ func proposeRewardsPercentages(c *cli.Context) error { pdaoString = prompt.Prompt("Please enter the new rewards allocation for the Protocol DAO treasury as a percentage from 0 to 1:", "^\\d+(\\.\\d+)?$", "Invalid amount") } } - pdaoPercent, err := cliutils.ValidateFloat(c, "pdao-percent", pdaoString, true) + pdaoPercent, err := cliutils.ValidateFloat(rawEnabled, "pdao-percent", pdaoString, true, yes) if err != nil { return err } @@ -99,13 +95,13 @@ func proposeRewardsPercentages(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose new rewards allocations?")) { + if !(yes || prompt.Confirm("Are you sure you want to propose new rewards allocations?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/proposals.go b/rocketpool-cli/pdao/proposals.go index a41bd6c68..b5b356a07 100644 --- a/rocketpool-cli/pdao/proposals.go +++ b/rocketpool-cli/pdao/proposals.go @@ -12,8 +12,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/utils/eth" utilsStrings "github.com/rocket-pool/smartnode/bindings/utils/strings" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/types/api" utilsMath "github.com/rocket-pool/smartnode/shared/utils/math" @@ -30,10 +28,10 @@ func filterProposalState(state string, stateFilter string) bool { return !slices.Contains(filterStates, state) } -func getProposals(c *cli.Context, stateFilter string) error { +func getProposals(stateFilter string) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -96,9 +94,9 @@ func getProposals(c *cli.Context, stateFilter string) error { } -func getProposal(c *cli.Context, id uint64) error { +func getProposal(id uint64) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/pdao/propose-settings.go b/rocketpool-cli/pdao/propose-settings.go index fbd21a763..5c677ae8b 100644 --- a/rocketpool-cli/pdao/propose-settings.go +++ b/rocketpool-cli/pdao/propose-settings.go @@ -9,7 +9,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/rocket-pool/smartnode/bindings/settings/protocol" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" protocol131 "github.com/rocket-pool/smartnode/bindings/legacy/v1.3.1/protocol" "github.com/rocket-pool/smartnode/shared/services/gas" @@ -19,389 +18,389 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func proposeSettingAuctionIsCreateLotEnabled(c *cli.Context, value bool) error { +func proposeSettingAuctionIsCreateLotEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.CreateLotEnabledSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.CreateLotEnabledSettingPath, trueValue, yes) } -func proposeSettingAuctionIsBidOnLotEnabled(c *cli.Context, value bool) error { +func proposeSettingAuctionIsBidOnLotEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.BidOnLotEnabledSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.BidOnLotEnabledSettingPath, trueValue, yes) } -func proposeSettingAuctionLotMinimumEthValue(c *cli.Context, value *big.Int) error { +func proposeSettingAuctionLotMinimumEthValue(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.LotMinimumEthValueSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.LotMinimumEthValueSettingPath, trueValue, yes) } -func proposeSettingAuctionLotMaximumEthValue(c *cli.Context, value *big.Int) error { +func proposeSettingAuctionLotMaximumEthValue(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.LotMaximumEthValueSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.LotMaximumEthValueSettingPath, trueValue, yes) } -func proposeSettingAuctionLotDuration(c *cli.Context, value time.Duration) error { +func proposeSettingAuctionLotDuration(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.LotDurationSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.LotDurationSettingPath, trueValue, yes) } -func proposeSettingAuctionLotStartingPriceRatio(c *cli.Context, value *big.Int) error { +func proposeSettingAuctionLotStartingPriceRatio(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.LotStartingPriceRatioSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.LotStartingPriceRatioSettingPath, trueValue, yes) } -func proposeSettingAuctionLotReservePriceRatio(c *cli.Context, value *big.Int) error { +func proposeSettingAuctionLotReservePriceRatio(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.LotReservePriceRatioSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.LotReservePriceRatioSettingPath, trueValue, yes) } -func proposeSettingDepositIsDepositingEnabled(c *cli.Context, value bool) error { +func proposeSettingDepositIsDepositingEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.DepositEnabledSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.DepositEnabledSettingPath, trueValue, yes) } -func proposeSettingDepositAreDepositAssignmentsEnabled(c *cli.Context, value bool) error { +func proposeSettingDepositAreDepositAssignmentsEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.AssignDepositsEnabledSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.AssignDepositsEnabledSettingPath, trueValue, yes) } -func proposeSettingDepositMinimumDeposit(c *cli.Context, value *big.Int) error { +func proposeSettingDepositMinimumDeposit(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.MinimumDepositSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.MinimumDepositSettingPath, trueValue, yes) } -func proposeSettingDepositMaximumDepositPoolSize(c *cli.Context, value *big.Int) error { +func proposeSettingDepositMaximumDepositPoolSize(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.MaximumDepositPoolSizeSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.MaximumDepositPoolSizeSettingPath, trueValue, yes) } -func proposeSettingDepositMaximumAssignmentsPerDeposit(c *cli.Context, value uint64) error { +func proposeSettingDepositMaximumAssignmentsPerDeposit(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.MaximumDepositAssignmentsSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.MaximumDepositAssignmentsSettingPath, trueValue, yes) } -func proposeSettingDepositMaximumSocialisedAssignmentsPerDeposit(c *cli.Context, value uint64) error { +func proposeSettingDepositMaximumSocialisedAssignmentsPerDeposit(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.MaximumSocializedDepositAssignmentsSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.MaximumSocializedDepositAssignmentsSettingPath, trueValue, yes) } -func proposeSettingDepositExpressQueueRate(c *cli.Context, value uint64) error { +func proposeSettingDepositExpressQueueRate(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.ExpressQueueRatePath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.ExpressQueueRatePath, trueValue, yes) } -func proposeSettingDepositExpressQueueTicketsBaseProvision(c *cli.Context, value uint64) error { +func proposeSettingDepositExpressQueueTicketsBaseProvision(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.ExpressQueueTicketsBaseProvisionPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.ExpressQueueTicketsBaseProvisionPath, trueValue, yes) } -func proposeSettingDepositDepositFee(c *cli.Context, value *big.Int) error { +func proposeSettingDepositDepositFee(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.DepositFeeSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.DepositFeeSettingPath, trueValue, yes) } -func proposeSettingMinipoolIsSubmitWithdrawableEnabled(c *cli.Context, value bool) error { +func proposeSettingMinipoolIsSubmitWithdrawableEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.MinipoolSubmitWithdrawableEnabledSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.MinipoolSubmitWithdrawableEnabledSettingPath, trueValue, yes) } -func proposeSettingMinipoolLaunchTimeout(c *cli.Context, value time.Duration) error { +func proposeSettingMinipoolLaunchTimeout(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.MinipoolLaunchTimeoutSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.MinipoolLaunchTimeoutSettingPath, trueValue, yes) } -func proposeSettingMinipoolIsBondReductionEnabled(c *cli.Context, value bool) error { +func proposeSettingMinipoolIsBondReductionEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.BondReductionEnabledSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.BondReductionEnabledSettingPath, trueValue, yes) } -func proposeSettingMinipoolMaximumCount(c *cli.Context, value uint64) error { +func proposeSettingMinipoolMaximumCount(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.MaximumMinipoolCountSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.MaximumMinipoolCountSettingPath, trueValue, yes) } -func proposeSettingMinipoolUserDistributeWindowStart(c *cli.Context, value time.Duration) error { +func proposeSettingMinipoolUserDistributeWindowStart(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.MinipoolUserDistributeWindowStartSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.MinipoolUserDistributeWindowStartSettingPath, trueValue, yes) } -func proposeSettingMinipoolUserDistributeWindowLength(c *cli.Context, value time.Duration) error { +func proposeSettingMinipoolUserDistributeWindowLength(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.MinipoolUserDistributeWindowLengthSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.MinipoolUserDistributeWindowLengthSettingPath, trueValue, yes) } -func proposeSettingNetworkOracleDaoConsensusThreshold(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkOracleDaoConsensusThreshold(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NodeConsensusThresholdSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NodeConsensusThresholdSettingPath, trueValue, yes) } -func proposeSettingNetworkNodePenaltyThreshold(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkNodePenaltyThreshold(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkPenaltyThresholdSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkPenaltyThresholdSettingPath, trueValue, yes) } -func proposeSettingNetworkPerPenaltyRate(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkPerPenaltyRate(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkPenaltyPerRateSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkPenaltyPerRateSettingPath, trueValue, yes) } -func proposeSettingNetworkIsSubmitBalancesEnabled(c *cli.Context, value bool) error { +func proposeSettingNetworkIsSubmitBalancesEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitBalancesEnabledSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitBalancesEnabledSettingPath, trueValue, yes) } -func proposeSettingNetworkSubmitBalancesFrequency(c *cli.Context, value time.Duration) error { +func proposeSettingNetworkSubmitBalancesFrequency(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitBalancesFrequencySettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitBalancesFrequencySettingPath, trueValue, yes) } -func proposeSettingNetworkIsSubmitPricesEnabled(c *cli.Context, value bool) error { +func proposeSettingNetworkIsSubmitPricesEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitPricesEnabledSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitPricesEnabledSettingPath, trueValue, yes) } -func proposeSettingNetworkSubmitPricesFrequency(c *cli.Context, value time.Duration) error { +func proposeSettingNetworkSubmitPricesFrequency(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitPricesFrequencySettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitPricesFrequencySettingPath, trueValue, yes) } -func proposeSettingNetworkMinimumNodeFee(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkMinimumNodeFee(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.MinimumNodeFeeSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.MinimumNodeFeeSettingPath, trueValue, yes) } -func proposeSettingNetworkTargetNodeFee(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkTargetNodeFee(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.TargetNodeFeeSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.TargetNodeFeeSettingPath, trueValue, yes) } -func proposeSettingNetworkMaximumNodeFee(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkMaximumNodeFee(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.MaximumNodeFeeSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.MaximumNodeFeeSettingPath, trueValue, yes) } -func proposeSettingNetworkNodeFeeDemandRange(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkNodeFeeDemandRange(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NodeFeeDemandRangeSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NodeFeeDemandRangeSettingPath, trueValue, yes) } -func proposeSettingNetworkTargetRethCollateralRate(c *cli.Context, value *big.Int) error { +func proposeSettingNetworkTargetRethCollateralRate(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.TargetRethCollateralRateSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.TargetRethCollateralRateSettingPath, trueValue, yes) } -func proposeSettingNetworkIsSubmitRewardsEnabled(c *cli.Context, value bool) error { +func proposeSettingNetworkIsSubmitRewardsEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitRewardsEnabledSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitRewardsEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeIsRegistrationEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeIsRegistrationEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.NodeRegistrationEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.NodeRegistrationEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeIsSmoothingPoolRegistrationEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeIsSmoothingPoolRegistrationEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.SmoothingPoolRegistrationEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.SmoothingPoolRegistrationEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeIsDepositingEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeIsDepositingEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.NodeDepositEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.NodeDepositEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeAreVacantMinipoolsEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeAreVacantMinipoolsEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.VacantMinipoolsEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.VacantMinipoolsEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeMinimumPerMinipoolStake(c *cli.Context, value *big.Int) error { +func proposeSettingNodeMinimumPerMinipoolStake(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NodeSettingsContractName, protocol131.MinimumPerMinipoolStakeSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol131.MinimumPerMinipoolStakeSettingPath, trueValue, yes) } -func proposeSettingNodeMaximumPerMinipoolStake(c *cli.Context, value *big.Int) error { +func proposeSettingNodeMaximumPerMinipoolStake(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NodeSettingsContractName, protocol131.MaximumPerMinipoolStakeSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol131.MaximumPerMinipoolStakeSettingPath, trueValue, yes) } -func proposeSettingNodeMinimumLegacyRplStake(c *cli.Context, value *big.Int) error { +func proposeSettingNodeMinimumLegacyRplStake(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.MinimumLegacyRplStakePath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.MinimumLegacyRplStakePath, trueValue, yes) } -func proposeSettingReducedBond(c *cli.Context, value *big.Int) error { +func proposeSettingReducedBond(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.ReducedBondSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.ReducedBondSettingPath, trueValue, yes) } -func proposeSettingNodeUnstakingPeriod(c *cli.Context, value time.Duration) error { +func proposeSettingNodeUnstakingPeriod(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.NodeUnstakingPeriodSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.NodeUnstakingPeriodSettingPath, trueValue, yes) } -func proposeSettingProposalsVotePhase1Time(c *cli.Context, value time.Duration) error { +func proposeSettingProposalsVotePhase1Time(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.VotePhase1TimeSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.VotePhase1TimeSettingPath, trueValue, yes) } -func proposeSettingProposalsVotePhase2Time(c *cli.Context, value time.Duration) error { +func proposeSettingProposalsVotePhase2Time(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.VotePhase2TimeSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.VotePhase2TimeSettingPath, trueValue, yes) } -func proposeSettingProposalsVoteDelayTime(c *cli.Context, value time.Duration) error { +func proposeSettingProposalsVoteDelayTime(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.VoteDelayTimeSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.VoteDelayTimeSettingPath, trueValue, yes) } -func proposeSettingProposalsExecuteTime(c *cli.Context, value time.Duration) error { +func proposeSettingProposalsExecuteTime(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ExecuteTimeSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ExecuteTimeSettingPath, trueValue, yes) } -func proposeSettingProposalsProposalBond(c *cli.Context, value *big.Int) error { +func proposeSettingProposalsProposalBond(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ProposalBondSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ProposalBondSettingPath, trueValue, yes) } -func proposeSettingProposalsChallengeBond(c *cli.Context, value *big.Int) error { +func proposeSettingProposalsChallengeBond(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ChallengeBondSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ChallengeBondSettingPath, trueValue, yes) } -func proposeSettingProposalsChallengePeriod(c *cli.Context, value time.Duration) error { +func proposeSettingProposalsChallengePeriod(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ChallengePeriodSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ChallengePeriodSettingPath, trueValue, yes) } -func proposeSettingProposalsQuorum(c *cli.Context, value *big.Int) error { +func proposeSettingProposalsQuorum(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ProposalQuorumSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ProposalQuorumSettingPath, trueValue, yes) } -func proposeSettingProposalsVetoQuorum(c *cli.Context, value *big.Int) error { +func proposeSettingProposalsVetoQuorum(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ProposalVetoQuorumSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ProposalVetoQuorumSettingPath, trueValue, yes) } -func proposeSettingProposalsMaxBlockAge(c *cli.Context, value uint64) error { +func proposeSettingProposalsMaxBlockAge(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.ProposalsSettingsContractName, protocol.ProposalMaxBlockAgeSettingPath, trueValue) + return proposeSetting(protocol.ProposalsSettingsContractName, protocol.ProposalMaxBlockAgeSettingPath, trueValue, yes) } -func proposeSettingRewardsIntervalPeriods(c *cli.Context, value uint64) error { +func proposeSettingRewardsIntervalPeriods(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.RewardsSettingsContractName, protocol.RewardsClaimIntervalPeriodsSettingPath, trueValue) + return proposeSetting(protocol.RewardsSettingsContractName, protocol.RewardsClaimIntervalPeriodsSettingPath, trueValue, yes) } -func proposeSettingSecurityMembersQuorum(c *cli.Context, value *big.Int) error { +func proposeSettingSecurityMembersQuorum(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.SecuritySettingsContractName, protocol.SecurityMembersQuorumSettingPath, trueValue) + return proposeSetting(protocol.SecuritySettingsContractName, protocol.SecurityMembersQuorumSettingPath, trueValue, yes) } -func proposeSettingSecurityMembersLeaveTime(c *cli.Context, value time.Duration) error { +func proposeSettingSecurityMembersLeaveTime(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.SecuritySettingsContractName, protocol.SecurityMembersLeaveTimeSettingPath, trueValue) + return proposeSetting(protocol.SecuritySettingsContractName, protocol.SecurityMembersLeaveTimeSettingPath, trueValue, yes) } -func proposeSettingSecurityProposalVoteTime(c *cli.Context, value time.Duration) error { +func proposeSettingSecurityProposalVoteTime(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.SecuritySettingsContractName, protocol.SecurityProposalVoteTimeSettingPath, trueValue) + return proposeSetting(protocol.SecuritySettingsContractName, protocol.SecurityProposalVoteTimeSettingPath, trueValue, yes) } -func proposeSettingSecurityProposalExecuteTime(c *cli.Context, value time.Duration) error { +func proposeSettingSecurityProposalExecuteTime(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.SecuritySettingsContractName, protocol.SecurityProposalExecuteTimeSettingPath, trueValue) + return proposeSetting(protocol.SecuritySettingsContractName, protocol.SecurityProposalExecuteTimeSettingPath, trueValue, yes) } -func proposeSettingSecurityProposalActionTime(c *cli.Context, value time.Duration) error { +func proposeSettingSecurityProposalActionTime(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.SecuritySettingsContractName, protocol.SecurityProposalActionTimeSettingPath, trueValue) + return proposeSetting(protocol.SecuritySettingsContractName, protocol.SecurityProposalActionTimeSettingPath, trueValue, yes) } -func proposeSettingNetworkAllowListedControllers(c *cli.Context, value []common.Address) error { +func proposeSettingNetworkAllowListedControllers(value []common.Address, yes bool) error { strs := make([]string, len(value)) for i, addr := range value { strs[i] = addr.Hex() } trueValue := strings.Join(strs, "") - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkAllowListedControllersPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkAllowListedControllersPath, trueValue, yes) } -func proposeSettingMegapoolTimeBeforeDissolve(c *cli.Context, value time.Duration) error { +func proposeSettingMegapoolTimeBeforeDissolve(value time.Duration, yes bool) error { trueValue := fmt.Sprint(uint64(value.Seconds())) - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolTimeBeforeDissolveSettingsPath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolTimeBeforeDissolveSettingsPath, trueValue, yes) } -func proposeSettingMaximumMegapoolEthPenalty(c *cli.Context, value *big.Int) error { +func proposeSettingMaximumMegapoolEthPenalty(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolMaximumMegapoolEthPenaltyPath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolMaximumMegapoolEthPenaltyPath, trueValue, yes) } -func proposeSettingMegapoolNotifyThreshold(c *cli.Context, value uint64) error { +func proposeSettingMegapoolNotifyThreshold(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolNotifyThresholdPath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolNotifyThresholdPath, trueValue, yes) } -func proposeSettingMegapoolLateNotifyFine(c *cli.Context, value *big.Int) error { +func proposeSettingMegapoolLateNotifyFine(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolLateNotifyFinePath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolLateNotifyFinePath, trueValue, yes) } -func proposeSettingMegapoolDissolvePenalty(c *cli.Context, value *big.Int) error { +func proposeSettingMegapoolDissolvePenalty(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolDissolvePenaltyPath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolDissolvePenaltyPath, trueValue, yes) } -func proposeSettingMegapoolUserDistributeDelay(c *cli.Context, value uint64) error { +func proposeSettingMegapoolUserDistributeDelay(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolUserDistributeDelayPath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolUserDistributeDelayPath, trueValue, yes) } -func proposeSettingMegapoolUserDistributeDelayWithShortfall(c *cli.Context, value uint64) error { +func proposeSettingMegapoolUserDistributeDelayWithShortfall(value uint64, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolUserDistributeDelayShortfallPath, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolUserDistributeDelayShortfallPath, trueValue, yes) } -func proposeSettingPenaltyThreshold(c *cli.Context, value *big.Int) error { +func proposeSettingPenaltyThreshold(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.MegapoolSettingsContractName, protocol.MegapoolPenaltyThreshold, trueValue) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolPenaltyThreshold, trueValue, yes) } -func proposeSettingNodeCommissionShare(c *cli.Context, value *big.Int) error { +func proposeSettingNodeCommissionShare(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkNodeCommissionSharePath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkNodeCommissionSharePath, trueValue, yes) } -func proposeSettingNodeCommissionShareSecurityCouncilAdder(c *cli.Context, value *big.Int) error { +func proposeSettingNodeCommissionShareSecurityCouncilAdder(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkNodeCommissionShareSecurityCouncilAdderPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkNodeCommissionShareSecurityCouncilAdderPath, trueValue, yes) } -func proposeSettingVoterShare(c *cli.Context, value *big.Int) error { +func proposeSettingVoterShare(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkVoterSharePath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkVoterSharePath, trueValue, yes) } -func proposeSettingPDAOShare(c *cli.Context, value *big.Int) error { +func proposeSettingPDAOShare(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkPDAOSharePath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkPDAOSharePath, trueValue, yes) } -func proposeMaxNodeShareSecurityCouncilAdder(c *cli.Context, value *big.Int) error { +func proposeMaxNodeShareSecurityCouncilAdder(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkMaxNodeShareSecurityCouncilAdderPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkMaxNodeShareSecurityCouncilAdderPath, trueValue, yes) } -func proposeMaxRethBalanceDelta(c *cli.Context, value *big.Int) error { +func proposeMaxRethBalanceDelta(value *big.Int, yes bool) error { trueValue := value.String() - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkMaxRethBalanceDeltaPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkMaxRethBalanceDeltaPath, trueValue, yes) } // Master general proposal function -func proposeSetting(c *cli.Context, contract string, setting string, value string) error { +func proposeSetting(contract string, setting string, value string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -431,13 +430,13 @@ func proposeSetting(c *cli.Context, contract string, setting string, value strin } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/recurring-spend-update.go b/rocketpool-cli/pdao/recurring-spend-update.go index 3bcc134ed..ed68e836a 100644 --- a/rocketpool-cli/pdao/recurring-spend-update.go +++ b/rocketpool-cli/pdao/recurring-spend-update.go @@ -8,28 +8,22 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func proposeRecurringSpendUpdate(c *cli.Context) error { +func proposeRecurringSpendUpdate(rawEnabled bool, contractName string, recipientString string, amountString string, periodLengthString string, numPeriods uint64, customMessage string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() - // Check for the raw flag - rawEnabled := c.Bool("raw") - // Get the contract name - contractName := c.String("contract-name") if contractName == "" { contractName = prompt.Prompt("Please enter a contract name for this recurring payment: ", "^\\s*\\S+\\s*$", "Invalid ID") } // Get the recipient - recipientString := c.String("recipient") if recipientString == "" { recipientString = prompt.Prompt("Please enter a recipient address for this recurring payment:", "^0x[0-9a-fA-F]{40}$", "Invalid recipient address") } @@ -39,7 +33,6 @@ func proposeRecurringSpendUpdate(c *cli.Context) error { } // Get the amount string - amountString := c.String("amount-per-period") if amountString == "" { if rawEnabled { amountString = prompt.Prompt(fmt.Sprintf("Please enter an amount of RPL to send to %s per period as a wei amount:", recipientString), "^[0-9]+$", "Invalid amount") @@ -53,14 +46,13 @@ func proposeRecurringSpendUpdate(c *cli.Context) error { if rawEnabled { amount, err = cliutils.ValidateBigInt("amount-per-period", amountString) } else { - amount, err = cliutils.ValidateFloat(c, "amount-per-period", amountString, false) + amount, err = cliutils.ValidateFloat(rawEnabled, "amount-per-period", amountString, false, yes) } if err != nil { return err } // Get the period length - periodLengthString := c.String("period-length") if periodLengthString == "" { periodLengthString = prompt.Prompt("Please enter the length of each payment period in hours / minutes / seconds (e.g., 168h0m0s):", "^.+$", "Invalid period length") } @@ -70,8 +62,7 @@ func proposeRecurringSpendUpdate(c *cli.Context) error { } // Get the number of periods - numPeriods := c.Uint64("number-of-periods") - if !c.IsSet("number-of-periods") { + if numPeriods == 0 { numPeriodsString := prompt.Prompt("Please enter the total number of payment periods:", "^[0-9]+$", "Invalid number of periods") numPeriods, err = cliutils.ValidateUint("number-of-periods", numPeriodsString) if err != nil { @@ -80,7 +71,6 @@ func proposeRecurringSpendUpdate(c *cli.Context) error { } // Get the custom message - customMessage := c.String("custom-message") if customMessage == "" { customMessage = prompt.Prompt("Please enter a message for this recurring spend update (no blank spaces):", "^\\S*$", "Invalid message") } @@ -102,13 +92,13 @@ func proposeRecurringSpendUpdate(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose updating this recurring spend of the Protocol DAO treasury?")) { + if !(yes || prompt.Confirm("Are you sure you want to propose updating this recurring spend of the Protocol DAO treasury?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/recurring-spend.go b/rocketpool-cli/pdao/recurring-spend.go index ced7df750..5953b922d 100644 --- a/rocketpool-cli/pdao/recurring-spend.go +++ b/rocketpool-cli/pdao/recurring-spend.go @@ -9,28 +9,22 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func proposeRecurringSpend(c *cli.Context) error { +func proposeRecurringSpend(rawEnabled bool, contractName string, recipientString string, amountString string, startTimeUnix uint64, periodLengthString string, numPeriods uint64, customMessage string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() - // Check for the raw flag - rawEnabled := c.Bool("raw") - // Get the contract name - contractName := c.String("contract-name") if contractName == "" { contractName = prompt.Prompt("Please enter a contract name for this recurring payment:", "^\\s*\\S+\\s*$", "Invalid ID") } // Get the recipient - recipientString := c.String("recipient") if recipientString == "" { recipientString = prompt.Prompt("Please enter a recipient address for this recurring payment:", "^0x[0-9a-fA-F]{40}$", "Invalid recipient address") } @@ -40,7 +34,6 @@ func proposeRecurringSpend(c *cli.Context) error { } // Get the amount string - amountString := c.String("amount-per-period") if amountString == "" { if rawEnabled { amountString = prompt.Prompt(fmt.Sprintf("Please enter an amount of RPL to send to %s per period as a wei amount:", recipientString), "^[0-9]+$", "Invalid amount") @@ -54,15 +47,14 @@ func proposeRecurringSpend(c *cli.Context) error { if rawEnabled { amount, err = cliutils.ValidateBigInt("amount-per-period", amountString) } else { - amount, err = cliutils.ValidateFloat(c, "amount-per-period", amountString, false) + amount, err = cliutils.ValidateFloat(rawEnabled, "amount-per-period", amountString, false, yes) } if err != nil { return err } // Get the start time - startTimeUnix := c.Uint64("start-time") - if !c.IsSet("start-time") { + if startTimeUnix == 0 { startTimeString := prompt.Prompt("Please enter the time that the recurring payment will start (as a UNIX timestamp):", "^[0-9]+$", "Invalid start time") startTimeUnix, err = cliutils.ValidateUint("start-time", startTimeString) if err != nil { @@ -70,13 +62,12 @@ func proposeRecurringSpend(c *cli.Context) error { } } startTime := time.Unix(int64(startTimeUnix), 0) - if !(c.Bool("yes") || prompt.Confirm("The provided timestamp corresponds to %s - is this correct?", startTime.UTC().String())) { + if !(yes || prompt.Confirm("The provided timestamp corresponds to %s - is this correct?", startTime.UTC().String())) { fmt.Println("Cancelled.") return nil } // Get the period length - periodLengthString := c.String("period-length") if periodLengthString == "" { periodLengthString = prompt.Prompt("Please enter the length of each payment period in hours / minutes / seconds (e.g., 168h0m0s):", "^.+$", "Invalid period length") } @@ -86,8 +77,7 @@ func proposeRecurringSpend(c *cli.Context) error { } // Get the number of periods - numPeriods := c.Uint64("number-of-periods") - if !c.IsSet("number-of-periods") { + if numPeriods == 0 { numPeriodsString := prompt.Prompt("Please enter the total number of payment periods:", "^[0-9]+$", "Invalid number of periods") numPeriods, err = cliutils.ValidateUint("number-of-periods", numPeriodsString) if err != nil { @@ -96,7 +86,6 @@ func proposeRecurringSpend(c *cli.Context) error { } // Get the custom message - customMessage := c.String("custom-message") if customMessage == "" { // Prompt for a custom message without blank spaces customMessage = prompt.Prompt("Please enter an optional message for this recurring payment (no blank spaces):", "^\\S*$", "Invalid message") @@ -119,13 +108,13 @@ func proposeRecurringSpend(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose this recurring spend of the Protocol DAO treasury?")) { + if !(yes || prompt.Confirm("Are you sure you want to propose this recurring spend of the Protocol DAO treasury?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/replace-sc.go b/rocketpool-cli/pdao/replace-sc.go index 72f6c5c8d..dc9ef70d5 100644 --- a/rocketpool-cli/pdao/replace-sc.go +++ b/rocketpool-cli/pdao/replace-sc.go @@ -9,12 +9,11 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func proposeSecurityCouncilReplace(c *cli.Context) error { +func proposeSecurityCouncilReplace(existingAddressString string, newID string, newAddressString string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -29,8 +28,7 @@ func proposeSecurityCouncilReplace(c *cli.Context) error { // Get the address of the member to replace var oldID string var oldAddress common.Address - oldAddressString := c.String("existing-address") - if oldAddressString == "" { + if existingAddressString == "" { options := make([]string, len(membersResponse.Members)) for i, member := range membersResponse.Members { options[i] = fmt.Sprintf("%d: %s (%s), joined %s\n", i+1, member.ID, member.Address, time.Unix(int64(member.JoinedTime), 0)) @@ -40,7 +38,7 @@ func proposeSecurityCouncilReplace(c *cli.Context) error { oldID = member.ID oldAddress = member.Address } else { - oldAddress, err = cliutils.ValidateAddress("address", oldAddressString) + oldAddress, err = cliutils.ValidateAddress("address", existingAddressString) if err != nil { return err } @@ -58,7 +56,6 @@ func proposeSecurityCouncilReplace(c *cli.Context) error { } // Get the new ID - newID := c.String("new-id") if newID == "" { newID = prompt.Prompt("Please enter an ID for the member you'd like to invite: (no spaces)", "^\\S+$", "Invalid ID") } @@ -68,7 +65,6 @@ func proposeSecurityCouncilReplace(c *cli.Context) error { } // Get the new address - newAddressString := c.String("new-address") if newAddressString == "" { newAddressString = prompt.Prompt("Please enter the member's address:", "^0x[0-9a-fA-F]{40}$", "Invalid member address") } @@ -91,13 +87,13 @@ func proposeSecurityCouncilReplace(c *cli.Context) error { } // Assign max fee - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose removing %s (%s) from the security council and inviting %s (%s)?", oldID, oldAddress.Hex(), newID, newAddress.Hex())) { + if !(yes || prompt.Confirm("Are you sure you want to propose removing %s (%s) from the security council and inviting %s (%s)?", oldID, oldAddress.Hex(), newID, newAddress.Hex())) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/set-allow-list.go b/rocketpool-cli/pdao/set-allow-list.go index 162775bec..f92b176bd 100644 --- a/rocketpool-cli/pdao/set-allow-list.go +++ b/rocketpool-cli/pdao/set-allow-list.go @@ -10,20 +10,17 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func setAllowListedControllers(c *cli.Context) error { +func setAllowListedControllers(addressListStr string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } defer rp.Close() - var addressListStr string - addressListStr = c.String("addressList") if addressListStr == "" { // Ask the user how many addresses should be included in the list numStr := prompt.Prompt(fmt.Sprintf("How many addresses do you want to propose as allowlisted controllers? Enter 0 to propose clearing the list"), "^\\d+$", "Invalid number.") @@ -65,7 +62,7 @@ func setAllowListedControllers(c *cli.Context) error { } fmt.Println() - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to propose a new list of allowlisted controllers?")) { + if !(yes || prompt.Confirm("Are you sure you want to propose a new list of allowlisted controllers?")) { fmt.Println("Cancelled.") return nil } @@ -76,7 +73,7 @@ func setAllowListedControllers(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } diff --git a/rocketpool-cli/pdao/set-signalling-address.go b/rocketpool-cli/pdao/set-signalling-address.go index e922ad21c..37d25984b 100644 --- a/rocketpool-cli/pdao/set-signalling-address.go +++ b/rocketpool-cli/pdao/set-signalling-address.go @@ -8,13 +8,12 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func setSignallingAddress(c *cli.Context, signallingAddress common.Address, signature string) error { +func setSignallingAddress(signallingAddress common.Address, signature string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -32,13 +31,13 @@ func setSignallingAddress(c *cli.Context, signallingAddress common.Address, sign } // Assign max fees - err = gas.AssignMaxFeeAndLimit(resp.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(resp.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to set the signalling address?")) { + if !(yes || prompt.Confirm("Are you sure you want to set the signalling address?")) { fmt.Println("Cancelled.") return nil } @@ -60,10 +59,10 @@ func setSignallingAddress(c *cli.Context, signallingAddress common.Address, sign return nil } -func clearSignallingAddress(c *cli.Context) error { +func clearSignallingAddress(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -81,13 +80,13 @@ func clearSignallingAddress(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(resp.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(resp.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to clear the signalling address?")) { + if !(yes || prompt.Confirm("Are you sure you want to clear the signalling address?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/status.go b/rocketpool-cli/pdao/status.go index 236253343..67d0db884 100644 --- a/rocketpool-cli/pdao/status.go +++ b/rocketpool-cli/pdao/status.go @@ -6,7 +6,6 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/eth" @@ -23,10 +22,10 @@ const ( challengeLink string = "https://docs.rocketpool.net/pdao#challenge-process" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get wallet status diff --git a/rocketpool-cli/pdao/vote-proposal.go b/rocketpool-cli/pdao/vote-proposal.go index 5e6c8024f..dcb51a225 100644 --- a/rocketpool-cli/pdao/vote-proposal.go +++ b/rocketpool-cli/pdao/vote-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/types" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -16,10 +15,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func voteOnProposal(c *cli.Context) error { +func voteOnProposal(proposal, voteDirectionFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -53,12 +52,12 @@ func voteOnProposal(c *cli.Context) error { // Get selected proposal var selectedProposal api.PDAOProposalWithNodeVoteDirection - if c.String("proposal") != "" { + if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -112,10 +111,10 @@ func voteOnProposal(c *cli.Context) error { // Get support status var voteDirection types.VoteDirection var voteDirectionLabel string - if c.String("vote-direction") != "" { + if voteDirectionFlag != "" { // Parse vote direction var err error - voteDirection, err = cliutils.ValidateVoteDirection("vote-direction", c.String("vote-direction")) + voteDirection, err = cliutils.ValidateVoteDirection("vote-direction", voteDirectionFlag) if err != nil { return err } @@ -166,13 +165,13 @@ func voteOnProposal(c *cli.Context) error { fmt.Printf("\n\nYour voting power on this proposal: %.10f\n\n", eth.WeiToEth(canVote.VotingPower)) // Assign max fees - err = gas.AssignMaxFeeAndLimit(canVote.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canVote.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to %s with a vote for '%s' on proposal %d? Your vote cannot be changed later.", actionString, voteDirectionLabel, selectedProposal.ID)) { + if !(yes || prompt.Confirm("Are you sure you want to %s with a vote for '%s' on proposal %d? Your vote cannot be changed later.", actionString, voteDirectionLabel, selectedProposal.ID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/pdao/voting.go b/rocketpool-cli/pdao/voting.go index 49c780e62..179e7bd67 100644 --- a/rocketpool-cli/pdao/voting.go +++ b/rocketpool-cli/pdao/voting.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -13,9 +12,9 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func pdaoSetVotingDelegate(c *cli.Context, nameOrAddress string) error { +func pdaoSetVotingDelegate(nameOrAddress string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -45,13 +44,13 @@ func pdaoSetVotingDelegate(c *cli.Context, nameOrAddress string) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasEstimate.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasEstimate.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want %s to represent your node in Rocket Pool on-chain governance proposals?", addressString)) { + if !(yes || prompt.Confirm("Are you sure you want %s to represent your node in Rocket Pool on-chain governance proposals?", addressString)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/queue/assign-deposits.go b/rocketpool-cli/queue/assign-deposits.go index 269a04ab7..7d226fdda 100644 --- a/rocketpool-cli/queue/assign-deposits.go +++ b/rocketpool-cli/queue/assign-deposits.go @@ -5,8 +5,6 @@ import ( "math/big" "strconv" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/bindings/utils/eth" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -14,9 +12,9 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func assignDeposits(c *cli.Context) error { +func assignDeposits(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -88,13 +86,13 @@ func assignDeposits(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canAssign.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canAssign.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to assign %d validators?", maxValidators)) { + if !(yes || prompt.Confirm("Are you sure you want to assign %d validators?", maxValidators)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/queue/commands.go b/rocketpool-cli/queue/commands.go index 60d1e8980..e588c2476 100644 --- a/rocketpool-cli/queue/commands.go +++ b/rocketpool-cli/queue/commands.go @@ -27,7 +27,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -45,7 +45,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return processQueue(c) + return processQueue(c.Bool("yes")) }, }, @@ -69,7 +69,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return assignDeposits(c) + return assignDeposits(c.Bool("yes")) }, }, diff --git a/rocketpool-cli/queue/process.go b/rocketpool-cli/queue/process.go index ac0918905..713403366 100644 --- a/rocketpool-cli/queue/process.go +++ b/rocketpool-cli/queue/process.go @@ -4,17 +4,15 @@ import ( "fmt" "strconv" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func processQueue(c *cli.Context) error { +func processQueue(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -50,13 +48,13 @@ func processQueue(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canProcess.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canProcess.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Do you accept this gas fee?")) { + if !(yes || prompt.Confirm("Do you accept this gas fee?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/queue/status.go b/rocketpool-cli/queue/status.go index f128cca2f..8298cdd07 100644 --- a/rocketpool-cli/queue/status.go +++ b/rocketpool-cli/queue/status.go @@ -4,17 +4,16 @@ import ( "fmt" "github.com/rocket-pool/smartnode/bindings/utils/eth" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/types/api" "github.com/rocket-pool/smartnode/shared/utils/math" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/rocketpool-cli.go b/rocketpool-cli/rocketpool-cli.go index c55005581..5278197a4 100644 --- a/rocketpool-cli/rocketpool-cli.go +++ b/rocketpool-cli/rocketpool-cli.go @@ -128,7 +128,13 @@ A special thanks to the Rocket Pool community for all their contributions. Usage: "Don't verify the singature of the release", }, }, - Action: update.Update, + Action: func(c *cli.Context) error { + return update.Update( + c.Bool("yes"), + c.Bool("skip-signature-verification"), + c.Bool("force"), + ) + }, }) app.Before = func(c *cli.Context) error { @@ -139,6 +145,15 @@ A special thanks to the Rocket Pool community for all their contributions. os.Exit(1) } + Defaults := rocketpool.Globals{ + ConfigPath: os.ExpandEnv(c.GlobalString("config-path")), + DaemonPath: os.ExpandEnv(c.GlobalString("daemon-path")), + MaxFee: c.GlobalFloat64("maxFee"), + MaxPrioFee: c.GlobalFloat64("maxPrioFee"), + GasLimit: c.GlobalUint64("gasLimit"), + DebugPrint: c.GlobalBool("debug"), + } + // If set, validate custom nonce customNonce := c.GlobalString("nonce") if customNonce != "" { @@ -148,10 +163,11 @@ A special thanks to the Rocket Pool community for all their contributions. os.Exit(1) } - // Save the parsed value on Metadata so we don't need to reparse it later - c.App.Metadata["nonce"] = nonce + Defaults.CustomNonce = nonce } + rocketpool.SetDefaults(Defaults) + return nil } @@ -161,7 +177,7 @@ A special thanks to the Rocket Pool community for all their contributions. return nil } - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Check if the user has enabled the "show alerts after every command" setting. diff --git a/rocketpool-cli/security/cancel-proposal.go b/rocketpool-cli/security/cancel-proposal.go index 157309597..4371be55d 100644 --- a/rocketpool-cli/security/cancel-proposal.go +++ b/rocketpool-cli/security/cancel-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func cancelProposal(c *cli.Context) error { +func cancelProposal(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -52,12 +51,12 @@ func cancelProposal(c *cli.Context) error { // Get selected proposal var selectedProposal dao.ProposalDetails - if c.String("proposal") != "" { + if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -91,13 +90,13 @@ func cancelProposal(c *cli.Context) error { return err } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canResponse.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to cancel proposal %d?", selectedProposal.ID)) { + if !(yes || prompt.Confirm("Are you sure you want to cancel proposal %d?", selectedProposal.ID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/security/commands.go b/rocketpool-cli/security/commands.go index e9d6064b9..b5e2ef418 100644 --- a/rocketpool-cli/security/commands.go +++ b/rocketpool-cli/security/commands.go @@ -35,7 +35,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -53,7 +53,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getMembers(c) + return getMembers() }, }, @@ -88,7 +88,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeLeave(c) + return proposeLeave(c.Bool("yes")) }, }, @@ -129,7 +129,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingAuctionIsCreateLotEnabled(c, value) + return proposeSettingAuctionIsCreateLotEnabled(value, c.Bool("yes")) }, }, @@ -157,7 +157,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingAuctionIsBidOnLotEnabled(c, value) + return proposeSettingAuctionIsBidOnLotEnabled(value, c.Bool("yes")) }, }, @@ -193,7 +193,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositIsDepositingEnabled(c, value) + return proposeSettingDepositIsDepositingEnabled(value, c.Bool("yes")) }, }, @@ -221,7 +221,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingDepositAreDepositAssignmentsEnabled(c, value) + return proposeSettingDepositAreDepositAssignmentsEnabled(value, c.Bool("yes")) }, }, @@ -257,7 +257,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolIsSubmitWithdrawableEnabled(c, value) + return proposeSettingMinipoolIsSubmitWithdrawableEnabled(value, c.Bool("yes")) }, }, @@ -285,7 +285,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingMinipoolIsBondReductionEnabled(c, value) + return proposeSettingMinipoolIsBondReductionEnabled(value, c.Bool("yes")) }, }, @@ -321,7 +321,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkIsSubmitBalancesEnabled(c, value) + return proposeSettingNetworkIsSubmitBalancesEnabled(value, c.Bool("yes")) }, }, @@ -349,7 +349,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkIsSubmitPricesEnabled(c, value) + return proposeSettingNetworkIsSubmitPricesEnabled(value, c.Bool("yes")) }, }, @@ -377,7 +377,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNetworkIsSubmitRewardsEnabled(c, value) + return proposeSettingNetworkIsSubmitRewardsEnabled(value, c.Bool("yes")) }, }, @@ -403,13 +403,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 1); err != nil { return err } - value, err := cliutils.ValidateFloat(c, "value", c.Args().Get(0), true) + value, err := cliutils.ValidateFloat(c.Bool("raw"), "value", c.Args().Get(0), true, c.Bool("yes")) if err != nil { return err } // Run - return proposeSettingNodeComissionShareSecurityCouncilAdder(c, value) + return proposeSettingNodeComissionShareSecurityCouncilAdder(value, c.Bool("yes")) }, }, @@ -445,7 +445,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeIsRegistrationEnabled(c, value) + return proposeSettingNodeIsRegistrationEnabled(value, c.Bool("yes")) }, }, @@ -473,7 +473,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeIsSmoothingPoolRegistrationEnabled(c, value) + return proposeSettingNodeIsSmoothingPoolRegistrationEnabled(value, c.Bool("yes")) }, }, @@ -501,7 +501,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeIsDepositingEnabled(c, value) + return proposeSettingNodeIsDepositingEnabled(value, c.Bool("yes")) }, }, @@ -529,7 +529,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return proposeSettingNodeAreVacantMinipoolsEnabled(c, value) + return proposeSettingNodeAreVacantMinipoolsEnabled(value, c.Bool("yes")) }, }, @@ -566,7 +566,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getProposals(c, c.String("states")) + return getProposals(c.String("states")) }, }, @@ -589,7 +589,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getProposal(c, id) + return getProposal(id) }, }, @@ -620,7 +620,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return cancelProposal(c) + return cancelProposal(c.String("proposal"), c.Bool("yes")) }, }, @@ -664,7 +664,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return voteOnProposal(c) + return voteOnProposal(c.String("proposal"), c.String("support"), c.Bool("yes")) }, }, @@ -695,7 +695,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return executeProposal(c) + return executeProposal(c.String("proposal"), c.Bool("yes")) }, }, @@ -721,7 +721,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return join(c) + return join(c.Bool("yes")) }, }, @@ -745,7 +745,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return leave(c) + return leave(c.Bool("yes")) }, }, diff --git a/rocketpool-cli/security/execute-proposal.go b/rocketpool-cli/security/execute-proposal.go index ab5765ef7..6ac824116 100644 --- a/rocketpool-cli/security/execute-proposal.go +++ b/rocketpool-cli/security/execute-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" rocketpoolapi "github.com/rocket-pool/smartnode/bindings/rocketpool" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func executeProposal(c *cli.Context) error { +func executeProposal(proposal string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -46,17 +45,17 @@ func executeProposal(c *cli.Context) error { // Get selected proposal var selectedProposals []dao.ProposalDetails - if c.String("proposal") == "all" { + if proposal == "all" { // Select all proposals selectedProposals = executableProposals - } else if c.String("proposal") != "" { + } else if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -110,13 +109,13 @@ func executeProposal(c *cli.Context) error { gasInfo.SafeGasLimit = totalSafeGas // Assign max fees - err = gas.AssignMaxFeeAndLimit(gasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(gasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { + if !(yes || prompt.Confirm("Are you sure you want to execute %d proposals?", len(selectedProposals))) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/security/join.go b/rocketpool-cli/security/join.go index 4971d30af..07a677dcb 100644 --- a/rocketpool-cli/security/join.go +++ b/rocketpool-cli/security/join.go @@ -3,18 +3,16 @@ package security import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func join(c *cli.Context) error { +func join(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -37,13 +35,13 @@ func join(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canJoin.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canJoin.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to join the security council?")) { + if !(yes || prompt.Confirm("Are you sure you want to join the security council?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/security/leave.go b/rocketpool-cli/security/leave.go index 5b032f6ff..5ef5f15e2 100644 --- a/rocketpool-cli/security/leave.go +++ b/rocketpool-cli/security/leave.go @@ -3,18 +3,16 @@ package security import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func leave(c *cli.Context) error { +func leave(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -34,13 +32,13 @@ func leave(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canLeave.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canLeave.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to leave the security council? This action cannot be undone!")) { + if !(yes || prompt.Confirm("Are you sure you want to leave the security council? This action cannot be undone!")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/security/members.go b/rocketpool-cli/security/members.go index 39f9af67f..4f5498194 100644 --- a/rocketpool-cli/security/members.go +++ b/rocketpool-cli/security/members.go @@ -3,16 +3,14 @@ package security import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" ) -func getMembers(c *cli.Context) error { +func getMembers() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/security/proposals.go b/rocketpool-cli/security/proposals.go index a084356ae..a3590163f 100644 --- a/rocketpool-cli/security/proposals.go +++ b/rocketpool-cli/security/proposals.go @@ -9,7 +9,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" @@ -26,10 +25,10 @@ func filterProposalState(state string, stateFilter string) bool { return !slices.Contains(filterStates, state) } -func getProposals(c *cli.Context, stateFilter string) error { +func getProposals(stateFilter string) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -103,9 +102,9 @@ func getProposals(c *cli.Context, stateFilter string) error { } -func getProposal(c *cli.Context, id uint64) error { +func getProposal(id uint64) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/security/propose-leave.go b/rocketpool-cli/security/propose-leave.go index a27057aab..bf8889b9d 100644 --- a/rocketpool-cli/security/propose-leave.go +++ b/rocketpool-cli/security/propose-leave.go @@ -3,18 +3,16 @@ package security import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func proposeLeave(c *cli.Context) error { +func proposeLeave(yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -33,13 +31,13 @@ func proposeLeave(c *cli.Context) error { return nil } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/security/propose-settings.go b/rocketpool-cli/security/propose-settings.go index 4ef37ec3e..558efd6ee 100644 --- a/rocketpool-cli/security/propose-settings.go +++ b/rocketpool-cli/security/propose-settings.go @@ -5,7 +5,6 @@ import ( "math/big" "github.com/rocket-pool/smartnode/bindings/settings/protocol" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -13,80 +12,80 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func proposeSettingAuctionIsCreateLotEnabled(c *cli.Context, value bool) error { +func proposeSettingAuctionIsCreateLotEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.CreateLotEnabledSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.CreateLotEnabledSettingPath, trueValue, yes) } -func proposeSettingAuctionIsBidOnLotEnabled(c *cli.Context, value bool) error { +func proposeSettingAuctionIsBidOnLotEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.AuctionSettingsContractName, protocol.BidOnLotEnabledSettingPath, trueValue) + return proposeSetting(protocol.AuctionSettingsContractName, protocol.BidOnLotEnabledSettingPath, trueValue, yes) } -func proposeSettingDepositIsDepositingEnabled(c *cli.Context, value bool) error { +func proposeSettingDepositIsDepositingEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.DepositEnabledSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.DepositEnabledSettingPath, trueValue, yes) } -func proposeSettingDepositAreDepositAssignmentsEnabled(c *cli.Context, value bool) error { +func proposeSettingDepositAreDepositAssignmentsEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.DepositSettingsContractName, protocol.AssignDepositsEnabledSettingPath, trueValue) + return proposeSetting(protocol.DepositSettingsContractName, protocol.AssignDepositsEnabledSettingPath, trueValue, yes) } -func proposeSettingMinipoolIsSubmitWithdrawableEnabled(c *cli.Context, value bool) error { +func proposeSettingMinipoolIsSubmitWithdrawableEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.MinipoolSubmitWithdrawableEnabledSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.MinipoolSubmitWithdrawableEnabledSettingPath, trueValue, yes) } -func proposeSettingMinipoolIsBondReductionEnabled(c *cli.Context, value bool) error { +func proposeSettingMinipoolIsBondReductionEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.MinipoolSettingsContractName, protocol.BondReductionEnabledSettingPath, trueValue) + return proposeSetting(protocol.MinipoolSettingsContractName, protocol.BondReductionEnabledSettingPath, trueValue, yes) } -func proposeSettingNetworkIsSubmitBalancesEnabled(c *cli.Context, value bool) error { +func proposeSettingNetworkIsSubmitBalancesEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitBalancesEnabledSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitBalancesEnabledSettingPath, trueValue, yes) } -func proposeSettingNetworkIsSubmitPricesEnabled(c *cli.Context, value bool) error { +func proposeSettingNetworkIsSubmitPricesEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitPricesEnabledSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitPricesEnabledSettingPath, trueValue, yes) } -func proposeSettingNetworkIsSubmitRewardsEnabled(c *cli.Context, value bool) error { +func proposeSettingNetworkIsSubmitRewardsEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.SubmitRewardsEnabledSettingPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.SubmitRewardsEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeIsRegistrationEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeIsRegistrationEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.NodeRegistrationEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.NodeRegistrationEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeIsSmoothingPoolRegistrationEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeIsSmoothingPoolRegistrationEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.SmoothingPoolRegistrationEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.SmoothingPoolRegistrationEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeIsDepositingEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeIsDepositingEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.NodeDepositEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.NodeDepositEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeAreVacantMinipoolsEnabled(c *cli.Context, value bool) error { +func proposeSettingNodeAreVacantMinipoolsEnabled(value bool, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NodeSettingsContractName, protocol.VacantMinipoolsEnabledSettingPath, trueValue) + return proposeSetting(protocol.NodeSettingsContractName, protocol.VacantMinipoolsEnabledSettingPath, trueValue, yes) } -func proposeSettingNodeComissionShareSecurityCouncilAdder(c *cli.Context, value *big.Int) error { +func proposeSettingNodeComissionShareSecurityCouncilAdder(value *big.Int, yes bool) error { trueValue := fmt.Sprint(value) - return proposeSetting(c, protocol.NetworkSettingsContractName, protocol.NetworkNodeCommissionShareSecurityCouncilAdderPath, trueValue) + return proposeSetting(protocol.NetworkSettingsContractName, protocol.NetworkNodeCommissionShareSecurityCouncilAdderPath, trueValue, yes) } // Master general proposal function -func proposeSetting(c *cli.Context, contract string, setting string, value string) error { +func proposeSetting(contract string, setting string, value string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -99,13 +98,13 @@ func proposeSetting(c *cli.Context, contract string, setting string, value strin } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canPropose.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to submit this proposal?")) { + if !(yes || prompt.Confirm("Are you sure you want to submit this proposal?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/security/status.go b/rocketpool-cli/security/status.go index ecff57aa0..7892d2dee 100644 --- a/rocketpool-cli/security/status.go +++ b/rocketpool-cli/security/status.go @@ -3,15 +3,13 @@ package security import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/security/vote-proposal.go b/rocketpool-cli/security/vote-proposal.go index 56f2e6674..b42eac066 100644 --- a/rocketpool-cli/security/vote-proposal.go +++ b/rocketpool-cli/security/vote-proposal.go @@ -7,7 +7,6 @@ import ( "github.com/rocket-pool/smartnode/bindings/dao" "github.com/rocket-pool/smartnode/bindings/types" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/gas" "github.com/rocket-pool/smartnode/shared/services/rocketpool" @@ -15,10 +14,10 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func voteOnProposal(c *cli.Context) error { +func voteOnProposal(proposal string, supportFlag string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -52,12 +51,12 @@ func voteOnProposal(c *cli.Context) error { // Get selected proposal var selectedProposal dao.ProposalDetails - if c.String("proposal") != "" { + if proposal != "" { // Get selected proposal ID - selectedId, err := strconv.ParseUint(c.String("proposal"), 10, 64) + selectedId, err := strconv.ParseUint(proposal, 10, 64) if err != nil { - return fmt.Errorf("Invalid proposal ID '%s': %w", c.String("proposal"), err) + return fmt.Errorf("Invalid proposal ID '%s': %w", proposal, err) } // Get matching proposal @@ -104,11 +103,11 @@ func voteOnProposal(c *cli.Context) error { // Get support status var support bool var supportLabel string - if c.String("support") != "" { + if supportFlag != "" { // Parse support status var err error - support, err = cliutils.ValidateBool("support", c.String("support")) + support, err = cliutils.ValidateBool("support", supportFlag) if err != nil { return err } @@ -139,13 +138,13 @@ func voteOnProposal(c *cli.Context) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(canVote.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(canVote.GasInfo, rp, yes) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to vote %s proposal %d? Your vote cannot be changed later.", supportLabel, selectedProposal.ID)) { + if !(yes || prompt.Confirm("Are you sure you want to vote %s proposal %d? Your vote cannot be changed later.", supportLabel, selectedProposal.ID)) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/service/commands.go b/rocketpool-cli/service/commands.go index 5db8034ec..7377b64dc 100644 --- a/rocketpool-cli/service/commands.go +++ b/rocketpool-cli/service/commands.go @@ -5,6 +5,7 @@ import ( "os" "strings" + "github.com/mitchellh/go-homedir" "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared" @@ -14,6 +15,11 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/color" ) +// Get the compose file paths for a CLI context +func getComposeFiles(c *cli.Context) []string { + return c.Parent().StringSlice("compose-file") +} + // Creates CLI argument flags from the parameters of the configuration struct func createFlagsFromConfigParams(sectionName string, params []*cfgtypes.Parameter, configFlags []cli.Flag, network cfgtypes.Network) []cli.Flag { for _, param := range params { @@ -148,7 +154,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return installService(c) + return installService(c.Bool("yes"), c.Bool("verbose"), c.Bool("no-deps"), c.String("path")) }, }, @@ -165,9 +171,34 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { if err := cliutils.ValidateArgCount(c, 0); err != nil { return err } + configPath := c.GlobalString("config-path") + path, err := homedir.Expand(configPath) + if err != nil { + return fmt.Errorf("error expanding config path [%s]: %w", configPath, err) + } + + _, err = os.Stat(path) + if os.IsNotExist(err) { + color.YellowPrintf("Your configured Rocket Pool directory of [%s] does not exist.\n", path) + color.YellowPrintln("Please follow the instructions at https://docs.rocketpool.net/node-staking/docker to install the Smart Node.") + } + if err != nil { + return fmt.Errorf("error checking if config path exists: %w", err) + } + + isHeadless := c.NumFlags() > 0 + + if isHeadless { + return configureServiceHeadless(c) + } // Run command - return configureService(c) + return configureService( + c.GlobalString("config-path"), + /*isNative=*/ c.GlobalIsSet("daemon-path"), + c.Bool("yes"), + getComposeFiles(c), + ) }, }, @@ -185,7 +216,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return serviceStatus(c) + return serviceStatus(getComposeFiles(c)) }, }, @@ -213,39 +244,20 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return startService(c, false) + return startService(startServiceParams{ + yes: c.Bool("yes"), + ignoreSlashTimer: c.Bool("ignore-slash-timer"), + ignoreConfigSuggestion: false, + composeFiles: getComposeFiles(c), + }) }, }, - { - Name: "pause", - Aliases: []string{"p"}, - Usage: "Pause the Rocket Pool service", - UsageText: "rocketpool service pause [options]", - Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "yes, y", - Usage: "Automatically confirm service suspension", - }, - }, - Action: func(c *cli.Context) error { - - // Validate args - if err := cliutils.ValidateArgCount(c, 0); err != nil { - return err - } - - // Run command - _, err := pauseService(c) - return err - - }, - }, { Name: "stop", - Aliases: []string{"o"}, - Usage: "Pause the Rocket Pool service (alias of 'rocketpool service pause')", + Aliases: []string{"pause", "p", "o"}, + Usage: "Pause the Rocket Pool service", UsageText: "rocketpool service stop [options]", Flags: []cli.Flag{ cli.BoolFlag{ @@ -261,7 +273,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - _, err := pauseService(c) + _, err := pauseService(c.Bool("yes"), getComposeFiles(c)) return err }, @@ -289,7 +301,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return resetDocker(c) + return resetDocker(c.Bool("yes"), c.Bool("all"), getComposeFiles(c)) }, }, @@ -312,7 +324,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return pruneDocker(c) + return pruneDocker(c.Bool("all"), getComposeFiles(c)) }, }, @@ -331,7 +343,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { Action: func(c *cli.Context) error { // Run command - return serviceLogs(c, c.Args()...) + return serviceLogs(c.String("tail"), getComposeFiles(c), c.Args()...) }, }, @@ -348,7 +360,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return serviceCompose(c) + return serviceCompose(getComposeFiles(c)) }, }, @@ -366,7 +378,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return serviceVersion(c) + return serviceVersion() }, }, @@ -384,7 +396,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return pruneExecutionClient(c) + return pruneExecutionClient(c.Bool("yes")) }, }, @@ -417,7 +429,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return installUpdateTracker(c) + return installUpdateTracker(c.Bool("yes"), c.Bool("verbose")) }, }, @@ -434,7 +446,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return getConfigYaml(c) + return getConfigYaml() }, }, @@ -451,7 +463,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return resyncEth1(c) + return resyncEth1(c.Bool("yes"), getComposeFiles(c)) }, }, @@ -468,7 +480,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return resyncEth2(c) + return resyncEth2(c.Bool("yes"), getComposeFiles(c)) }, }, @@ -492,7 +504,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run command - return terminateService(c) + return terminateService(c.Bool("yes"), getComposeFiles(c), c.GlobalString("config-path")) }, }, diff --git a/rocketpool-cli/service/service.go b/rocketpool-cli/service/service.go index 7876c0519..b080d185a 100644 --- a/rocketpool-cli/service/service.go +++ b/rocketpool-cli/service/service.go @@ -49,11 +49,11 @@ const ( ) // Install the Rocket Pool service -func installService(c *cli.Context) error { +func installService(yes, verbose, noDeps bool, path string) error { dataPath := "" // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm( + if !(yes || prompt.Confirm( "%s", fmt.Sprintf("The Rocket Pool %s service will be installed.\n\n", shared.RocketPoolVersion())+ color.Green("If you're upgrading, your existing configuration will be backed up and preserved.\nAll of your previous settings will be migrated automatically.\n")+ @@ -64,7 +64,7 @@ func installService(c *cli.Context) error { } // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Attempt to load the config to see if any settings need to be passed along to the install script @@ -81,7 +81,7 @@ func installService(c *cli.Context) error { } // Install service - err = rp.InstallService(c.Bool("verbose"), c.Bool("no-deps"), c.String("path"), dataPath) + err = rp.InstallService(verbose, noDeps, path, dataPath) if err != nil { return err } @@ -90,7 +90,7 @@ func installService(c *cli.Context) error { fmt.Println("") fmt.Println("The Rocket Pool service was successfully installed!") - printPatchNotes(c) + printPatchNotes() // Reload the config after installation _, isNew, err = rp.LoadConfig() @@ -115,7 +115,7 @@ func installService(c *cli.Context) error { } // Print the latest patch notes for this release -func printPatchNotes(c *cli.Context) { +func printPatchNotes() { fmt.Print(shared.Logo()) fmt.Println() @@ -130,10 +130,10 @@ func printPatchNotes(c *cli.Context) { } // Install the Rocket Pool update tracker for the metrics dashboard -func installUpdateTracker(c *cli.Context) error { +func installUpdateTracker(yes, verbose bool) error { // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm( + if !(yes || prompt.Confirm( "This will add the ability to display any available Operating System updates or new Rocket Pool versions on the metrics dashboard. "+ "Are you sure you want to install the update tracker?")) { fmt.Println("Cancelled.") @@ -141,11 +141,11 @@ func installUpdateTracker(c *cli.Context) error { } // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Install service - err := rp.InstallUpdateTracker(c.Bool("verbose")) + err := rp.InstallUpdateTracker(verbose) if err != nil { return err } @@ -162,10 +162,10 @@ func installUpdateTracker(c *cli.Context) error { } // View the Rocket Pool service status -func serviceStatus(c *cli.Context) error { +func serviceStatus(composeFiles []string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -181,41 +181,26 @@ func serviceStatus(c *cli.Context) error { } // Print service status - return rp.PrintServiceStatus(getComposeFiles(c)) + return rp.PrintServiceStatus(composeFiles) } -// Configure the service -func configureService(c *cli.Context) error { - - // Make sure the config directory exists first - configPath := c.GlobalString("config-path") - path, err := homedir.Expand(configPath) - if err != nil { - return fmt.Errorf("error expanding config path [%s]: %w", configPath, err) - } - _, err = os.Stat(path) - if os.IsNotExist(err) { - color.YellowPrintf("Your configured Rocket Pool directory of [%s] does not exist.\n", path) - color.YellowPrintln("Please follow the instructions at https://docs.rocketpool.net/node-staking/docker to install the Smart Node.") - return nil - } +func configureServicePrecheck() (isNew bool, cfg, oldCfg *config.RocketPoolConfig, err error) { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Load the config, checking to see if it's new (hasn't been installed before) - var oldCfg *config.RocketPoolConfig - cfg, isNew, err := rp.LoadConfig() + cfg, isNew, err = rp.LoadConfig() if err != nil { - return fmt.Errorf("error loading user settings: %w", err) + return false, nil, nil, fmt.Errorf("error loading user settings: %w", err) } // Check if this is a new install isUpdate, err := rp.IsFirstRun() if err != nil { - return fmt.Errorf("error checking for first-run status: %w", err) + return false, nil, nil, fmt.Errorf("error checking for first-run status: %w", err) } // For upgrades, move the config to the old one and create a new upgraded copy @@ -224,23 +209,61 @@ func configureService(c *cli.Context) error { cfg = cfg.CreateCopy() err = cfg.UpdateDefaults() if err != nil { - return fmt.Errorf("error upgrading configuration with the latest parameters: %w", err) + return false, nil, nil, fmt.Errorf("error upgrading configuration with the latest parameters: %w", err) } } cfg.ConfirmUpdateSuggestedSettings() - // Save the config and exit in headless mode - if c.NumFlags() > 0 { - err := configureHeadless(c, cfg) + return isNew, cfg, oldCfg, nil +} + +// This function is the exception to the rule- +// we pass cli.Context here and here only because +// otherwise it's very difficult to set config values by CLI flag. +func configureServiceHeadless(c *cli.Context) error { + // Get RP client + rp := rocketpool.NewClient() + defer rp.Close() + + _, cfg, _, err := configureServicePrecheck() + if err != nil { + return err + } + + // Root params + for _, param := range cfg.GetParameters() { + err := updateConfigParamFromCliArg(c, "", param, cfg) if err != nil { return fmt.Errorf("error updating config from provided arguments: %w", err) } - return rp.SaveConfig(cfg) } - // Check for native mode - isNative := c.GlobalIsSet("daemon-path") + // Subconfigs + for sectionName, subconfig := range cfg.GetSubconfigs() { + for _, param := range subconfig.GetParameters() { + err := updateConfigParamFromCliArg(c, sectionName, param, cfg) + if err != nil { + return fmt.Errorf("error updating config from provided arguments: %w", err) + } + } + } + + return nil +} + +// Configure the service +func configureService(configPath string, isNative, yes bool, composeFiles []string) error { + // Get RP client + rp := rocketpool.NewClient() + defer rp.Close() + + isNew, cfg, oldCfg, err := configureServicePrecheck() + if err != nil { + return err + } + + isUpdate := !isNew && oldCfg != nil app := tview.NewApplication() md := cliconfig.NewMainDisplay(app, oldCfg, cfg, isNew, isUpdate, isNative) @@ -286,7 +309,7 @@ func configureService(c *cli.Context) error { return nil } - err = changeNetworks(c, rp, fmt.Sprintf("%s%s", prefix, ApiContainerSuffix)) + err = changeNetworks(rp, fmt.Sprintf("%s%s", prefix, ApiContainerSuffix), composeFiles) if err != nil { color.RedPrintln(err.Error()) fmt.Println("The Smart Node could not automatically change networks for you, so you will have to run the steps manually. Please follow the steps laid out in the Node Operator's guide (https://docs.rocketpool.net/node-staking/mainnet.html).") @@ -300,7 +323,11 @@ func configureService(c *cli.Context) error { fmt.Println("Please run `rocketpool service start` when you are ready to launch.") return nil } - return startService(c, true) + return startService(startServiceParams{ + yes: yes, + ignoreConfigSuggestion: true, + composeFiles: composeFiles, + }) } // Query for service start if this is old and there are containers to change @@ -316,7 +343,7 @@ func configureService(c *cli.Context) error { // Let's reduce potential downtime by pulling the new containers before restarting fmt.Println("Pulling potential new container images...") - err = rp.PullComposeImages(getComposeFiles(c)) + err = rp.PullComposeImages(composeFiles) if err != nil { fmt.Fprintf(os.Stderr, "Warning: couldn't pull new images for updated containers: %s\n", err.Error()) } @@ -331,7 +358,11 @@ func configureService(c *cli.Context) error { fmt.Println() fmt.Println("Applying changes and restarting containers...") - return startService(c, true) + return startService(startServiceParams{ + yes: yes, + ignoreConfigSuggestion: true, + composeFiles: composeFiles, + }) } } else { fmt.Println("Your changes have not been saved. Your Smart Node configuration is the same as it was before.") @@ -341,31 +372,6 @@ func configureService(c *cli.Context) error { return err } -// Updates a configuration from the provided CLI arguments headlessly -func configureHeadless(c *cli.Context, cfg *config.RocketPoolConfig) error { - - // Root params - for _, param := range cfg.GetParameters() { - err := updateConfigParamFromCliArg(c, "", param, cfg) - if err != nil { - return err - } - } - - // Subconfigs - for sectionName, subconfig := range cfg.GetSubconfigs() { - for _, param := range subconfig.GetParameters() { - err := updateConfigParamFromCliArg(c, sectionName, param, cfg) - if err != nil { - return err - } - } - } - - return nil - -} - // Updates a config parameter from a CLI flag func updateConfigParamFromCliArg(c *cli.Context, sectionName string, param *cfgtypes.Parameter, cfg *config.RocketPoolConfig) error { @@ -415,11 +421,11 @@ func updateConfigParamFromCliArg(c *cli.Context, sectionName string, param *cfgt } // Handle a network change by terminating the service, deleting everything, and starting over -func changeNetworks(c *cli.Context, rp *rocketpool.Client, apiContainerName string) error { +func changeNetworks(rp *rocketpool.Client, apiContainerName string, composeFiles []string) error { // Stop all of the containers fmt.Println("Stopping containers... ") - err := rp.PauseService(getComposeFiles(c)) + err := rp.PauseService(composeFiles) if err != nil { return fmt.Errorf("error stopping service: %w", err) } @@ -454,7 +460,7 @@ func changeNetworks(c *cli.Context, rp *rocketpool.Client, apiContainerName stri // Terminate the current setup fmt.Println("Removing old installation... ") - err = rp.StopService(getComposeFiles(c)) + err = rp.StopService(composeFiles) if err != nil { return fmt.Errorf("error terminating old installation: %w", err) } @@ -469,7 +475,7 @@ func changeNetworks(c *cli.Context, rp *rocketpool.Client, apiContainerName stri // Start the service fmt.Println("Starting Rocket Pool... ") - err = rp.StartService(getComposeFiles(c)) + err = rp.StartService(composeFiles) if err != nil { return fmt.Errorf("error starting service: %w", err) } @@ -479,11 +485,19 @@ func changeNetworks(c *cli.Context, rp *rocketpool.Client, apiContainerName stri } +type startServiceParams struct { + yes bool // Whether to automatically confirm prompts + // N.B.: This should ALYWAYS be false unless --ignore-slash-timer is set! + ignoreSlashTimer bool // Whether to ignore the slash timer + ignoreConfigSuggestion bool // Whether to skip suggesting the user run config first + composeFiles []string // The compose files to start the service with +} + // Start the Rocket Pool service -func startService(c *cli.Context, ignoreConfigSuggestion bool) error { +func startService(params startServiceParams) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Update the Prometheus template with the assigned ports @@ -510,8 +524,8 @@ func startService(c *cli.Context, ignoreConfigSuggestion bool) error { if err != nil { return fmt.Errorf("error checking for first-run status: %w", err) } - if isUpdate && !ignoreConfigSuggestion { - if c.Bool("yes") || prompt.Confirm("Smart Node upgrade detected - starting will overwrite certain settings with the latest defaults (such as container versions).\nYou may want to run `service config` first to see what's changed.\n\nWould you like to continue starting the service?") { + if isUpdate && !params.ignoreConfigSuggestion { + if params.yes || prompt.Confirm("Smart Node upgrade detected - starting will overwrite certain settings with the latest defaults (such as container versions).\nYou may want to run `service config` first to see what's changed.\n\nWould you like to continue starting the service?") { err = cfg.UpdateDefaults() if err != nil { return fmt.Errorf("error upgrading configuration with the latest parameters: %w", err) @@ -554,7 +568,7 @@ func startService(c *cli.Context, ignoreConfigSuggestion bool) error { return nil } - if !c.Bool("ignore-slash-timer") { + if !params.ignoreSlashTimer { // Do the client swap check err := checkForValidatorChange(rp, cfg) if err != nil { @@ -589,7 +603,7 @@ func startService(c *cli.Context, ignoreConfigSuggestion bool) error { fmt.Println() // Start service - err = rp.StartService(getComposeFiles(c)) + err = rp.StartService(params.composeFiles) if err != nil { return err } @@ -756,10 +770,10 @@ func getDockerImageName(imageString string) (string, error) { } // Prepares the execution client for pruning -func pruneExecutionClient(c *cli.Context) error { +func pruneExecutionClient(yes bool) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -811,7 +825,7 @@ func pruneExecutionClient(c *cli.Context) error { } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to prune your main execution client?")) { + if !(yes || prompt.Confirm("Are you sure you want to prune your main execution client?")) { fmt.Println("Cancelled.") return nil } @@ -905,14 +919,14 @@ func pruneExecutionClient(c *cli.Context) error { } // Stops Smart Node stack containers, prunes docker, and restarts the Smart Node stack. -func resetDocker(c *cli.Context) error { +func resetDocker(yes, all bool, composeFiles []string) error { fmt.Println("Once cleanup is complete, Rocket Pool will restart automatically.") fmt.Println() // Stop... // NOTE: pauseService prompts for confirmation, so we don't need to do it here - confirmed, err := pauseService(c) + confirmed, err := pauseService(yes, composeFiles) if err != nil { return err } @@ -923,7 +937,7 @@ func resetDocker(c *cli.Context) error { } // Prune images... - err = pruneDocker(c) + err = pruneDocker(all, composeFiles) if err != nil { return fmt.Errorf("error pruning Docker: %s", err) } @@ -931,25 +945,28 @@ func resetDocker(c *cli.Context) error { // Restart... // NOTE: startService does some other sanity checks and messages that we leverage here: fmt.Println("Restarting Rocket Pool...") - err = startService(c, true) + err = startService(startServiceParams{ + yes: yes, + ignoreConfigSuggestion: true, + composeFiles: composeFiles, + }) if err != nil { return fmt.Errorf("error starting Rocket Pool: %s", err) } return nil } -func pruneDocker(c *cli.Context) error { +func pruneDocker(deleteAllImages bool, composeFiles []string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // NOTE: we deliberately avoid using `docker system prune -a` and delete all // images manually so that we can preserve the current smartnode-stack // images, _unless_ the user specified --all option - deleteAllImages := c.Bool("all") if !deleteAllImages { - ourImages, err := rp.GetComposeImages(getComposeFiles(c)) + ourImages, err := rp.GetComposeImages(composeFiles) if err != nil { return fmt.Errorf("error getting compose images: %w", err) } @@ -992,10 +1009,10 @@ func pruneDocker(c *cli.Context) error { } // Pause the Rocket Pool service. Returns whether the action proceeded (was confirmed by user and no error occurred before starting it) -func pauseService(c *cli.Context) (bool, error) { +func pauseService(yes bool, composeFiles []string) (bool, error) { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -1018,37 +1035,37 @@ func pauseService(c *cli.Context) (bool, error) { fmt.Println() // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to pause the Rocket Pool service? Any staking minipools and megapool validators will be penalized!")) { + if !(yes || prompt.Confirm("Are you sure you want to pause the Rocket Pool service? Any staking minipools and megapool validators will be penalized!")) { fmt.Println("Cancelled.") return false, nil } // Pause service - err = rp.PauseService(getComposeFiles(c)) + err = rp.PauseService(composeFiles) return true, err } // Terminate the Rocket Pool service -func terminateService(c *cli.Context) error { +func terminateService(yes bool, composeFiles []string, configPath string) error { // Prompt for confirmation - if !(c.Bool("yes") || prompt.ConfirmRed("WARNING: Are you sure you want to terminate the Rocket Pool service? Any staking minipools will be penalized, your ETH1 and ETH2 chain databases will be deleted, you will lose ALL of your sync progress, and you will lose your Prometheus metrics database!\nAfter doing this, you will have to **reinstall** the Smart Node uses `rocketpool service install -d` in order to use it again.")) { + if !(yes || prompt.ConfirmRed("WARNING: Are you sure you want to terminate the Rocket Pool service? Any staking minipools will be penalized, your ETH1 and ETH2 chain databases will be deleted, you will lose ALL of your sync progress, and you will lose your Prometheus metrics database!\nAfter doing this, you will have to **reinstall** the Smart Node uses `rocketpool service install -d` in order to use it again.")) { fmt.Println("Cancelled.") return nil } // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Stop service - return rp.TerminateService(getComposeFiles(c), c.GlobalString("config-path")) + return rp.TerminateService(composeFiles, configPath) } // View the Rocket Pool service logs -func serviceLogs(c *cli.Context, aliasedNames ...string) error { +func serviceLogs(tail string, composeFiles []string, aliasedNames ...string) error { // Handle name aliasing serviceNames := []string{} @@ -1066,31 +1083,31 @@ func serviceLogs(c *cli.Context, aliasedNames ...string) error { } // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Print service logs - return rp.PrintServiceLogs(getComposeFiles(c), c.String("tail"), serviceNames...) + return rp.PrintServiceLogs(composeFiles, tail, serviceNames...) } // View the Rocket Pool service compose config -func serviceCompose(c *cli.Context) error { +func serviceCompose(composeFiles []string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Print service compose config - return rp.PrintServiceCompose(getComposeFiles(c)) + return rp.PrintServiceCompose(composeFiles) } // View the Rocket Pool service version information -func serviceVersion(c *cli.Context) error { +func serviceVersion() error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -1113,7 +1130,7 @@ func serviceVersion(c *cli.Context) error { // Handle native mode if cfg.IsNativeMode { - fmt.Printf("Rocket Pool client version: %s\n", c.App.Version) + fmt.Printf("Rocket Pool client version: %s\n", shared.RocketPoolVersion()) fmt.Printf("Rocket Pool service version: %s\n", serviceVersion) fmt.Println("Configured for Native Mode") return nil @@ -1213,7 +1230,7 @@ func serviceVersion(c *cli.Context) error { } // Print version info - fmt.Printf("Rocket Pool client version: %s\n", c.App.Version) + fmt.Printf("Rocket Pool client version: %s\n", shared.RocketPoolVersion()) fmt.Printf("Rocket Pool service version: %s\n", serviceVersion) fmt.Printf("Selected Eth 1.0 client: %s\n", eth1ClientString) fmt.Printf("Selected Eth 2.0 client: %s\n", eth2ClientString) @@ -1223,16 +1240,11 @@ func serviceVersion(c *cli.Context) error { } -// Get the compose file paths for a CLI context -func getComposeFiles(c *cli.Context) []string { - return c.Parent().StringSlice("compose-file") -} - // Destroy and resync the eth1 client from scratch -func resyncEth1(c *cli.Context) error { +func resyncEth1(yes bool, composeFiles []string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -1255,7 +1267,7 @@ func resyncEth1(c *cli.Context) error { } // Prompt for confirmation - if !(c.Bool("yes") || prompt.ConfirmRed("Are you SURE you want to delete and resync your main ETH1 client from scratch? This cannot be undone!")) { + if !(yes || prompt.ConfirmRed("Are you SURE you want to delete and resync your main ETH1 client from scratch? This cannot be undone!")) { fmt.Println("Cancelled.") return nil } @@ -1299,7 +1311,11 @@ func resyncEth1(c *cli.Context) error { // Restart Rocket Pool fmt.Printf("Rebuilding %s and restarting Rocket Pool...\n", executionContainerName) - err = startService(c, true) + err = startService(startServiceParams{ + yes: yes, + ignoreConfigSuggestion: true, + composeFiles: composeFiles, + }) if err != nil { return fmt.Errorf("Error starting Rocket Pool: %s", err) } @@ -1311,10 +1327,10 @@ func resyncEth1(c *cli.Context) error { } // Destroy and resync the eth2 client from scratch -func resyncEth2(c *cli.Context) error { +func resyncEth2(yes bool, composeFiles []string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the merged config @@ -1378,7 +1394,7 @@ func resyncEth2(c *cli.Context) error { } // Prompt for confirmation - if !(c.Bool("yes") || prompt.ConfirmRed("Are you SURE you want to delete and resync your ETH2 client from scratch? This cannot be undone!")) { + if !(yes || prompt.ConfirmRed("Are you SURE you want to delete and resync your ETH2 client from scratch? This cannot be undone!")) { fmt.Println("Cancelled.") return nil } @@ -1445,7 +1461,11 @@ func resyncEth2(c *cli.Context) error { // Restart Rocket Pool fmt.Printf("Rebuilding %s and restarting Rocket Pool...\n", beaconContainerName) - err = startService(c, true) + err = startService(startServiceParams{ + yes: yes, + ignoreConfigSuggestion: true, + composeFiles: composeFiles, + }) if err != nil { return fmt.Errorf("Error starting Rocket Pool: %s", err) } @@ -1457,7 +1477,7 @@ func resyncEth2(c *cli.Context) error { } // Generate a YAML file that shows the current configuration schema, including all of the parameters and their descriptions -func getConfigYaml(c *cli.Context) error { +func getConfigYaml() error { cfg := config.NewRocketPoolConfig("", false) bytes, err := yaml.Marshal(cfg) if err != nil { diff --git a/rocketpool-cli/update/update.go b/rocketpool-cli/update/update.go index 0924e5596..4bc9a7143 100644 --- a/rocketpool-cli/update/update.go +++ b/rocketpool-cli/update/update.go @@ -14,7 +14,6 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) const ( @@ -67,9 +66,9 @@ func forkCommand(binaryPath string, yes bool, args ...string) *exec.Cmd { return cmd } -func Update(c *cli.Context) error { +func Update(yes bool, skipSignatureVerification bool, force bool) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config @@ -100,7 +99,7 @@ func Update(c *cli.Context) error { fmt.Printf("Your detected os/architecture is %s/%s.\n", color.Green(runtime.GOOS), color.Green(runtime.GOARCH)) fmt.Println() - if !c.Bool("yes") { + if !yes { ok := prompt.Confirm("The cli at %s will be replaced. Continue?", color.Yellow(oldBinaryPath)) if !ok { return nil @@ -134,7 +133,7 @@ func Update(c *cli.Context) error { return fmt.Errorf("error downloading new binary: %s", response.Status) } defer response.Body.Close() - if !c.Bool("skip-signature-verification") { + if !skipSignatureVerification { // Download the signature file fmt.Println("Verifying the binary signature") signatureUrl := fmt.Sprintf("%s.sig", downloadUrl) @@ -174,7 +173,7 @@ func Update(c *cli.Context) error { newVersion := strings.TrimSpace(string(output)) newVersion = strings.TrimPrefix(newVersion, "rocketpool version ") - if strings.EqualFold(shared.RocketPoolVersion(), newVersion) && !c.Bool("force") { + if strings.EqualFold(shared.RocketPoolVersion(), newVersion) && !force { color.GreenPrintf("You are already on the latest version of smartnode: %s.", newVersion) return nil } @@ -191,7 +190,7 @@ func Update(c *cli.Context) error { color.GreenPrintln("The cli has been updated.") fmt.Println() - if !c.Bool("yes") { + if !yes { if !prompt.Confirm("Would you like to automatically stop, upgrade, and restart the service to complete the update?") { printPartialSuccessNextSteps() return nil @@ -202,7 +201,7 @@ func Update(c *cli.Context) error { fmt.Println("========= Stopping service... ===========") fmt.Println("=========================================") stopCmd := []string{"service", "stop"} - cmd = forkCommand(oldBinaryPath, c.Bool("yes"), stopCmd...) + cmd = forkCommand(oldBinaryPath, yes, stopCmd...) err = cmd.Run() if err != nil { errorPartialSuccess(err) @@ -212,7 +211,7 @@ func Update(c *cli.Context) error { fmt.Println("=========================================") fmt.Println("========= Upgrading service... ==========") fmt.Println("=========================================") - cmd = forkCommand(oldBinaryPath, c.Bool("yes"), "service", "install", "-d") + cmd = forkCommand(oldBinaryPath, yes, "service", "install", "-d") err = cmd.Run() if err != nil { errorPartialSuccess(err) @@ -222,7 +221,7 @@ func Update(c *cli.Context) error { fmt.Println("=========================================") fmt.Println("========= Starting service... ===========") fmt.Println("=========================================") - cmd = forkCommand(oldBinaryPath, c.Bool("yes"), "service", "start") + cmd = forkCommand(oldBinaryPath, yes, "service", "start") err = cmd.Run() if err != nil { errorPartialSuccess(err) diff --git a/rocketpool-cli/wallet/commands.go b/rocketpool-cli/wallet/commands.go index 6ce635c6d..6a931f465 100644 --- a/rocketpool-cli/wallet/commands.go +++ b/rocketpool-cli/wallet/commands.go @@ -28,7 +28,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return getStatus(c) + return getStatus() }, }, @@ -67,7 +67,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return initWallet(c) + return initWallet(c.String("password"), c.Bool("confirm-mnemonic"), c.String("derivation-path"), c.GlobalBool("secure-session")) }, }, @@ -124,7 +124,14 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return recoverWallet(c) + return recoverWallet( + c.String("password"), + c.String("mnemonic"), + c.String("address"), + c.Bool("skip-validator-key-recovery"), + c.String("derivation-path"), + c.Uint("wallet-index"), + ) }, }, @@ -142,7 +149,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return rebuildWallet(c) + return rebuildWallet() }, }, @@ -190,7 +197,13 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return testRecovery(c) + return testRecovery( + c.String("mnemonic"), + c.String("address"), + c.Bool("skip-validator-key-recovery"), + c.String("derivation-path"), + c.Uint("wallet-index"), + ) }, }, @@ -208,7 +221,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return exportWallet(c) + return exportWallet(c.GlobalBool("secure-session")) }, }, @@ -225,7 +238,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return setEnsName(c, c.Args().Get(0)) + return setEnsName(c.Args().Get(0), c.Bool("yes")) }, }, @@ -242,7 +255,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return purge(c) + return purge(c.Parent().StringSlice("compose-file")) }, }, @@ -272,7 +285,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return masquerade(c) + return masquerade(c.String("address"), c.Bool("yes")) }, }, @@ -297,7 +310,7 @@ func RegisterCommands(app *cli.App, name string, aliases []string) { } // Run - return endMasquerade(c) + return endMasquerade(c.Bool("yes")) }, }, diff --git a/rocketpool-cli/wallet/end-masquerade.go b/rocketpool-cli/wallet/end-masquerade.go index fb9615963..c15ad97cf 100644 --- a/rocketpool-cli/wallet/end-masquerade.go +++ b/rocketpool-cli/wallet/end-masquerade.go @@ -7,12 +7,11 @@ import ( "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func endMasquerade(c *cli.Context) error { +func endMasquerade(yes bool) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get wallet status @@ -38,7 +37,7 @@ func endMasquerade(c *cli.Context) error { } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to end masquerade mode?")) { + if !(yes || prompt.Confirm("Are you sure you want to end masquerade mode?")) { fmt.Println("Cancelled.") return nil } diff --git a/rocketpool-cli/wallet/ens-name.go b/rocketpool-cli/wallet/ens-name.go index f88a0cab0..e4e7bd5bf 100644 --- a/rocketpool-cli/wallet/ens-name.go +++ b/rocketpool-cli/wallet/ens-name.go @@ -8,13 +8,12 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" promptcli "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func setEnsName(c *cli.Context, name string) error { +func setEnsName(name string, yes bool) error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } @@ -33,7 +32,7 @@ func setEnsName(c *cli.Context, name string) error { } // Assign max fees - err = gas.AssignMaxFeeAndLimit(estimateGasSetName.GasInfo, rp, c.Bool("yes")) + err = gas.AssignMaxFeeAndLimit(estimateGasSetName.GasInfo, rp, yes) if err != nil { return err } diff --git a/rocketpool-cli/wallet/export.go b/rocketpool-cli/wallet/export.go index d7c8abd07..f74b488f3 100644 --- a/rocketpool-cli/wallet/export.go +++ b/rocketpool-cli/wallet/export.go @@ -4,16 +4,14 @@ import ( "fmt" "os" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" promptcli "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func exportWallet(c *cli.Context) error { +func exportWallet(secureSession bool) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get & check wallet status @@ -26,7 +24,7 @@ func exportWallet(c *cli.Context) error { return nil } - if !c.GlobalBool("secure-session") { + if !secureSession { // Check if stdout is interactive stat, err := os.Stdout.Stat() if err != nil { diff --git a/rocketpool-cli/wallet/init.go b/rocketpool-cli/wallet/init.go index 5ce34ea30..1ae52f8bb 100644 --- a/rocketpool-cli/wallet/init.go +++ b/rocketpool-cli/wallet/init.go @@ -3,17 +3,15 @@ package wallet import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" promptcli "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" "github.com/rocket-pool/smartnode/shared/utils/term" ) -func initWallet(c *cli.Context) error { +func initWallet(password string, confirmMnemonicFlag bool, derivationPath string, secureSession bool) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get & check wallet status @@ -27,17 +25,14 @@ func initWallet(c *cli.Context) error { } // Prompt for user confirmation before printing sensitive information - if !(c.GlobalBool("secure-session") || + if !(secureSession || promptcli.ConfirmSecureSession("Creating a wallet will print sensitive information to your screen.")) { return nil } // Set password if not set if !status.PasswordSet { - var password string - if c.String("password") != "" { - password = c.String("password") - } else { + if password == "" { password = promptPassword() } if _, err := rp.SetPassword(password); err != nil { @@ -46,7 +41,6 @@ func initWallet(c *cli.Context) error { } // Get the derivation path - derivationPath := c.String("derivation-path") if derivationPath != "" { fmt.Printf("Using a custom derivation path (%s).\n\n", derivationPath) } @@ -68,7 +62,7 @@ func initWallet(c *cli.Context) error { fmt.Println("") // Confirm mnemonic - if !c.Bool("confirm-mnemonic") { + if !confirmMnemonicFlag { confirmMnemonic(response.Mnemonic) } diff --git a/rocketpool-cli/wallet/masquerade.go b/rocketpool-cli/wallet/masquerade.go index efbecb573..48047ed28 100644 --- a/rocketpool-cli/wallet/masquerade.go +++ b/rocketpool-cli/wallet/masquerade.go @@ -7,30 +7,28 @@ import ( cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" ) -func masquerade(c *cli.Context) error { +func masquerade(addressFlag string, yes bool) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() fmt.Println("Masquerading allows you to set your node address to any address you want. All commands will act as though your node wallet is for that address. Since you don't have the private key for that address, you can't submit transactions or sign messages though; commands will be", color.Yellow("read-only"), "until you end the masquerade with `rocketpool wallet end-masquerade`.") fmt.Println() // Get address - addressString := c.String("address") - if addressString == "" { - addressString = prompt.Prompt("Please enter an address to masquerade as:", "^0x[0-9a-fA-F]{40}$", "Invalid address") + if addressFlag == "" { + addressFlag = prompt.Prompt("Please enter an address to masquerade as:", "^0x[0-9a-fA-F]{40}$", "Invalid address") } - address, err := cliutils.ValidateAddress("address", addressString) + address, err := cliutils.ValidateAddress("address", addressFlag) if err != nil { return err } // Prompt for confirmation - if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to masquerade as %s?", color.LightBlue(addressString))) { + if !(yes || prompt.Confirm("Are you sure you want to masquerade as %s?", color.LightBlue(address.Hex()))) { fmt.Println("Cancelled.") return nil } @@ -41,7 +39,7 @@ func masquerade(c *cli.Context) error { return fmt.Errorf("error running masquerade: %w", err) } - fmt.Printf("Your node is now masquerading as address %s.\n", color.LightBlue(addressString)) + fmt.Printf("Your node is now masquerading as address %s.\n", color.LightBlue(address.Hex())) return nil } diff --git a/rocketpool-cli/wallet/purge.go b/rocketpool-cli/wallet/purge.go index 993f4ecb7..eb76400d3 100644 --- a/rocketpool-cli/wallet/purge.go +++ b/rocketpool-cli/wallet/purge.go @@ -3,17 +3,15 @@ package wallet import ( "fmt" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" promptcli "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func purge(c *cli.Context) error { +func purge(composeFiles []string) error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() color.RedPrintln("WARNING: This will delete your node wallet, all of your validator keys (including externally-generated ones in the 'custom-keys' folder), and restart your Docker containers.") @@ -27,7 +25,6 @@ func purge(c *cli.Context) error { } // Purge - composeFiles := c.Parent().StringSlice("compose-file") err := rp.PurgeAllKeys(composeFiles) if err != nil { return fmt.Errorf("%w\n"+color.Red("THERE WAS AN ERROR DELETING YOUR KEYS. They most likely have not been deleted. Proceed with caution."), err) diff --git a/rocketpool-cli/wallet/rebuild.go b/rocketpool-cli/wallet/rebuild.go index d625c4040..6411685e1 100644 --- a/rocketpool-cli/wallet/rebuild.go +++ b/rocketpool-cli/wallet/rebuild.go @@ -4,15 +4,13 @@ import ( "fmt" "os" - "github.com/urfave/cli" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" ) -func rebuildWallet(c *cli.Context) error { +func rebuildWallet() error { // Get RP client - rp, err := rocketpool.NewClientFromCtx(c).WithReady() + rp, err := rocketpool.NewClient().WithReady() if err != nil { return err } diff --git a/rocketpool-cli/wallet/recover.go b/rocketpool-cli/wallet/recover.go index c2661c085..d2f1ec904 100644 --- a/rocketpool-cli/wallet/recover.go +++ b/rocketpool-cli/wallet/recover.go @@ -6,17 +6,16 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" promptcli "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" ) -func recoverWallet(c *cli.Context) error { +func recoverWallet(password, mnemonic, addressFlag string, skipValidatorKeyRecovery bool, derivationPath string, walletIndex uint) error { // Get RP client - rp, ready, err := rocketpool.NewClientFromCtx(c).WithStatus() + rp, ready, err := rocketpool.NewClient().WithStatus() if err != nil { return err } @@ -46,10 +45,7 @@ func recoverWallet(c *cli.Context) error { // Set password if not set if !status.PasswordSet { - var password string - if c.String("password") != "" { - password = c.String("password") - } else { + if password == "" { password = promptPassword() } if _, err := rp.SetPassword(password); err != nil { @@ -58,7 +54,6 @@ func recoverWallet(c *cli.Context) error { } // Handle validator key recovery skipping - skipValidatorKeyRecovery := c.Bool("skip-validator-key-recovery") if !skipValidatorKeyRecovery && !ready { fmt.Println(color.Yellow("Eth Clients are not available.") + " Validator keys cannot be recovered until they are synced and ready.") fmt.Println("You can recover them later with 'rocketpool wallet rebuild'") @@ -70,10 +65,7 @@ func recoverWallet(c *cli.Context) error { } // Prompt for mnemonic - var mnemonic string - if c.String("mnemonic") != "" { - mnemonic = c.String("mnemonic") - } else { + if mnemonic == "" { mnemonic = PromptMnemonic() } mnemonic = strings.TrimSpace(mnemonic) @@ -101,11 +93,9 @@ func recoverWallet(c *cli.Context) error { } // Check for a search-by-address operation - addressString := c.String("address") - if addressString != "" { - + if addressFlag != "" { // Get the address to search for - address := common.HexToAddress(addressString) + address := common.HexToAddress(addressFlag) fmt.Printf("Searching for the derivation path and index for wallet %s...\nNOTE: this may take several minutes depending on how large your wallet's index is.\n", address.Hex()) if !skipValidatorKeyRecovery { @@ -139,13 +129,11 @@ func recoverWallet(c *cli.Context) error { } else { // Get the derivation path - derivationPath := c.String("derivation-path") if derivationPath != "" { fmt.Printf("Using a custom derivation path (%s).\n", derivationPath) } // Get the wallet index - walletIndex := c.Uint("wallet-index") if walletIndex != 0 { fmt.Printf("Using a custom wallet index (%d).\n", walletIndex) } diff --git a/rocketpool-cli/wallet/status.go b/rocketpool-cli/wallet/status.go index 0d946f596..7226bf9d9 100644 --- a/rocketpool-cli/wallet/status.go +++ b/rocketpool-cli/wallet/status.go @@ -4,17 +4,16 @@ import ( "fmt" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" cliutils "github.com/rocket-pool/smartnode/shared/utils/cli" "github.com/rocket-pool/smartnode/shared/utils/cli/color" ) -func getStatus(c *cli.Context) error { +func getStatus() error { // Get RP client - rp := rocketpool.NewClientFromCtx(c) + rp := rocketpool.NewClient() defer rp.Close() // Get the config diff --git a/rocketpool-cli/wallet/test.go b/rocketpool-cli/wallet/test.go index 1fef45691..571c7be4b 100644 --- a/rocketpool-cli/wallet/test.go +++ b/rocketpool-cli/wallet/test.go @@ -6,16 +6,15 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" - "github.com/urfave/cli" "github.com/rocket-pool/smartnode/shared/services/rocketpool" "github.com/rocket-pool/smartnode/shared/utils/cli/color" ) -func testRecovery(c *cli.Context) error { +func testRecovery(mnemonic, addressFlag string, skipValidatorKeyRecovery bool, derivationPath string, walletIndex uint) error { // Get RP client - rp, ready, err := rocketpool.NewClientFromCtx(c).WithStatus() + rp, ready, err := rocketpool.NewClient().WithStatus() if err != nil { return err } @@ -34,17 +33,12 @@ func testRecovery(c *cli.Context) error { fmt.Println() // Prompt for mnemonic - var mnemonic string - if c.String("mnemonic") != "" { - mnemonic = c.String("mnemonic") - } else { + if mnemonic == "" { mnemonic = PromptMnemonic() } mnemonic = strings.TrimSpace(mnemonic) // Handle validator key recovery skipping - skipValidatorKeyRecovery := c.Bool("skip-validator-key-recovery") - // Check for custom keys if !skipValidatorKeyRecovery { customKeyPasswordFile, err := promptForCustomKeyPasswords(rp, cfg, true) @@ -61,18 +55,25 @@ func testRecovery(c *cli.Context) error { err = os.Remove(customKeyPasswordFile) if err != nil { - fmt.Printf("*** WARNING ***\nAn error occurred while removing the custom keystore password file: %s\n\nThis file contains the passwords to your custom validator keys.\nYou *must* delete it manually as soon as possible so nobody can read it.\n\nThe file is located here:\n\n\t%s\n\n", err.Error(), customKeyPasswordFile) + fmt.Println("*** WARNING ***") + fmt.Printf("An error occurred while removing the custom keystore password file: %s\n", err.Error()) + fmt.Println() + fmt.Println("This file contains the passwords to your custom validator keys.") + fmt.Println("You *must* delete it manually as soon as possible so nobody can read it.") + fmt.Println() + fmt.Println("The file is located here:") + fmt.Println() + fmt.Printf("\t%s\n", customKeyPasswordFile) + fmt.Println() } }(customKeyPasswordFile) } } // Check for a search-by-address operation - addressString := c.String("address") - if addressString != "" { - + if addressFlag != "" { // Get the address to search for - address := common.HexToAddress(addressString) + address := common.HexToAddress(addressFlag) fmt.Printf("Searching for the derivation path and index for wallet %s...\nNOTE: this may take several minutes depending on how large your wallet's index is.\n", address.Hex()) if !skipValidatorKeyRecovery { @@ -109,13 +110,11 @@ func testRecovery(c *cli.Context) error { } else { // Get the derivation path - derivationPath := c.String("derivation-path") if derivationPath != "" { fmt.Printf("Using a custom derivation path (%s).\n", derivationPath) } // Get the wallet index - walletIndex := c.Uint("wallet-index") if walletIndex != 0 { fmt.Printf("Using a custom wallet index (%d).\n", walletIndex) } diff --git a/shared/services/rocketpool/client.go b/shared/services/rocketpool/client.go index 5169b024b..b99bd878b 100644 --- a/shared/services/rocketpool/client.go +++ b/shared/services/rocketpool/client.go @@ -17,7 +17,6 @@ import ( "github.com/fatih/color" "github.com/goccy/go-json" - "github.com/urfave/cli" "golang.org/x/crypto/ssh" "github.com/alessio/shellescape" @@ -58,6 +57,8 @@ const ( DebugColor = color.FgYellow ) +var Defaults Globals + // When printing sync percents, we should avoid printing 100%. // This function is only called if we're still syncing, // and the `%0.2f` token will round up if we're above 99.99%. @@ -65,19 +66,23 @@ func SyncRatioToPercent(in float64) float64 { return math.Min(99.99, in*100) } +type Globals struct { + ConfigPath string + DaemonPath string + MaxFee float64 + MaxPrioFee float64 + GasLimit uint64 + DebugPrint bool + CustomNonce *big.Int +} + // Rocket Pool client type Client struct { - configPath string - daemonPath string - maxFee float64 - maxPrioFee float64 - gasLimit uint64 - customNonce *big.Int + globals Globals client *ssh.Client originalMaxFee float64 originalMaxPrioFee float64 originalGasLimit uint64 - debugPrint bool ignoreSyncCheck bool forceFallbacks bool } @@ -141,30 +146,25 @@ func checkClientStatus(rp *Client) (bool, error) { return false, nil } +func SetDefaults(g Globals) { + Defaults = g +} + // Create new Rocket Pool client from CLI context without checking for sync status // Only use this function from commands that may work if the Daemon service doesn't exist -// Most users should call NewClientFromCtx(c).WithStatus() or NewClientFromCtx(c).WithReady() -func NewClientFromCtx(c *cli.Context) *Client { +// Most users should call NewClient().WithStatus() or NewClient().WithReady() +func NewClient() *Client { // Return client client := &Client{ - configPath: os.ExpandEnv(c.GlobalString("config-path")), - daemonPath: os.ExpandEnv(c.GlobalString("daemon-path")), - maxFee: c.GlobalFloat64("maxFee"), - maxPrioFee: c.GlobalFloat64("maxPrioFee"), - gasLimit: c.GlobalUint64("gasLimit"), - originalMaxFee: c.GlobalFloat64("maxFee"), - originalMaxPrioFee: c.GlobalFloat64("maxPrioFee"), - originalGasLimit: c.GlobalUint64("gasLimit"), - debugPrint: c.GlobalBool("debug"), + globals: Defaults, + originalMaxFee: Defaults.MaxFee, + originalMaxPrioFee: Defaults.MaxPrioFee, + originalGasLimit: Defaults.GasLimit, forceFallbacks: false, ignoreSyncCheck: false, } - if nonce, ok := c.App.Metadata["nonce"]; ok { - client.customNonce = nonce.(*big.Int) - } - return client } @@ -210,13 +210,13 @@ func (c *Client) Close() { } func (c *Client) ConfigPath() string { - return c.configPath + return c.globals.ConfigPath } // Load the config // Returns the RocketPoolConfig and whether or not it was newly generated func (c *Client) LoadConfig() (*config.RocketPoolConfig, bool, error) { - settingsFilePath := filepath.Join(c.configPath, SettingsFile) + settingsFilePath := filepath.Join(c.ConfigPath(), SettingsFile) expandedPath, err := homedir.Expand(settingsFilePath) if err != nil { return nil, false, fmt.Errorf("error expanding settings file path: %w", err) @@ -233,12 +233,12 @@ func (c *Client) LoadConfig() (*config.RocketPoolConfig, bool, error) { } // Config wasn't loaded, but there was no error- we should create one. - return config.NewRocketPoolConfig(c.configPath, c.daemonPath != ""), true, nil + return config.NewRocketPoolConfig(c.ConfigPath(), c.globals.DaemonPath != ""), true, nil } // Load the backup config func (c *Client) LoadBackupConfig() (*config.RocketPoolConfig, error) { - settingsFilePath := filepath.Join(c.configPath, BackupSettingsFile) + settingsFilePath := filepath.Join(c.ConfigPath(), BackupSettingsFile) expandedPath, err := homedir.Expand(settingsFilePath) if err != nil { return nil, fmt.Errorf("error expanding backup settings file path: %w", err) @@ -249,7 +249,7 @@ func (c *Client) LoadBackupConfig() (*config.RocketPoolConfig, error) { // Save the config func (c *Client) SaveConfig(cfg *config.RocketPoolConfig) error { - settingsFileDirectoryPath, err := homedir.Expand(c.configPath) + settingsFileDirectoryPath, err := homedir.Expand(c.ConfigPath()) if err != nil { return err } @@ -258,7 +258,7 @@ func (c *Client) SaveConfig(cfg *config.RocketPoolConfig) error { // Remove the upgrade flag file func (c *Client) RemoveUpgradeFlagFile() error { - expandedPath, err := homedir.Expand(c.configPath) + expandedPath, err := homedir.Expand(c.ConfigPath()) if err != nil { return err } @@ -267,7 +267,7 @@ func (c *Client) RemoveUpgradeFlagFile() error { // Returns whether or not this is the first run of the configurator since a previous installation func (c *Client) IsFirstRun() (bool, error) { - expandedPath, err := homedir.Expand(c.configPath) + expandedPath, err := homedir.Expand(c.ConfigPath()) if err != nil { return false, fmt.Errorf("error expanding settings file path: %w", err) } @@ -276,12 +276,12 @@ func (c *Client) IsFirstRun() (bool, error) { // Load the Prometheus template, do a template variable substitution, and save it func (c *Client) UpdatePrometheusConfiguration(config *config.RocketPoolConfig) error { - prometheusTemplatePath, err := homedir.Expand(fmt.Sprintf("%s/%s", c.configPath, PrometheusConfigTemplate)) + prometheusTemplatePath, err := homedir.Expand(fmt.Sprintf("%s/%s", c.ConfigPath(), PrometheusConfigTemplate)) if err != nil { return fmt.Errorf("Error expanding Prometheus template path: %w", err) } - prometheusConfigPath, err := homedir.Expand(fmt.Sprintf("%s/%s", c.configPath, PrometheusFile)) + prometheusConfigPath, err := homedir.Expand(fmt.Sprintf("%s/%s", c.ConfigPath(), PrometheusFile)) if err != nil { return fmt.Errorf("Error expanding Prometheus config file path: %w", err) } @@ -541,14 +541,14 @@ func (c *Client) GetServiceVersion() (string, error) { // Get service container version output var cmd string - if c.daemonPath == "" { + if c.globals.DaemonPath == "" { containerName, err := c.getAPIContainerName() if err != nil { return "", err } cmd = fmt.Sprintf("docker exec %s %s --version", shellescape.Quote(containerName), shellescape.Quote(APIBinPath)) } else { - cmd = fmt.Sprintf("%s --version", shellescape.Quote(c.daemonPath)) + cmd = fmt.Sprintf("%s --version", shellescape.Quote(c.globals.DaemonPath)) } versionBytes, err := c.readOutput(cmd) if err != nil { @@ -577,7 +577,7 @@ func (c *Client) GetServiceVersion() (string, error) { // Increments the custom nonce parameter. // This is used for calls that involve multiple transactions, so they don't all have the same nonce. func (c *Client) IncrementCustomNonce() { - c.customNonce.Add(c.customNonce, big.NewInt(1)) + c.globals.CustomNonce.Add(c.globals.CustomNonce, big.NewInt(1)) } // Get the current Docker image used by the given container @@ -1019,14 +1019,14 @@ func (c *Client) PurgeAllKeys(composeFiles []string) error { // Get the gas settings func (c *Client) GetGasSettings() (float64, float64, uint64) { - return c.maxFee, c.maxPrioFee, c.gasLimit + return c.globals.MaxFee, c.globals.MaxPrioFee, c.globals.GasLimit } // Get the gas fees func (c *Client) AssignGasSettings(maxFee float64, maxPrioFee float64, gasLimit uint64) { - c.maxFee = maxFee - c.maxPrioFee = maxPrioFee - c.gasLimit = gasLimit + c.globals.MaxFee = maxFee + c.globals.MaxPrioFee = maxPrioFee + c.globals.GasLimit = gasLimit } // Set the flags for ignoring EC and CC sync checks and forcing fallbacks to prevent unnecessary duplication of effort by the API during CLI commands @@ -1061,12 +1061,12 @@ func (c *Client) checkIfCommandExists(command string) (bool, error) { func (c *Client) compose(composeFiles []string, args string) (string, error) { // Cancel if running in non-docker mode - if c.daemonPath != "" { + if c.globals.DaemonPath != "" { return "", errors.New("command unavailable in Native Mode (with '--daemon-path' option specified)") } // Get the expanded config path - expandedConfigPath, err := homedir.Expand(c.configPath) + expandedConfigPath, err := homedir.Expand(c.ConfigPath()) if err != nil { return "", err } @@ -1271,7 +1271,7 @@ func (c *Client) callAPI(args string, otherArgs ...string) ([]byte, error) { // Create the command to run var cmd string - if c.daemonPath == "" { + if c.globals.DaemonPath == "" { containerName, err := c.getAPIContainerName() if err != nil { return []byte{}, err @@ -1279,8 +1279,8 @@ func (c *Client) callAPI(args string, otherArgs ...string) ([]byte, error) { cmd = fmt.Sprintf("docker exec %s %s %s %s %s %s api %s", shellescape.Quote(containerName), shellescape.Quote(APIBinPath), ignoreSyncCheckFlag, forceFallbackECFlag, c.getGasOpts(), c.getCustomNonce(), args) } else { cmd = fmt.Sprintf("%s --settings %s %s %s %s %s api %s", - c.daemonPath, - shellescape.Quote(fmt.Sprintf("%s/%s", c.configPath, SettingsFile)), + c.globals.DaemonPath, + shellescape.Quote(fmt.Sprintf("%s/%s", c.ConfigPath(), SettingsFile)), ignoreSyncCheckFlag, forceFallbackECFlag, c.getGasOpts(), @@ -1299,7 +1299,7 @@ func (c *Client) callAPIWithEnvVars(envVars map[string]string, args string, othe // Create the command to run var cmd string - if c.daemonPath == "" { + if c.globals.DaemonPath == "" { envArgs := "" for key, value := range envVars { os.Setenv(key, shellescape.Quote(value)) @@ -1317,8 +1317,8 @@ func (c *Client) callAPIWithEnvVars(envVars map[string]string, args string, othe } cmd = fmt.Sprintf("%s %s --settings %s %s %s %s %s api %s", envArgs, - c.daemonPath, - shellescape.Quote(fmt.Sprintf("%s/%s", c.configPath, SettingsFile)), + c.globals.DaemonPath, + shellescape.Quote(fmt.Sprintf("%s/%s", c.ConfigPath(), SettingsFile)), ignoreSyncCheckFlag, forceFallbackECFlag, c.getGasOpts(), @@ -1358,14 +1358,14 @@ func (c *Client) getApiCallArgs(args string, otherArgs ...string) (string, strin } func (c *Client) runApiCall(cmd string) ([]byte, error) { - if c.debugPrint { + if c.globals.DebugPrint { fmt.Println("To API:") fmt.Println(cmd) } output, err := c.readOutput(cmd) - if c.debugPrint { + if c.globals.DebugPrint { if output != nil { fmt.Println("API Out:") fmt.Println(string(output)) @@ -1377,9 +1377,9 @@ func (c *Client) runApiCall(cmd string) ([]byte, error) { } // Reset the gas settings after the call - c.maxFee = c.originalMaxFee - c.maxPrioFee = c.originalMaxPrioFee - c.gasLimit = c.originalGasLimit + c.globals.MaxFee = c.originalMaxFee + c.globals.MaxPrioFee = c.originalMaxPrioFee + c.globals.GasLimit = c.originalGasLimit return output, err } @@ -1399,17 +1399,17 @@ func (c *Client) getAPIContainerName() (string, error) { // Get gas price & limit flags func (c *Client) getGasOpts() string { var opts string - opts += fmt.Sprintf("--maxFee %f ", c.maxFee) - opts += fmt.Sprintf("--maxPrioFee %f ", c.maxPrioFee) - opts += fmt.Sprintf("--gasLimit %d ", c.gasLimit) + opts += fmt.Sprintf("--maxFee %f ", c.globals.MaxFee) + opts += fmt.Sprintf("--maxPrioFee %f ", c.globals.MaxPrioFee) + opts += fmt.Sprintf("--gasLimit %d ", c.globals.GasLimit) return opts } func (c *Client) getCustomNonce() string { // Set the custom nonce nonce := "" - if c.customNonce != nil { - nonce = fmt.Sprintf("--nonce %s", c.customNonce.String()) + if c.globals.CustomNonce != nil { + nonce = fmt.Sprintf("--nonce %s", c.globals.CustomNonce.String()) } return nonce } diff --git a/shared/utils/cli/migration/change-withdrawal-creds.go b/shared/utils/cli/migration/change-withdrawal-creds.go deleted file mode 100644 index 4dfcad619..000000000 --- a/shared/utils/cli/migration/change-withdrawal-creds.go +++ /dev/null @@ -1,37 +0,0 @@ -package migration - -import ( - "fmt" - - "github.com/ethereum/go-ethereum/common" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" -) - -// Changes a vacant minipool's withdrawal credentials from 0x00 to 0x01 -func ChangeWithdrawalCreds(rp *rocketpool.Client, minipoolAddress common.Address, mnemonic string) bool { - - // Check if the withdrawal creds can be changed - changeResponse, err := rp.CanChangeWithdrawalCredentials(minipoolAddress, mnemonic) - success := true - if err != nil { - fmt.Printf("Error checking if withdrawal creds can be migrated: %s\n", err.Error()) - success = false - } - if !changeResponse.CanChange { - success = false - } - if !success { - return false - } - - // Change the withdrawal creds - fmt.Print("Changing withdrawal credentials to the minipool address... ") - _, err = rp.ChangeWithdrawalCredentials(minipoolAddress, mnemonic) - if err != nil { - fmt.Printf("error changing withdrawal credentials: %s\n", err.Error()) - return false - } - fmt.Println("done!") - return true - -} diff --git a/shared/utils/cli/migration/import-key.go b/shared/utils/cli/migration/import-key.go deleted file mode 100644 index 7395ddf58..000000000 --- a/shared/utils/cli/migration/import-key.go +++ /dev/null @@ -1,64 +0,0 @@ -package migration - -import ( - "fmt" - - "github.com/ethereum/go-ethereum/common" - "github.com/rocket-pool/smartnode/rocketpool-cli/wallet" - "github.com/rocket-pool/smartnode/shared/services/rocketpool" - "github.com/rocket-pool/smartnode/shared/utils/cli/color" - "github.com/rocket-pool/smartnode/shared/utils/cli/prompt" - "github.com/urfave/cli" -) - -// Imports the private key for a vacant minipool's validator -func ImportKey(c *cli.Context, rp *rocketpool.Client, minipoolAddress common.Address, mnemonic string) bool { - - // Print a warning and prompt for confirmation of anti-slashing - color.RedPrintln("WARNING:") - color.RedPrintln("Before doing this, you **MUST** do the following:") - color.RedPrintln("1. Remove this key from your existing Validator Client used for solo staking") - color.RedPrintln("2. Restart it so that it is no longer validating with that key") - color.RedPrintln("3. Wait for 15 minutes so it has missed at least two attestations") - color.RedPrintln("Failure to do this **will result in your validator being SLASHED**.") - fmt.Println() - if !prompt.Confirm("Have you removed the key from your own Validator Client, restarted it, and waited long enough for your validator to miss at least two attestations?") { - fmt.Println("Cancelled.") - return false - } - - // Get the mnemonic - if mnemonic == "" { - mnemonic = wallet.PromptMnemonic() - } - - // Import the key - fmt.Printf("Importing validator key... ") - _, err := rp.ImportKey(minipoolAddress, mnemonic) - if err != nil { - fmt.Printf("error importing validator key: %s\n", err.Error()) - return false - } - fmt.Println("done!") - - // Restart the VC if necessary - if c.Bool("no-restart") { - return true - } - if c.Bool("yes") || prompt.Confirm("Would you like to restart the Smart Node's Validator Client now so it loads your validator's key?") { - // Restart the VC - fmt.Print("Restarting Validator Client... ") - _, err := rp.RestartVc() - if err != nil { - fmt.Println("failed!") - color.YellowPrintf("WARNING: error restarting validator client: %s\n", err.Error()) - fmt.Println() - color.YellowPrintln("Please restart it manually so it picks up the new validator key for your minipool.") - return false - } - fmt.Println("done!") - fmt.Println() - } - return true - -} diff --git a/shared/utils/cli/utils.go b/shared/utils/cli/utils.go index e301b9a67..742658b12 100644 --- a/shared/utils/cli/utils.go +++ b/shared/utils/cli/utils.go @@ -11,6 +11,8 @@ import ( "github.com/rocket-pool/smartnode/shared/utils/cli/color" ) +const TimeFormat = "2006-01-02, 15:04 -0700 MST" + // Print a TX's details to the console. func PrintTransactionHash(rp *rocketpool.Client, hash common.Hash) { diff --git a/shared/utils/cli/validation.go b/shared/utils/cli/validation.go index 0eb58087a..adf637ac8 100644 --- a/shared/utils/cli/validation.go +++ b/shared/utils/cli/validation.go @@ -384,9 +384,9 @@ func ValidateVoteDirection(name, value string) (types.VoteDirection, error) { // Validate a float // isFraction should be true for percentage inputs or false for unbounded percentage inputs -func ValidateFloat(c *cli.Context, name string, value string, isFraction bool) (*big.Int, error) { +func ValidateFloat(rawEnabled bool, name string, value string, isFraction bool, yes bool) (*big.Int, error) { var floatValue float64 - if c.Bool("raw") { + if rawEnabled { val, err := ValidatePositiveWeiAmount(name, value) if err != nil { return nil, err @@ -407,8 +407,11 @@ func ValidateFloat(c *cli.Context, name string, value string, isFraction bool) ( } trueVal := eth.EthToWei(floatValue) - fmt.Printf("Your value will be multiplied by 10^18 to be used in the contracts, which results in:\n\n\t[%s]\n\n", trueVal.String()) - if !(c.Bool("yes") || prompt.Confirm("Please make sure this is what you want and does not have any floating-point errors.\n\nIs this result correct?")) { + fmt.Println("Your value will be multiplied by 10^18 to be used in the contracts, which results in:") + fmt.Println() + fmt.Printf("\t[%s]\n", trueVal.String()) + fmt.Println() + if !(yes || prompt.Confirm("Please make sure this is what you want and does not have any floating-point errors.\n\nIs this result correct?")) { value = prompt.Prompt("Please enter the wei amount:", "^[0-9]+$", "Invalid amount") val, err := ValidatePositiveWeiAmount(name, value) if err != nil {