feat(gov): autocli query support (backport #16987) (#16999)

Co-authored-by: Julien Robert <julien@rbrt.fr>
This commit is contained in:
mergify[bot] 2023-07-14 09:43:56 +00:00 committed by GitHub
parent 1018f5346f
commit 93a995ca0c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 150 additions and 1605 deletions

View File

@ -70,6 +70,12 @@ Ref: https://keepachangelog.com/en/1.0.0/
### CLI Breaking Changes
* (all) Query pagination flags have been renamed with the migration to AutoCLI:
* `--limit` -> `--page-limit`
* `--offset` -> `--page-offset`
* `--count-total` -> `--page-count-total`
* `--reverse` -> `--page-reverse`
* (x/gov) [#16987](https://github.com/cosmos/cosmos-sdk/pull/16987) In `<appd> query gov proposals` the proposal status flag have renamed from `--status` to `--proposal-status`. Additonally, that flags now uses the ENUM values: `PROPOSAL_STATUS_DEPOSIT_PERIOD`, `PROPOSAL_STATUS_VOTING_PERIOD`, `PROPOSAL_STATUS_PASSED`, `PROPOSAL_STATUS_REJECTED`, `PROPOSAL_STATUS_FAILED`.
* (x/bank) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) With the migration to AutoCLI some bank commands have been split in two:
* Use `denoms-metadata` for querying all denom metadata and `denom-metadata` for querying a specific denom metadata.
* Use `total-supply` (or `total`) for querying the total supply and `total-supply-of` for querying the supply of a specific denom.

View File

@ -992,7 +992,6 @@ func (s *E2ETestSuite) TestCLIMultisign() {
var balRes banktypes.QueryAllBalancesResponse
err = s.network.RetryForBlocks(func() error {
resp, err := testutil.GetRequest(fmt.Sprintf("%s/cosmos/bank/v1beta1/balances/%s", val1.APIAddress, addr))
s.Require().NoError(err)
if err != nil {
return err
}

View File

@ -9,10 +9,7 @@ import (
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec/address"
"github.com/cosmos/cosmos-sdk/testutil"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
"github.com/cosmos/cosmos-sdk/testutil/network"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/gov/client/cli"
@ -59,14 +56,12 @@ func (s *DepositTestSuite) submitProposal(val *network.Validator, initialDeposit
s.Require().NoError(s.network.WaitForNextBlock())
// query proposals, return the last's id
cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos"))
args := []string{fmt.Sprintf("--%s=json", flags.FlagOutput)}
res, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
res, err := testutil.GetRequest(fmt.Sprintf("%s/cosmos/gov/v1/proposals", val.APIAddress))
s.Require().NoError(err)
var proposals v1.QueryProposalsResponse
err = s.cfg.Codec.UnmarshalJSON(res.Bytes(), &proposals)
err = s.cfg.Codec.UnmarshalJSON(res, &proposals)
s.Require().NoError(err)
s.Require().GreaterOrEqual(len(proposals.Proposals), 1)
return proposals.Proposals[len(proposals.Proposals)-1].Id
}
@ -93,14 +88,14 @@ func (s *DepositTestSuite) TestQueryDepositsWithoutInitialDeposit() {
// query deposit
deposit := s.queryDeposit(val, proposalID, false, "")
s.Require().NotNil(deposit)
s.Require().Equal(sdk.Coins(deposit.Amount).String(), depositAmount)
s.Require().Equal(depositAmount, sdk.Coins(deposit.Deposit.Amount).String())
// query deposits
deposits := s.queryDeposits(val, proposalID, false, "")
s.Require().NotNil(deposits)
s.Require().Len(deposits.Deposits, 1)
// verify initial deposit
s.Require().Equal(sdk.Coins(deposits.Deposits[0].Amount).String(), depositAmount)
s.Require().Equal(depositAmount, sdk.Coins(deposits.Deposits[0].Amount).String())
}
func (s *DepositTestSuite) TestQueryDepositsWithInitialDeposit() {
@ -114,14 +109,14 @@ func (s *DepositTestSuite) TestQueryDepositsWithInitialDeposit() {
// query deposit
deposit := s.queryDeposit(val, proposalID, false, "")
s.Require().NotNil(deposit)
s.Require().Equal(sdk.Coins(deposit.Amount).String(), depositAmount.String())
s.Require().Equal(depositAmount.String(), sdk.Coins(deposit.Deposit.Amount).String())
// query deposits
deposits := s.queryDeposits(val, proposalID, false, "")
s.Require().NotNil(deposits)
s.Require().Len(deposits.Deposits, 1)
// verify initial deposit
s.Require().Equal(sdk.Coins(deposits.Deposits[0].Amount).String(), depositAmount.String())
s.Require().Equal(depositAmount.String(), sdk.Coins(deposits.Deposits[0].Amount).String())
}
func (s *DepositTestSuite) TestQueryProposalAfterVotingPeriod() {
@ -132,80 +127,65 @@ func (s *DepositTestSuite) TestQueryProposalAfterVotingPeriod() {
id := s.submitProposal(val, depositAmount, "TestQueryProposalAfterVotingPeriod")
proposalID := strconv.FormatUint(id, 10)
args := []string{fmt.Sprintf("--%s=json", flags.FlagOutput)}
cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos"))
_, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
resp, err := testutil.GetRequest(fmt.Sprintf("%s/cosmos/gov/v1/proposals", val.APIAddress))
s.Require().NoError(err)
var proposals v1.QueryProposalsResponse
err = s.cfg.Codec.UnmarshalJSON(resp, &proposals)
s.Require().NoError(err)
s.Require().GreaterOrEqual(len(proposals.Proposals), 1)
// query proposal
args = []string{proposalID, fmt.Sprintf("--%s=json", flags.FlagOutput)}
cmd = cli.GetCmdQueryProposal()
_, err = clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
resp, err = testutil.GetRequest(fmt.Sprintf("%s/cosmos/gov/v1/proposals/%s", val.APIAddress, proposalID))
s.Require().NoError(err)
var proposal v1.QueryProposalResponse
err = s.cfg.Codec.UnmarshalJSON(resp, &proposal)
s.Require().NoError(err)
// waiting for deposit and voting period to end
time.Sleep(25 * time.Second)
// query proposal
_, err = clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
s.Require().Error(err)
s.Require().Contains(err.Error(), fmt.Sprintf("proposal %s doesn't exist", proposalID))
resp, err = testutil.GetRequest(fmt.Sprintf("%s/cosmos/gov/v1/proposals/%s", val.APIAddress, proposalID))
s.Require().NoError(err)
s.Require().Contains(string(resp), fmt.Sprintf("proposal %s doesn't exist", proposalID))
// query deposits
deposits := s.queryDeposits(val, proposalID, true, "proposal 3 doesn't exist")
s.Require().Nil(deposits)
deposits := s.queryDeposits(val, proposalID, false, "")
s.Require().Len(deposits.Deposits, 0)
}
func (s *DepositTestSuite) queryDeposits(val *network.Validator, proposalID string, exceptErr bool, message string) *v1.QueryDepositsResponse {
args := []string{proposalID, fmt.Sprintf("--%s=json", flags.FlagOutput)}
var depositsRes *v1.QueryDepositsResponse
cmd := cli.GetCmdQueryDeposits()
s.Require().NoError(s.network.WaitForNextBlock())
var (
out testutil.BufferWriter
err error
)
err = s.network.RetryForBlocks(func() error {
out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
if err == nil {
err = val.ClientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), &depositsRes)
return err
}
return err
}, 3)
resp, err := testutil.GetRequest(fmt.Sprintf("%s/cosmos/gov/v1/proposals/%s/deposits", val.APIAddress, proposalID))
s.Require().NoError(err)
if exceptErr {
s.Require().Error(err)
s.Require().Contains(err.Error(), message)
s.Require().Contains(string(resp), message)
return nil
}
var depositsRes v1.QueryDepositsResponse
err = val.ClientCtx.Codec.UnmarshalJSON(resp, &depositsRes)
s.Require().NoError(err)
return depositsRes
return &depositsRes
}
func (s *DepositTestSuite) queryDeposit(val *network.Validator, proposalID string, exceptErr bool, message string) *v1.Deposit {
args := []string{proposalID, val.Address.String(), fmt.Sprintf("--%s=json", flags.FlagOutput)}
var depositRes *v1.Deposit
cmd := cli.GetCmdQueryDeposit()
var (
out testutil.BufferWriter
err error
)
func (s *DepositTestSuite) queryDeposit(val *network.Validator, proposalID string, exceptErr bool, message string) *v1.QueryDepositResponse {
s.Require().NoError(s.network.WaitForNextBlock())
err = s.network.RetryForBlocks(func() error {
out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
return err
}, 3)
resp, err := testutil.GetRequest(fmt.Sprintf("%s/cosmos/gov/v1/proposals/%s/deposits/%s", val.APIAddress, proposalID, val.Address.String()))
s.Require().NoError(err)
if exceptErr {
s.Require().Error(err)
s.Require().Contains(err.Error(), message)
s.Require().Contains(string(resp), message)
return nil
}
s.Require().NoError(err)
s.Require().NoError(val.ClientCtx.LegacyAmino.UnmarshalJSON(out.Bytes(), &depositRes))
return depositRes
var depositRes v1.QueryDepositResponse
err = val.ClientCtx.Codec.UnmarshalJSON(resp, &depositRes)
s.Require().NoError(err)
return &depositRes
}

View File

@ -4,131 +4,11 @@ import (
"fmt"
"strings"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec/address"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/gov/client/cli"
v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
"github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
)
func (s *E2ETestSuite) TestCmdParams() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectedOutput string
}{
{
"json output",
[]string{fmt.Sprintf("--%s=json", flags.FlagOutput)},
`{"voting_params":{"voting_period":"172800s"},"deposit_params":{"min_deposit":[{"denom":"stake","amount":"10000000"}],"max_deposit_period":"172800s"},"tally_params":{"quorum":"0.334000000000000000","threshold":"0.500000000000000000","veto_threshold":"0.334000000000000000"},"params":{"min_deposit":[{"denom":"stake","amount":"10000000"}],"max_deposit_period":"172800s","voting_period":"172800s","quorum":"0.334000000000000000","threshold":"0.500000000000000000","veto_threshold":"0.334000000000000000","min_initial_deposit_ratio":"0.000000000000000000","proposal_cancel_ratio":"0.500000000000000000","proposal_cancel_dest":"","expedited_voting_period":"86400s","expedited_threshold":"0.667000000000000000","expedited_min_deposit":[{"denom":"stake","amount":"50000000"}],"burn_vote_quorum":false,"burn_proposal_deposit_prevote":false,"burn_vote_veto":true}}`,
},
{
"text output",
[]string{},
`
deposit_params:
max_deposit_period: 172800s
min_deposit:
- amount: "10000000"
denom: stake
params:
burn_proposal_deposit_prevote: false
burn_vote_quorum: false
burn_vote_veto: true
expedited_min_deposit:
- amount: "50000000"
denom: stake
expedited_threshold: "0.667000000000000000"
expedited_voting_period: 86400s
max_deposit_period: 172800s
min_deposit:
- amount: "10000000"
denom: stake
min_initial_deposit_ratio: "0.000000000000000000"
proposal_cancel_dest: ""
proposal_cancel_ratio: "0.500000000000000000"
quorum: "0.334000000000000000"
threshold: "0.500000000000000000"
veto_threshold: "0.334000000000000000"
voting_period: 172800s
tally_params:
quorum: "0.334000000000000000"
threshold: "0.500000000000000000"
veto_threshold: "0.334000000000000000"
voting_params:
voting_period: 172800s
`,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryParams()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
s.Require().NoError(err)
s.Require().Equal(strings.TrimSpace(tc.expectedOutput), strings.TrimSpace(out.String()))
})
}
}
func (s *E2ETestSuite) TestCmdParam() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectedOutput string
}{
{
"voting params",
[]string{
"voting",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
`{"voting_period":"172800000000000"}`,
},
{
"tally params",
[]string{
"tallying",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
`{"quorum":"0.334000000000000000","threshold":"0.500000000000000000","veto_threshold":"0.334000000000000000"}`,
},
{
"deposit params",
[]string{
"deposit",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
`{"min_deposit":[{"denom":"stake","amount":"10000000"}],"max_deposit_period":"172800000000000"}`,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryParam()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
s.Require().NoError(err)
s.Require().Equal(strings.TrimSpace(tc.expectedOutput), strings.TrimSpace(out.String()))
})
}
}
func (s *E2ETestSuite) TestCmdProposer() {
val := s.network.Validators[0]
@ -174,385 +54,3 @@ func (s *E2ETestSuite) TestCmdProposer() {
})
}
}
func (s *E2ETestSuite) TestCmdTally() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectErr bool
expectedOutput v1.TallyResult
}{
{
"without proposal id",
[]string{
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
true,
v1.TallyResult{},
},
{
"json output",
[]string{
"2",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
v1.NewTallyResult(math.NewInt(0), math.NewInt(0), math.NewInt(0), math.NewInt(0)),
},
{
"json output",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
v1.NewTallyResult(s.cfg.BondedTokens, math.NewInt(0), math.NewInt(0), math.NewInt(0)),
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryTally()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
var tally v1.TallyResult
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &tally), out.String())
s.Require().Equal(tally, tc.expectedOutput)
}
})
}
}
func (s *E2ETestSuite) TestCmdGetProposal() {
val := s.network.Validators[0]
title := "Text Proposal 1"
testCases := []struct {
name string
args []string
expectErr bool
}{
{
"get non existing proposal",
[]string{
"10",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
true,
},
{
"get proposal with json response",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryProposal()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
var proposal v1.Proposal
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &proposal), out.String())
s.Require().Equal(title, proposal.Messages[0].GetCachedValue().(*v1.MsgExecLegacyContent).Content.GetCachedValue().(v1beta1.Content).GetTitle())
}
})
}
}
func (s *E2ETestSuite) TestCmdGetProposals() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectErr bool
}{
{
"get proposals as json response",
[]string{
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
},
{
"get proposals with invalid status",
[]string{
"--status=unknown",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
true,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos"))
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
var proposals v1.QueryProposalsResponse
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &proposals), out.String())
s.Require().Greater(len(proposals.Proposals), 0)
}
})
}
}
func (s *E2ETestSuite) TestCmdQueryDeposits() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectErr bool
}{
{
"get deposits of non existing proposal",
[]string{
"10",
},
true,
},
{
"get deposits(valid req)",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryDeposits()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
var deposits v1.QueryDepositsResponse
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &deposits), out.String())
s.Require().Len(deposits.Deposits, 1)
}
})
}
}
func (s *E2ETestSuite) TestCmdQueryDeposit() {
val := s.network.Validators[0]
depositAmount := sdk.NewCoin(s.cfg.BondDenom, v1.DefaultMinDepositTokens)
testCases := []struct {
name string
args []string
expectErr bool
}{
{
"get deposit with no depositer",
[]string{
"1",
},
true,
},
{
"get deposit with wrong deposit address",
[]string{
"1",
"wrong address",
},
true,
},
{
"get deposit (valid req)",
[]string{
"1",
val.Address.String(),
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryDeposit()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
var deposit v1.Deposit
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &deposit), out.String())
s.Require().Equal(depositAmount.String(), sdk.Coins(deposit.Amount).String())
}
})
}
}
func (s *E2ETestSuite) TestCmdQueryVotes() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectErr bool
}{
{
"get votes with no proposal id",
[]string{},
true,
},
{
"get votes of non existed proposal",
[]string{
"10",
},
true,
},
{
"vote for invalid proposal",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryVotes()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
var votes v1.QueryVotesResponse
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &votes), out.String())
s.Require().Len(votes.Votes, 1)
}
})
}
}
func (s *E2ETestSuite) TestCmdQueryVote() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
expectErr bool
expVoteOptions v1.WeightedVoteOptions
}{
{
"get vote of non existing proposal",
[]string{
"10",
val.Address.String(),
},
true,
v1.NewNonSplitVoteOption(v1.OptionYes),
},
{
"get vote by wrong voter",
[]string{
"1",
"wrong address",
},
true,
v1.NewNonSplitVoteOption(v1.OptionYes),
},
{
"vote for valid proposal",
[]string{
"1",
val.Address.String(),
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
v1.NewNonSplitVoteOption(v1.OptionYes),
},
{
"split vote for valid proposal",
[]string{
"3",
val.Address.String(),
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
false,
v1.WeightedVoteOptions{
&v1.WeightedVoteOption{Option: v1.OptionYes, Weight: math.LegacyNewDecWithPrec(60, 2).String()},
&v1.WeightedVoteOption{Option: v1.OptionNo, Weight: math.LegacyNewDecWithPrec(30, 2).String()},
&v1.WeightedVoteOption{Option: v1.OptionAbstain, Weight: math.LegacyNewDecWithPrec(5, 2).String()},
&v1.WeightedVoteOption{Option: v1.OptionNoWithVeto, Weight: math.LegacyNewDecWithPrec(5, 2).String()},
},
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryVote(address.NewBech32Codec("cosmos"))
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
var vote v1.Vote
s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &vote), out.String())
s.Require().Equal(len(vote.Options), len(tc.expVoteOptions))
for i, option := range tc.expVoteOptions {
s.Require().Equal(option.Option, vote.Options[i].Option)
s.Require().Equal(option.Weight, vote.Options[i].Weight)
}
}
})
}
}

View File

@ -1,14 +1,101 @@
package gov
import (
"fmt"
autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
govv1 "cosmossdk.io/api/cosmos/gov/v1"
govv1beta1 "cosmossdk.io/api/cosmos/gov/v1beta1"
"github.com/cosmos/cosmos-sdk/version"
)
// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface.
func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
return &autocliv1.ModuleOptions{
Query: &autocliv1.ServiceCommandDescriptor{
Service: govv1.Query_ServiceDesc.ServiceName,
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "Params",
Use: "params",
Short: "Query the parameters of the governance process",
Long: "Query the parameters of the governance process. Specify specific param types (voting|tallying|deposit) to filter results.",
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "params_type", Optional: true},
},
},
{
RpcMethod: "Proposals",
Use: "proposals",
Short: "Query proposals with optional filters",
Example: fmt.Sprintf("%[1]s query gov proposals --depositor cosmos1...\n%[1]s query gov proposals --voter cosmos1...\n%[1]s query gov proposals --proposal-status (PROPOSAL_STATUS_DEPOSIT_PERIOD|PROPOSAL_STATUS_VOTING_PERIOD|PROPOSAL_STATUS_PASSED|PROPOSAL_STATUS_REJECTED|PROPOSAL_STATUS_FAILED)", version.AppName),
},
{
RpcMethod: "Proposal",
Use: "proposal [proposal-id]",
Short: "Query details of a single proposal",
Example: fmt.Sprintf("%s query gov proposal 1", version.AppName),
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "proposal_id"},
},
},
{
RpcMethod: "Vote",
Use: "vote [proposal-id] [voter-addr]",
Short: "Query details of a single vote",
Example: fmt.Sprintf("%s query gov vote 1 cosmos1...", version.AppName),
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "proposal_id"},
{ProtoField: "voter"},
},
},
{
RpcMethod: "Votes",
Use: "votes [proposal-id]",
Short: "Query votes of a single proposal",
Example: fmt.Sprintf("%s query gov votes 1", version.AppName),
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "proposal_id"},
},
},
{
RpcMethod: "Deposit",
Use: "deposit [proposal-id] [depositer-addr]",
Short: "Query details of a deposit",
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "proposal_id"},
{ProtoField: "depositor"},
},
},
{
RpcMethod: "Deposits",
Use: "deposits [proposal-id]",
Short: "Query deposits on a proposal",
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "proposal_id"},
},
},
{
RpcMethod: "TallyResult",
Use: "tally [proposal-id]",
Short: "Query the tally of a proposal vote",
Example: fmt.Sprintf("%s query gov tally 1", version.AppName),
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "proposal_id"},
},
},
{
RpcMethod: "Constitution",
Use: "constitution",
Short: "Query the current chain constitution",
},
},
// map v1beta1 as a sub-command
SubCommands: map[string]*autocliv1.ServiceCommandDescriptor{
"v1beta1": {Service: govv1beta1.Query_ServiceDesc.ServiceName},
},
},
Tx: &autocliv1.ServiceCommandDescriptor{
Service: govv1.Msg_ServiceDesc.ServiceName,
// map v1beta1 as a sub-command
@ -16,12 +103,5 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
"v1beta1": {Service: govv1beta1.Msg_ServiceDesc.ServiceName},
},
},
Query: &autocliv1.ServiceCommandDescriptor{
Service: govv1.Query_ServiceDesc.ServiceName,
// map v1beta1 as a sub-command
SubCommands: map[string]*autocliv1.ServiceCommandDescriptor{
"v1beta1": {Service: govv1beta1.Query_ServiceDesc.ServiceName},
},
},
}
}

View File

@ -3,7 +3,6 @@ package cli
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
@ -14,11 +13,12 @@ import (
"github.com/cosmos/cosmos-sdk/version"
gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils"
"github.com/cosmos/cosmos-sdk/x/gov/types"
v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
)
// GetQueryCmd returns the cli query commands for this module
func GetQueryCmd(ac address.Codec) *cobra.Command {
// GetCustomQueryCmd returns the cli query commands for this module
// These commands do not rely on gRPC and cannot be autogenerated
// TODO(@julienrbrt) https://github.com/cosmos/cosmos-sdk/issues/16836
func GetCustomQueryCmd(ac address.Codec) *cobra.Command {
// Group gov queries under a subcommand
govQueryCmd := &cobra.Command{
Use: types.ModuleName,
@ -29,606 +29,20 @@ func GetQueryCmd(ac address.Codec) *cobra.Command {
}
govQueryCmd.AddCommand(
GetCmdQueryProposal(),
GetCmdQueryProposals(ac),
GetCmdQueryVote(ac),
GetCmdQueryVotes(),
GetCmdQueryParams(),
GetCmdQueryParam(),
GetCmdQueryProposer(),
GetCmdQueryDeposit(),
GetCmdQueryDeposits(),
GetCmdQueryTally(),
GetCmdConstitution(),
)
return govQueryCmd
}
// GetCmdQueryProposal implements the query proposal command.
func GetCmdQueryProposal() *cobra.Command {
cmd := &cobra.Command{
Use: "proposal [proposal-id]",
Args: cobra.ExactArgs(1),
Short: "Query details of a single proposal",
Long: strings.TrimSpace(
fmt.Sprintf(`Query details for a proposal. You can find the
proposal-id by running "%s query gov proposals".
Example:
$ %s query gov proposal 1
`,
version.AppName, version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// validate that the proposal id is a uint
proposalID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return fmt.Errorf("proposal-id %s not a valid uint, please input a valid proposal-id", args[0])
}
// Query the proposal
res, err := queryClient.Proposal(
cmd.Context(),
&v1.QueryProposalRequest{ProposalId: proposalID},
)
if err != nil {
return err
}
return clientCtx.PrintProto(res.Proposal)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryProposals implements a query proposals command. Command to Get
// Proposals Information.
func GetCmdQueryProposals(ac address.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "proposals",
Short: "Query proposals with optional filters",
Long: strings.TrimSpace(
fmt.Sprintf(`Query for a all paginated proposals that match optional filters:
Example:
$ %s query gov proposals --depositor cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk
$ %s query gov proposals --voter cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk
$ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected)
$ %s query gov proposals --page=2 --limit=100
`,
version.AppName, version.AppName, version.AppName, version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
bechDepositorAddr, _ := cmd.Flags().GetString(flagDepositor)
bechVoterAddr, _ := cmd.Flags().GetString(flagVoter)
strProposalStatus, _ := cmd.Flags().GetString(flagStatus)
var proposalStatus v1.ProposalStatus
if len(bechDepositorAddr) != 0 {
_, err := ac.StringToBytes(bechDepositorAddr)
if err != nil {
return err
}
}
if len(bechVoterAddr) != 0 {
_, err := ac.StringToBytes(bechVoterAddr)
if err != nil {
return err
}
}
if len(strProposalStatus) != 0 {
proposalStatus1, err := v1.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus))
proposalStatus = proposalStatus1
if err != nil {
return err
}
}
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
pageReq, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
res, err := queryClient.Proposals(
cmd.Context(),
&v1.QueryProposalsRequest{
ProposalStatus: proposalStatus,
Voter: bechVoterAddr,
Depositor: bechDepositorAddr,
Pagination: pageReq,
},
)
if err != nil {
return err
}
if len(res.GetProposals()) == 0 {
return fmt.Errorf("no proposals found")
}
return clientCtx.PrintProto(res)
},
}
cmd.Flags().String(flagDepositor, "", "(optional) filter by proposals deposited on by depositor")
cmd.Flags().String(flagVoter, "", "(optional) filter by proposals voted on by voted")
cmd.Flags().String(flagStatus, "", "(optional) filter proposals by proposal status, status: deposit_period/voting_period/passed/rejected")
flags.AddPaginationFlagsToCmd(cmd, "proposals")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryVote implements the query proposal vote command. Command to Get a
// Vote Information.
func GetCmdQueryVote(ac address.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "vote [proposal-id] [voter-addr]",
Args: cobra.ExactArgs(2),
Short: "Query details of a single vote",
Long: strings.TrimSpace(
fmt.Sprintf(`Query details for a single vote on a proposal given its identifier.
Example:
$ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk
`,
version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// validate that the proposal id is a uint
proposalID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return fmt.Errorf("proposal-id %s not a valid int, please input a valid proposal-id", args[0])
}
// check to see if the proposal is in the store
ctx := cmd.Context()
_, err = queryClient.Proposal(
ctx,
&v1.QueryProposalRequest{ProposalId: proposalID},
)
if err != nil {
return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err)
}
voterAddr, err := ac.StringToBytes(args[1])
if err != nil {
return err
}
res, err := queryClient.Vote(
ctx,
&v1.QueryVoteRequest{ProposalId: proposalID, Voter: args[1]},
)
if err != nil {
return err
}
vote := res.GetVote()
if vote.Empty() {
params := v1.NewQueryVoteParams(proposalID, voterAddr)
resByTxQuery, err := gcutils.QueryVoteByTxQuery(clientCtx, params)
if err != nil {
return err
}
if err := clientCtx.Codec.UnmarshalJSON(resByTxQuery, vote); err != nil {
return err
}
}
return clientCtx.PrintProto(res.Vote)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryVotes implements the command to query for proposal votes.
func GetCmdQueryVotes() *cobra.Command {
cmd := &cobra.Command{
Use: "votes [proposal-id]",
Args: cobra.ExactArgs(1),
Short: "Query votes on a proposal",
Long: strings.TrimSpace(
fmt.Sprintf(`Query vote details for a single proposal by its identifier.
Example:
$ %[1]s query gov votes 1
$ %[1]s query gov votes 1 --page=2 --limit=100
`,
version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// validate that the proposal id is a uint
proposalID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return fmt.Errorf("proposal-id %s not a valid int, please input a valid proposal-id", args[0])
}
// check to see if the proposal is in the store
ctx := cmd.Context()
proposalRes, err := queryClient.Proposal(
ctx,
&v1.QueryProposalRequest{ProposalId: proposalID},
)
if err != nil {
return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err)
}
propStatus := proposalRes.GetProposal().Status
if !(propStatus == v1.StatusVotingPeriod || propStatus == v1.StatusDepositPeriod) {
page, _ := cmd.Flags().GetInt(flags.FlagPage)
limit, _ := cmd.Flags().GetInt(flags.FlagLimit)
params := v1.NewQueryProposalVotesParams(proposalID, page, limit)
resByTxQuery, err := gcutils.QueryVotesByTxQuery(clientCtx, params)
if err != nil {
return err
}
var votes v1.Votes
// TODO migrate to use JSONCodec (implement MarshalJSONArray
// or wrap lists of proto.Message in some other message)
clientCtx.LegacyAmino.MustUnmarshalJSON(resByTxQuery, &votes)
return clientCtx.PrintObjectLegacy(votes)
}
pageReq, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
res, err := queryClient.Votes(
ctx,
&v1.QueryVotesRequest{ProposalId: proposalID, Pagination: pageReq},
)
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddPaginationFlagsToCmd(cmd, "votes")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryDeposit implements the query proposal deposit command. Command to
// get a specific Deposit Information.
func GetCmdQueryDeposit() *cobra.Command {
cmd := &cobra.Command{
Use: "deposit [proposal-id] [depositer-addr]",
Args: cobra.ExactArgs(2),
Short: "Query details of a deposit",
Long: strings.TrimSpace(
fmt.Sprintf(`Query details for a single proposal deposit on a proposal by its identifier.
Example:
$ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk
`,
version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// validate that the proposal id is a uint
proposalID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return fmt.Errorf("proposal-id %s not a valid uint, please input a valid proposal-id", args[0])
}
// check to see if the proposal is in the store
ctx := cmd.Context()
_, err = queryClient.Proposal(
ctx,
&v1.QueryProposalRequest{ProposalId: proposalID},
)
if err != nil {
return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err)
}
res, err := queryClient.Deposit(
ctx,
&v1.QueryDepositRequest{ProposalId: proposalID, Depositor: args[1]},
)
if err != nil {
return err
}
return clientCtx.PrintProto(res.Deposit)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryDeposits implements the command to query for proposal deposits.
func GetCmdQueryDeposits() *cobra.Command {
cmd := &cobra.Command{
Use: "deposits [proposal-id]",
Args: cobra.ExactArgs(1),
Short: "Query deposits on a proposal",
Long: strings.TrimSpace(
fmt.Sprintf(`Query details for all deposits on a proposal.
You can find the proposal-id by running "%s query gov proposals".
Example:
$ %s query gov deposits 1
`,
version.AppName, version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// validate that the proposal id is a uint
proposalID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return fmt.Errorf("proposal-id %s not a valid uint, please input a valid proposal-id", args[0])
}
// check to see if the proposal is in the store
ctx := cmd.Context()
_, err = queryClient.Proposal(
ctx,
&v1.QueryProposalRequest{ProposalId: proposalID},
)
if err != nil {
return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err)
}
pageReq, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
res, err := queryClient.Deposits(
ctx,
&v1.QueryDepositsRequest{ProposalId: proposalID, Pagination: pageReq},
)
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddPaginationFlagsToCmd(cmd, "deposits")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryTally implements the command to query for proposal tally result.
func GetCmdQueryTally() *cobra.Command {
cmd := &cobra.Command{
Use: "tally [proposal-id]",
Args: cobra.ExactArgs(1),
Short: "Get the tally of a proposal vote",
Long: strings.TrimSpace(
fmt.Sprintf(`Query tally of votes on a proposal. You can find
the proposal-id by running "%s query gov proposals".
Example:
$ %s query gov tally 1
`,
version.AppName, version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// validate that the proposal id is a uint
proposalID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return fmt.Errorf("proposal-id %s not a valid int, please input a valid proposal-id", args[0])
}
// check to see if the proposal is in the store
ctx := cmd.Context()
_, err = queryClient.Proposal(
ctx,
&v1.QueryProposalRequest{ProposalId: proposalID},
)
if err != nil {
return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err)
}
// Query store
res, err := queryClient.TallyResult(
ctx,
&v1.QueryTallyResultRequest{ProposalId: proposalID},
)
if err != nil {
return err
}
return clientCtx.PrintProto(res.Tally)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryParams implements the query params command.
//
//nolint:staticcheck // this function contains deprecated commands that we need.
func GetCmdQueryParams() *cobra.Command {
cmd := &cobra.Command{
Use: "params",
Short: "Query the parameters of the governance process",
Long: strings.TrimSpace(
fmt.Sprintf(`Query the all the parameters for the governance process.
Example:
$ %s query gov params
`,
version.AppName,
),
),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// Query store for all 3 params
ctx := cmd.Context()
res, err := queryClient.Params(
ctx,
&v1.QueryParamsRequest{ParamsType: "deposit"},
)
if err != nil {
return err
}
vp := v1.NewVotingParams(res.Params.VotingPeriod)
res.VotingParams = &vp
tp := v1.NewTallyParams(res.Params.Quorum, res.Params.Threshold, res.Params.VetoThreshold)
res.TallyParams = &tp
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryParam implements the query param command.
func GetCmdQueryParam() *cobra.Command {
cmd := &cobra.Command{
Use: "param [param-type]",
Args: cobra.ExactArgs(1),
Short: "Query the parameters (voting|tallying|deposit) of the governance process",
Long: strings.TrimSpace(
fmt.Sprintf(`Query the all the parameters for the governance process.
Example:
$ %s query gov param voting
$ %s query gov param tallying
$ %s query gov param deposit
`,
version.AppName, version.AppName, version.AppName,
),
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
// Query store
res, err := queryClient.Params(
cmd.Context(),
&v1.QueryParamsRequest{ParamsType: args[0]},
)
if err != nil {
return err
}
var out fmt.Stringer
//nolint:staticcheck // this switch statement contains deprecated commands that we need.
switch args[0] {
case "voting":
out = res.GetVotingParams()
case "tallying":
out = res.GetTallyParams()
case "deposit":
out = res.GetDepositParams()
default:
return fmt.Errorf("argument must be one of (voting|tallying|deposit), was %s", args[0])
}
return clientCtx.PrintObjectLegacy(out)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetCmdQueryProposer implements the query proposer command.
func GetCmdQueryProposer() *cobra.Command {
cmd := &cobra.Command{
Use: "proposer [proposal-id]",
Args: cobra.ExactArgs(1),
Short: "Query the proposer of a governance proposal",
Long: strings.TrimSpace(
fmt.Sprintf(`Query which address proposed a proposal with a given ID.
Example:
$ %s query gov proposer 1
`,
version.AppName,
),
),
Use: "proposer [proposal-id]",
Args: cobra.ExactArgs(1),
Short: "Query the proposer of a governance proposal",
Long: "Query which address proposed a proposal with a given ID",
Example: fmt.Sprintf("%s query gov proposer 1", version.AppName),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
@ -654,25 +68,3 @@ $ %s query gov proposer 1
return cmd
}
func GetCmdConstitution() *cobra.Command {
return &cobra.Command{
Use: "constitution",
Short: "Get the constitution",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
queryClient := v1.NewQueryClient(clientCtx)
resp, err := queryClient.Constitution(cmd.Context(), &v1.QueryConstitutionRequest{})
if err != nil {
return err
}
return clientCtx.PrintProto(resp)
},
}
}

View File

@ -1,408 +0,0 @@
package cli_test
import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec/address"
"github.com/cosmos/cosmos-sdk/testutil"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
"github.com/cosmos/cosmos-sdk/x/gov/client/cli"
)
func (s *CLITestSuite) TestCmdParams() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"json output",
[]string{fmt.Sprintf("--%s=json", flags.FlagOutput)},
"--output=json",
},
{
"text output",
[]string{fmt.Sprintf("--%s=text", flags.FlagOutput)},
"--output=text",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryParams()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdParam() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"voting params",
[]string{
"voting",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
`voting --output=json`,
},
{
"tally params",
[]string{
"tallying",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
`tallying --output=json`,
},
{
"deposit params",
[]string{
"deposit",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
`deposit --output=json`,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryParam()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdProposer() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"without proposal id",
[]string{
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"--output=json",
},
{
"with proposal id",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"1 --output=json",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryProposer()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdTally() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"without proposal id",
[]string{
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"--output=json",
},
{
"with proposal id (json output)",
[]string{
"2",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"2 --output=json",
},
{
"with proposal id (text output)",
[]string{
"1",
fmt.Sprintf("--%s=text", flags.FlagOutput),
},
"1 --output=text",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryTally()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdGetProposal() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"get proposal with json response",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"1 --output=json",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryProposal()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdGetProposals() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"get proposals as json response",
[]string{
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"--output=json",
},
{
"get proposals with invalid status",
[]string{
"--status=unknown",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"--status=unknown --output=json",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos"))
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdQueryDeposits() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"get deposits",
[]string{
"10",
},
"10",
},
{
"get deposits(json output)",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"1 --output=json",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryDeposits()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdQueryDeposit() {
val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1)
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"get deposit with no depositer",
[]string{
"1",
},
"1",
},
{
"get deposit with wrong deposit address",
[]string{
"1",
"wrong address",
},
"1 wrong address",
},
{
"get deposit (valid req)",
[]string{
"1",
val[0].Address.String(),
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
fmt.Sprintf("1 %s --output=json", val[0].Address.String()),
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryDeposit()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdQueryVotes() {
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"get votes with no proposal id",
[]string{},
"",
},
{
"get votes of a proposal",
[]string{
"10",
},
"10",
},
{
"get votes of a proposal (json output)",
[]string{
"1",
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
"1 --output=json",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryVotes()
cmd.SetArgs(tc.args)
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
})
}
}
func (s *CLITestSuite) TestCmdQueryVote() {
val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1)
testCases := []struct {
name string
args []string
expCmdOutput string
}{
{
"get vote of a proposal",
[]string{
"10",
val[0].Address.String(),
},
fmt.Sprintf("10 %s", val[0].Address.String()),
},
{
"get vote by wrong voter",
[]string{
"1",
"wrong address",
},
"1 wrong address",
},
{
"get vote of a proposal (json output)",
[]string{
"1",
val[0].Address.String(),
fmt.Sprintf("--%s=json", flags.FlagOutput),
},
fmt.Sprintf("1 %s --output=json", val[0].Address.String()),
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryVote(address.NewBech32Codec("cosmos"))
cmd.SetArgs(tc.args)
if len(tc.args) != 0 {
s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput))
}
})
}
}
func (s *CLITestSuite) TestCmdGetConstitution() {
testCases := []struct {
name string
expOutput string
}{
{
name: "get constitution",
expOutput: "constitution",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdConstitution()
out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, []string{})
s.Require().NoError(err)
s.Require().Contains(out.String(), tc.expOutput)
})
}
}

View File

@ -179,11 +179,10 @@ func (q queryServer) Params(ctx context.Context, req *v1.QueryParamsRequest) (*v
case v1.ParamTallying:
tallyParams := v1.NewTallyParams(params.Quorum, params.Threshold, params.VetoThreshold)
response.TallyParams = &tallyParams
default:
return nil, status.Errorf(codes.InvalidArgument,
"%s is not a valid parameter type", req.ParamsType)
if len(req.ParamsType) > 0 {
return nil, status.Errorf(codes.InvalidArgument, "unknown params type: %s", req.ParamsType)
}
}
response.Params = &params
@ -377,6 +376,10 @@ func (q legacyQueryServer) Params(ctx context.Context, req *v1beta1.QueryParamsR
response := &v1beta1.QueryParamsResponse{}
if resp.DepositParams == nil && resp.VotingParams == nil && resp.TallyParams == nil {
return nil, status.Errorf(codes.InvalidArgument, "%s is not a valid parameter type", req.ParamsType)
}
if resp.DepositParams != nil {
minDeposit := sdk.NewCoins(resp.DepositParams.MinDeposit...)
response.DepositParams = v1beta1.NewDepositParams(minDeposit, *resp.DepositParams.MaxDepositPeriod)

View File

@ -891,11 +891,11 @@ func (suite *KeeperTestSuite) TestGRPCQueryParams() {
expPass bool
}{
{
"empty request",
"empty request (valid and returns all params)",
func() {
req = &v1.QueryParamsRequest{}
},
false,
true,
},
{
"deposit params request",

View File

@ -109,11 +109,6 @@ func getProposalCLIHandlers(handlers []govclient.ProposalHandler) []*cobra.Comma
return proposalCLIHandlers
}
// GetQueryCmd returns the root query command for the gov module.
func (ab AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd(ab.ac)
}
// RegisterInterfaces implements InterfaceModule.RegisterInterfaces
func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {
v1.RegisterInterfaces(registry)