From 473208be058236cdb4af0ba222699504050d764b Mon Sep 17 00:00:00 2001 From: MalteHerrmann Date: Sun, 17 Dec 2023 18:51:16 +0100 Subject: [PATCH 1/6] add deposit logic --- go.mod | 2 +- gov/proposal.go | 23 +++++++++++++++++++++-- main.go | 28 +++++++++++++++++++++------- 3 files changed, 43 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index f0fa956..7d201fb 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/MalteHerrmann/upgrade-local-node-go go 1.21 require ( - github.com/cometbft/cometbft v0.37.2 github.com/cosmos/cosmos-sdk v0.47.4 github.com/evmos/evmos/v14 v14.0.0-rc3 github.com/pkg/errors v0.9.1 @@ -43,6 +42,7 @@ require ( github.com/chzyer/readline v1.5.1 // indirect github.com/cockroachdb/apd/v2 v2.0.2 // indirect github.com/coinbase/rosetta-sdk-go/types v1.0.0 // indirect + github.com/cometbft/cometbft v0.37.2 // indirect github.com/cometbft/cometbft-db v0.8.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect diff --git a/gov/proposal.go b/gov/proposal.go index afe3307..2fef680 100644 --- a/gov/proposal.go +++ b/gov/proposal.go @@ -18,7 +18,7 @@ func buildUpgradeProposalCommand(targetVersion string, upgradeHeight int) []stri "tx", "gov", "submit-legacy-proposal", "software-upgrade", targetVersion, "--title", fmt.Sprintf("'Upgrade to %s'", targetVersion), "--description", fmt.Sprintf("'Upgrade to %s'", targetVersion), - "--upgrade-height", fmt.Sprintf("%d", upgradeHeight), + "--upgrade-height", strconv.Itoa(upgradeHeight), "--deposit", "100000000000000000000aevmos", "--output", "json", "--no-validate", @@ -149,7 +149,7 @@ func SubmitUpgradeProposal(bin *utils.Binary, targetVersion string, upgradeHeigh // VoteForProposal votes for the proposal with the given ID using the given account. func VoteForProposal(bin *utils.Binary, proposalID int, sender string) (string, error) { out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ - Subcommand: []string{"tx", "gov", "vote", fmt.Sprintf("%d", proposalID), "yes"}, + Subcommand: []string{"tx", "gov", "vote", strconv.Itoa(proposalID), "yes"}, From: sender, UseDefaults: true, Quiet: true, @@ -160,3 +160,22 @@ func VoteForProposal(bin *utils.Binary, proposalID int, sender string) (string, return out, nil } + +// DepositForProposal deposits the given amount of Evmos for the proposal with the given proposalID +// from the given account. +func DepositForProposal(bin *utils.Binary, proposalID int, sender string, amount int) (string, error) { + out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ + Subcommand: []string{ + "tx", "gov", "deposit", strconv.Itoa(proposalID), strconv.Itoa(amount) + "aevmos", + }, + From: sender, + UseDefaults: true, + Quiet: true, + }) + + if err != nil { + return out, errors.Wrap(err, fmt.Sprintf("failed to deposit for proposal %d", proposalID)) + } + + return out, nil +} diff --git a/main.go b/main.go index d4103a3..b59edda 100644 --- a/main.go +++ b/main.go @@ -19,7 +19,8 @@ func main() { log.Printf( "Possible usages:\n" + " upgrade-local-node-go \n" + - " upgrade-local-node-go vote [proposal-id]\n", + " upgrade-local-node-go vote [proposal-id]\n" + + " upgrade-local-node-go deposit [proposal-id]\n", ) os.Exit(1) } @@ -34,9 +35,10 @@ func main() { log.Fatalf("Error getting accounts: %v", err) } - //nolint:nestif // nesting complexity is fine here, will be reworked with Cobra commands anyway - if os.Args[1] == "vote" { - proposalID, err := getProposalIDForVoting(bin, os.Args) + // TODO: use with Cobra CLI + switch os.Args[1] { + case "vote": + proposalID, err := getProposalIDFromInput(bin, os.Args) if err != nil { log.Fatalf("Error getting proposal ID: %v", err) } @@ -45,7 +47,19 @@ func main() { if err != nil { log.Fatalf("Error submitting votes for proposal %d: %v", proposalID, err) } - } else { + + case "deposit": + proposalID, err := getProposalIDFromInput(bin, os.Args) + if err != nil { + log.Fatalf("Error getting proposal ID: %v", err) + } + + // TODO: replace fixed amount with min deposit from chain params + if _, err = gov.DepositForProposal(bin, proposalID, bin.Accounts[0].Name, 1e9); err != nil { + log.Fatalf("Error depositing for proposal %d: %v", proposalID, err) + } + + default: targetVersion := os.Args[1] if matched, _ := regexp.MatchString(`v\d+\.\d+\.\d(-rc\d+)?`, targetVersion); !matched { log.Fatalf("Invalid target version: %s. Please use the format vX.Y.Z(-rc*).\n", targetVersion) @@ -58,8 +72,8 @@ func main() { } } -// getProposalIDForVoting gets the proposal ID from the command line arguments. -func getProposalIDForVoting(bin *utils.Binary, args []string) (int, error) { +// getProposalIDFromInput gets the proposal ID from the command line arguments. +func getProposalIDFromInput(bin *utils.Binary, args []string) (int, error) { var ( err error proposalID int From 4f93ce59e335d7e91d43bba230e90b9bf351c440 Mon Sep 17 00:00:00 2001 From: MalteHerrmann Date: Sun, 17 Dec 2023 19:14:55 +0100 Subject: [PATCH 2/6] linters and restructuring --- gov/deposit.go | 27 +++++++++++++++++++ gov/proposal.go | 71 ------------------------------------------------- gov/vote.go | 62 ++++++++++++++++++++++++++++++++++++++++++ main.go | 40 +++++++++++++--------------- 4 files changed, 107 insertions(+), 93 deletions(-) create mode 100644 gov/deposit.go create mode 100644 gov/vote.go diff --git a/gov/deposit.go b/gov/deposit.go new file mode 100644 index 0000000..b604234 --- /dev/null +++ b/gov/deposit.go @@ -0,0 +1,27 @@ +package gov + +import ( + "fmt" + "strconv" + + "github.com/MalteHerrmann/upgrade-local-node-go/utils" + "github.com/pkg/errors" +) + +// DepositForProposal deposits the given amount of Evmos for the proposal with the given proposalID +// from the given account. +func DepositForProposal(bin *utils.Binary, proposalID int, sender string, amount int) (string, error) { + out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ + Subcommand: []string{ + "tx", "gov", "deposit", strconv.Itoa(proposalID), strconv.Itoa(amount) + "aevmos", + }, + From: sender, + UseDefaults: true, + Quiet: true, + }) + if err != nil { + return out, errors.Wrap(err, fmt.Sprintf("failed to deposit for proposal %d", proposalID)) + } + + return out, nil +} diff --git a/gov/proposal.go b/gov/proposal.go index 2fef680..5dfbcf2 100644 --- a/gov/proposal.go +++ b/gov/proposal.go @@ -2,7 +2,6 @@ package gov import ( "fmt" - "log" "strconv" "strings" @@ -78,42 +77,6 @@ func QueryLatestProposalID(bin *utils.Binary) (int, error) { return int(res.Proposals[len(res.Proposals)-1].Id), nil } -// SubmitAllVotesForProposal submits a vote for the given proposal ID using all testing accounts. -func SubmitAllVotesForProposal(bin *utils.Binary, proposalID int) error { - accsWithDelegations, err := utils.FilterAccountsWithDelegations(bin) - if err != nil { - return errors.Wrap(err, "Error filtering accounts") - } - - if len(accsWithDelegations) == 0 { - return errors.New("No accounts with delegations found") - } - - utils.Wait(1) - log.Printf("Voting for proposal %d...\n", proposalID) - - var out string - - for _, acc := range accsWithDelegations { - out, err = VoteForProposal(bin, proposalID, acc.Name) - if err != nil { - if strings.Contains(out, fmt.Sprintf("%d: unknown proposal", proposalID)) { - return fmt.Errorf("no proposal with ID %d found", proposalID) - } - - if strings.Contains(out, fmt.Sprintf("%d: inactive proposal", proposalID)) { - return fmt.Errorf("proposal with ID %d is inactive", proposalID) - } - - log.Printf(" - could NOT vote using key: %s\n", acc.Name) - } else { - log.Printf(" - voted using key: %s\n", acc.Name) - } - } - - return nil -} - // SubmitUpgradeProposal submits a software upgrade proposal with the given target version and upgrade height. func SubmitUpgradeProposal(bin *utils.Binary, targetVersion string, upgradeHeight int) (int, error) { upgradeProposal := buildUpgradeProposalCommand(targetVersion, upgradeHeight) @@ -145,37 +108,3 @@ func SubmitUpgradeProposal(bin *utils.Binary, targetVersion string, upgradeHeigh return GetProposalIDFromSubmitEvents(events) } - -// VoteForProposal votes for the proposal with the given ID using the given account. -func VoteForProposal(bin *utils.Binary, proposalID int, sender string) (string, error) { - out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ - Subcommand: []string{"tx", "gov", "vote", strconv.Itoa(proposalID), "yes"}, - From: sender, - UseDefaults: true, - Quiet: true, - }) - if err != nil { - return out, errors.Wrap(err, fmt.Sprintf("failed to vote for proposal %d", proposalID)) - } - - return out, nil -} - -// DepositForProposal deposits the given amount of Evmos for the proposal with the given proposalID -// from the given account. -func DepositForProposal(bin *utils.Binary, proposalID int, sender string, amount int) (string, error) { - out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ - Subcommand: []string{ - "tx", "gov", "deposit", strconv.Itoa(proposalID), strconv.Itoa(amount) + "aevmos", - }, - From: sender, - UseDefaults: true, - Quiet: true, - }) - - if err != nil { - return out, errors.Wrap(err, fmt.Sprintf("failed to deposit for proposal %d", proposalID)) - } - - return out, nil -} diff --git a/gov/vote.go b/gov/vote.go new file mode 100644 index 0000000..b7e5310 --- /dev/null +++ b/gov/vote.go @@ -0,0 +1,62 @@ +package gov + +import ( + "fmt" + "log" + "strconv" + "strings" + + "github.com/MalteHerrmann/upgrade-local-node-go/utils" + "github.com/pkg/errors" +) + +// SubmitAllVotesForProposal submits a vote for the given proposal ID using all testing accounts. +func SubmitAllVotesForProposal(bin *utils.Binary, proposalID int) error { + accsWithDelegations, err := utils.FilterAccountsWithDelegations(bin) + if err != nil { + return errors.Wrap(err, "error filtering accounts") + } + + if len(accsWithDelegations) == 0 { + return errors.New("no accounts with delegations found") + } + + utils.Wait(1) + log.Printf("Voting for proposal %d...\n", proposalID) + + var out string + + for _, acc := range accsWithDelegations { + out, err = VoteForProposal(bin, proposalID, acc.Name) + if err != nil { + if strings.Contains(out, fmt.Sprintf("%d: unknown proposal", proposalID)) { + return fmt.Errorf("no proposal with ID %d found", proposalID) + } + + if strings.Contains(out, fmt.Sprintf("%d: inactive proposal", proposalID)) { + return fmt.Errorf("proposal with ID %d is inactive", proposalID) + } + + log.Printf(" - could NOT vote using key: %s\n", acc.Name) + } else { + log.Printf(" - voted using key: %s\n", acc.Name) + } + } + + return nil +} + +// VoteForProposal votes for the proposal with the given ID using the given account. +func VoteForProposal(bin *utils.Binary, proposalID int, sender string) (string, error) { + out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ + Subcommand: []string{"tx", "gov", "vote", strconv.Itoa(proposalID), "yes"}, + From: sender, + UseDefaults: true, + Quiet: true, + }) + if err != nil { + return out, errors.Wrap(err, fmt.Sprintf("failed to vote for proposal %d", proposalID)) + } + + return out, nil +} diff --git a/main.go b/main.go index b59edda..ac45d02 100644 --- a/main.go +++ b/main.go @@ -27,12 +27,11 @@ func main() { bin, err := utils.NewEvmosTestingBinary() if err != nil { - log.Fatalf("Error creating binary: %v", err) + log.Fatalf("error creating binary: %v", err) } - err = bin.GetAccounts() - if err != nil { - log.Fatalf("Error getting accounts: %v", err) + if err = bin.GetAccounts(); err != nil { + log.Fatalf("error getting accounts: %v", err) } // TODO: use with Cobra CLI @@ -40,34 +39,32 @@ func main() { case "vote": proposalID, err := getProposalIDFromInput(bin, os.Args) if err != nil { - log.Fatalf("Error getting proposal ID: %v", err) + log.Fatalf("error getting proposal ID: %v", err) } - err = gov.SubmitAllVotesForProposal(bin, proposalID) - if err != nil { - log.Fatalf("Error submitting votes for proposal %d: %v", proposalID, err) + if err = gov.SubmitAllVotesForProposal(bin, proposalID); err != nil { + log.Fatalf("error submitting votes for proposal %d: %v", proposalID, err) } case "deposit": proposalID, err := getProposalIDFromInput(bin, os.Args) if err != nil { - log.Fatalf("Error getting proposal ID: %v", err) + log.Fatalf("error getting proposal ID: %v", err) } // TODO: replace fixed amount with min deposit from chain params if _, err = gov.DepositForProposal(bin, proposalID, bin.Accounts[0].Name, 1e9); err != nil { - log.Fatalf("Error depositing for proposal %d: %v", proposalID, err) + log.Fatalf("error depositing for proposal %d: %v", proposalID, err) } default: targetVersion := os.Args[1] if matched, _ := regexp.MatchString(`v\d+\.\d+\.\d(-rc\d+)?`, targetVersion); !matched { - log.Fatalf("Invalid target version: %s. Please use the format vX.Y.Z(-rc*).\n", targetVersion) + log.Fatalf("invalid target version: %s; please use the format vX.Y.Z(-rc*).\n", targetVersion) } - err := upgradeLocalNode(bin, targetVersion) - if err != nil { - log.Fatalf("Error upgrading local node: %v", err) + if err := upgradeLocalNode(bin, targetVersion); err != nil { + log.Fatalf("error upgrading local node: %v", err) } } } @@ -83,15 +80,15 @@ func getProposalIDFromInput(bin *utils.Binary, args []string) (int, error) { case 2: proposalID, err = gov.QueryLatestProposalID(bin) if err != nil { - return 0, errors.Wrap(err, "Error querying latest proposal ID") + return 0, errors.Wrap(err, "error querying latest proposal ID") } case 3: proposalID, err = strconv.Atoi(args[2]) if err != nil { - return 0, errors.Wrapf(err, "Error converting proposal ID %s to integer", args[2]) + return 0, errors.Wrapf(err, "error converting proposal ID %s to integer", args[2]) } default: - return 0, errors.New("Invalid number of arguments") + return 0, errors.New("invalid number of arguments") } return proposalID, nil @@ -102,7 +99,7 @@ func getProposalIDFromInput(bin *utils.Binary, args []string) (int, error) { func upgradeLocalNode(bin *utils.Binary, targetVersion string) error { currentHeight, err := utils.GetCurrentHeight(bin) if err != nil { - return errors.Wrap(err, "Error getting current height") + return errors.Wrap(err, "error getting current height") } upgradeHeight := currentHeight + deltaHeight @@ -111,14 +108,13 @@ func upgradeLocalNode(bin *utils.Binary, targetVersion string) error { proposalID, err := gov.SubmitUpgradeProposal(bin, targetVersion, upgradeHeight) if err != nil { - return errors.Wrap(err, "Error executing upgrade proposal") + return errors.Wrap(err, "error executing upgrade proposal") } log.Printf("Scheduled upgrade to %s at height %d.\n", targetVersion, upgradeHeight) - err = gov.SubmitAllVotesForProposal(bin, proposalID) - if err != nil { - return errors.Wrapf(err, "Error submitting votes for proposal %d", proposalID) + if err = gov.SubmitAllVotesForProposal(bin, proposalID); err != nil { + return errors.Wrapf(err, "error submitting votes for proposal %d", proposalID) } return nil From 0dfd994b973a58e4b0b47d9d73ad79c6512c2e4e Mon Sep 17 00:00:00 2001 From: MalteHerrmann Date: Sun, 17 Dec 2023 20:32:54 +0100 Subject: [PATCH 3/6] move delegations specific functionality to own file --- utils/delegations.go | 25 +++++++++++++++++ utils/delegations_test.go | 56 +++++++++++++++++++++++++++++++++++++++ utils/keys.go | 18 ------------- utils/keys_test.go | 48 --------------------------------- 4 files changed, 81 insertions(+), 66 deletions(-) create mode 100644 utils/delegations.go create mode 100644 utils/delegations_test.go diff --git a/utils/delegations.go b/utils/delegations.go new file mode 100644 index 0000000..8c21fd9 --- /dev/null +++ b/utils/delegations.go @@ -0,0 +1,25 @@ +package utils + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// ParseDelegationsFromResponse parses the delegations from the given response. +func ParseDelegationsFromResponse(cdc *codec.ProtoCodec, out string) ([]stakingtypes.Delegation, error) { + var res stakingtypes.QueryDelegatorDelegationsResponse + + err := cdc.UnmarshalJSON([]byte(out), &res) + if err != nil { + return nil, fmt.Errorf("error unmarshalling delegations: %w", err) + } + + delegations := make([]stakingtypes.Delegation, len(res.DelegationResponses)) + for i, delegation := range res.DelegationResponses { + delegations[i] = delegation.Delegation + } + + return delegations, nil +} diff --git a/utils/delegations_test.go b/utils/delegations_test.go new file mode 100644 index 0000000..c379e7e --- /dev/null +++ b/utils/delegations_test.go @@ -0,0 +1,56 @@ +package utils_test + +import ( + "testing" + + "github.com/MalteHerrmann/upgrade-local-node-go/utils" + "github.com/stretchr/testify/require" +) + +func TestParseDelegationsFromResponse(t *testing.T) { + t.Parallel() + + cdc, ok := utils.GetCodec() + require.True(t, ok, "unexpected error getting codec") + + testcases := []struct { + name string + out string + expVals []string + expError bool + errContains string + }{ + { + name: "pass", + //nolint:lll // line length is okay here + out: `{"delegation_responses":[{"delegation":{"delegator_address":"evmos1v6jyld5mcu37d3dfe7kjrw0htkc4wu2mxn9y25","validator_address":"evmosvaloper1v6jyld5mcu37d3dfe7kjrw0htkc4wu2mta25tf","shares":"1000000000000000000000.000000000000000000"},"balance":{"denom":"aevmos","amount":"1000000000000000000000"}}],"pagination":{"next_key":null,"total":"0"}}`, + expVals: []string{"evmosvaloper1v6jyld5mcu37d3dfe7kjrw0htkc4wu2mta25tf"}, + }, + { + name: "fail - no keys", + out: "invalid output", + expError: true, + errContains: "error unmarshalling delegations", + }, + } + + for _, tc := range testcases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + delegations, err := utils.ParseDelegationsFromResponse(cdc, tc.out) + if tc.expError { + require.Error(t, err, "expected error parsing delegations") + require.ErrorContains(t, err, tc.errContains, "expected different error") + } else { + require.NoError(t, err, "unexpected error parsing delegations") + + var vals []string + for _, delegation := range delegations { + vals = append(vals, delegation.ValidatorAddress) + } + require.Equal(t, tc.expVals, vals, "expected different validators") + } + }) + } +} diff --git a/utils/keys.go b/utils/keys.go index e403a1a..61614e4 100644 --- a/utils/keys.go +++ b/utils/keys.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/codec" cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -68,23 +67,6 @@ func FilterAccountsWithDelegations(bin *Binary) ([]Account, error) { return stakingAccs, nil } -// ParseDelegationsFromResponse parses the delegations from the given response. -func ParseDelegationsFromResponse(cdc *codec.ProtoCodec, out string) ([]stakingtypes.Delegation, error) { - var res stakingtypes.QueryDelegatorDelegationsResponse - - err := cdc.UnmarshalJSON([]byte(out), &res) - if err != nil { - return nil, fmt.Errorf("error unmarshalling delegations: %w", err) - } - - delegations := make([]stakingtypes.Delegation, len(res.DelegationResponses)) - for i, delegation := range res.DelegationResponses { - delegations[i] = delegation.Delegation - } - - return delegations, nil -} - // ParseAccountsFromOut parses the keys from the given output from the keys list command. func ParseAccountsFromOut(out string) ([]Account, error) { var ( diff --git a/utils/keys_test.go b/utils/keys_test.go index e4f2ebc..51f4c03 100644 --- a/utils/keys_test.go +++ b/utils/keys_test.go @@ -51,51 +51,3 @@ func TestParseKeysFromOut(t *testing.T) { }) } } - -func TestParseDelegationsFromResponse(t *testing.T) { - t.Parallel() - - cdc, ok := utils.GetCodec() - require.True(t, ok, "unexpected error getting codec") - - testcases := []struct { - name string - out string - expVals []string - expError bool - errContains string - }{ - { - name: "pass", - //nolint:lll // line length is okay here - out: `{"delegation_responses":[{"delegation":{"delegator_address":"evmos1v6jyld5mcu37d3dfe7kjrw0htkc4wu2mxn9y25","validator_address":"evmosvaloper1v6jyld5mcu37d3dfe7kjrw0htkc4wu2mta25tf","shares":"1000000000000000000000.000000000000000000"},"balance":{"denom":"aevmos","amount":"1000000000000000000000"}}],"pagination":{"next_key":null,"total":"0"}}`, - expVals: []string{"evmosvaloper1v6jyld5mcu37d3dfe7kjrw0htkc4wu2mta25tf"}, - }, - { - name: "fail - no keys", - out: "invalid output", - expError: true, - errContains: "error unmarshalling delegations", - }, - } - - for _, tc := range testcases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - delegations, err := utils.ParseDelegationsFromResponse(cdc, tc.out) - if tc.expError { - require.Error(t, err, "expected error parsing delegations") - require.ErrorContains(t, err, tc.errContains, "expected different error") - } else { - require.NoError(t, err, "unexpected error parsing delegations") - - var vals []string - for _, delegation := range delegations { - vals = append(vals, delegation.ValidatorAddress) - } - require.Equal(t, tc.expVals, vals, "expected different validators") - } - }) - } -} From bad98757777c0f0fbb3a8480aa9b8f07f13a0904 Mon Sep 17 00:00:00 2001 From: MalteHerrmann Date: Sun, 17 Dec 2023 20:33:15 +0100 Subject: [PATCH 4/6] get min deposit from governance params --- gov/deposit.go | 45 +++++++++++++++++++++++++++++++++++++--- gov/deposit_test.go | 50 +++++++++++++++++++++++++++++++++++++++++++++ main.go | 8 ++++++-- 3 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 gov/deposit_test.go diff --git a/gov/deposit.go b/gov/deposit.go index b604234..bfd7c33 100644 --- a/gov/deposit.go +++ b/gov/deposit.go @@ -2,18 +2,20 @@ package gov import ( "fmt" + "regexp" "strconv" "github.com/MalteHerrmann/upgrade-local-node-go/utils" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/pkg/errors" ) -// DepositForProposal deposits the given amount of Evmos for the proposal with the given proposalID +// DepositForProposal deposits the given amount for the proposal with the given proposalID // from the given account. -func DepositForProposal(bin *utils.Binary, proposalID int, sender string, amount int) (string, error) { +func DepositForProposal(bin *utils.Binary, proposalID int, sender, deposit string) (string, error) { out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ Subcommand: []string{ - "tx", "gov", "deposit", strconv.Itoa(proposalID), strconv.Itoa(amount) + "aevmos", + "tx", "gov", "deposit", strconv.Itoa(proposalID), deposit, }, From: sender, UseDefaults: true, @@ -25,3 +27,40 @@ func DepositForProposal(bin *utils.Binary, proposalID int, sender string, amount return out, nil } + +// GetMinDeposit returns the minimum deposit necessary for a proposal from the governance parameters of +// the running chain. +func GetMinDeposit(bin *utils.Binary) (sdk.Coins, error) { + out, err := utils.ExecuteBinaryCmd(bin, utils.BinaryCmdArgs{ + Subcommand: []string{"q", "gov", "param", "deposit", "--output=json"}, + Quiet: true, + }) + if err != nil { + return sdk.Coins{}, errors.Wrap(err, "failed to query governance parameters") + } + + return ParseMinDepositFromResponse(out) +} + +// ParseMinDepositFromResponse parses the minimum deposit from the given output of the governance +// parameters query. +// +// FIXME: It wasn't possible to unmarshal the JSON output of the query because of a missing unit in the max_deposit_period +// parameter. This should rather be done using GRPC. +func ParseMinDepositFromResponse(out string) (sdk.Coins, error) { + // FIXME: This is a workaround for the missing unit in the max_deposit_period parameter. Should be done with gRPC. + depositPatternRaw := `min_deposit":\[{"denom":"(\w+)","amount":"(\d+)` + depositPattern := regexp.MustCompile(depositPatternRaw) + minDepositMatch := depositPattern.FindStringSubmatch(out) + if len(minDepositMatch) == 0 { + return sdk.Coins{}, fmt.Errorf("failed to find min deposit in params output: %q", out) + } + + minDepositDenom := minDepositMatch[1] + minDepositAmount, err := strconv.Atoi(minDepositMatch[2]) + if err != nil { + return sdk.Coins{}, fmt.Errorf("failed to find min deposit in params output: %q", out) + } + + return sdk.Coins{sdk.NewInt64Coin(minDepositDenom, int64(minDepositAmount))}, nil +} diff --git a/gov/deposit_test.go b/gov/deposit_test.go new file mode 100644 index 0000000..fd561fe --- /dev/null +++ b/gov/deposit_test.go @@ -0,0 +1,50 @@ +package gov_test + +import ( + "testing" + + "github.com/MalteHerrmann/upgrade-local-node-go/gov" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func TestParseMinDepositFromResponse(t *testing.T) { + t.Parallel() + + testcases := []struct { + name string + out string + expMinDeposit sdk.Coins + expError bool + errContains string + }{ + { + name: "pass", + //nolint:lll // line length is okay here + out: `{"min_deposit":[{"denom":"aevmos","amount":"10000000"}],"max_deposit_period":"30000000000"}`, + expMinDeposit: sdk.Coins{sdk.NewInt64Coin("aevmos", 10000000)}, + }, + { + name: "fail - no min deposit", + out: "invalid output", + expError: true, + errContains: "failed to find min deposit in params output", + }, + } + + for _, tc := range testcases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + minDeposit, err := gov.ParseMinDepositFromResponse(tc.out) + if tc.expError { + require.Error(t, err, "expected error parsing min deposit") + require.ErrorContains(t, err, tc.errContains, "expected different error") + } else { + require.NoError(t, err, "unexpected error parsing min deposit") + require.Equal(t, tc.expMinDeposit, minDeposit, "expected different min deposit") + } + }) + } +} diff --git a/main.go b/main.go index ac45d02..b5ba5da 100644 --- a/main.go +++ b/main.go @@ -47,13 +47,17 @@ func main() { } case "deposit": + deposit, err := gov.GetMinDeposit(bin) + if err != nil { + log.Fatalf("error getting minimum deposit: %v", err) + } + proposalID, err := getProposalIDFromInput(bin, os.Args) if err != nil { log.Fatalf("error getting proposal ID: %v", err) } - // TODO: replace fixed amount with min deposit from chain params - if _, err = gov.DepositForProposal(bin, proposalID, bin.Accounts[0].Name, 1e9); err != nil { + if _, err = gov.DepositForProposal(bin, proposalID, bin.Accounts[0].Name, deposit.String()); err != nil { log.Fatalf("error depositing for proposal %d: %v", proposalID, err) } From 92d0e5881a4725327758bb51399d2e44b72590fd Mon Sep 17 00:00:00 2001 From: MalteHerrmann Date: Sun, 17 Dec 2023 20:37:41 +0100 Subject: [PATCH 5/6] add changelog entry --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f92e75..0c7f3c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ # Changelog +## Unreleased + +### Features + +- [#26](https://github.com/MalteHerrmann/upgrade-local-node-go/pull/26) Enable just depositing with the binary + ## [v0.3.0](https://github.com/MalteHerrmann/upgrade-local-node-go/releases/tag/v0.3.0) - 2023-08-30 ### Features From 4951b29574ca2d9fcd3f71ad09bbed4cf0f767ff Mon Sep 17 00:00:00 2001 From: MalteHerrmann Date: Sun, 17 Dec 2023 20:42:42 +0100 Subject: [PATCH 6/6] address linters --- gov/deposit.go | 2 ++ gov/deposit_test.go | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/gov/deposit.go b/gov/deposit.go index bfd7c33..1a519ea 100644 --- a/gov/deposit.go +++ b/gov/deposit.go @@ -51,12 +51,14 @@ func ParseMinDepositFromResponse(out string) (sdk.Coins, error) { // FIXME: This is a workaround for the missing unit in the max_deposit_period parameter. Should be done with gRPC. depositPatternRaw := `min_deposit":\[{"denom":"(\w+)","amount":"(\d+)` depositPattern := regexp.MustCompile(depositPatternRaw) + minDepositMatch := depositPattern.FindStringSubmatch(out) if len(minDepositMatch) == 0 { return sdk.Coins{}, fmt.Errorf("failed to find min deposit in params output: %q", out) } minDepositDenom := minDepositMatch[1] + minDepositAmount, err := strconv.Atoi(minDepositMatch[2]) if err != nil { return sdk.Coins{}, fmt.Errorf("failed to find min deposit in params output: %q", out) diff --git a/gov/deposit_test.go b/gov/deposit_test.go index fd561fe..88ecd3d 100644 --- a/gov/deposit_test.go +++ b/gov/deposit_test.go @@ -19,8 +19,7 @@ func TestParseMinDepositFromResponse(t *testing.T) { errContains string }{ { - name: "pass", - //nolint:lll // line length is okay here + name: "pass", out: `{"min_deposit":[{"denom":"aevmos","amount":"10000000"}],"max_deposit_period":"30000000000"}`, expMinDeposit: sdk.Coins{sdk.NewInt64Coin("aevmos", 10000000)}, },