Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ValSet-Pref] Setup tx and query and added GetCmdValSetPref and NewSetValSetCmd #3498

Merged
merged 5 commits into from
Dec 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions app/apptesting/test_suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,16 @@ func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sd
return valAddr
}

// SetupMultipleValidators setups "numValidator" validators and returns their address in string
func (s *KeeperTestHelper) SetupMultipleValidators(numValidator int) []string {
valAddrs := []string{}
for i := 0; i < numValidator; i++ {
valAddr := s.SetupValidator(stakingtypes.Bonded)
valAddrs = append(valAddrs, valAddr.String())
}
return valAddrs
}

// BeginNewBlock starts a new block.
func (s *KeeperTestHelper) BeginNewBlock(executeNextEpoch bool) {
var valAddr []byte
Expand Down
25 changes: 25 additions & 0 deletions osmoutils/cli_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,28 @@ func ParseSdkIntFromString(s string, separator string) ([]sdk.Int, error) {
}
return parsedInts, nil
}

func ParseSdkDecFromString(s string, separator string) ([]sdk.Dec, error) {
var parsedDec []sdk.Dec
for _, weightStr := range strings.Split(s, separator) {
weightStr = strings.TrimSpace(weightStr)

parsed, err := sdk.NewDecFromStr(weightStr)
if err != nil {
return parsedDec, err
}

parsedDec = append(parsedDec, parsed)
}
return parsedDec, nil
}

func ParseSdkValAddressFromString(s string, separator string) []sdk.ValAddress {
var parsedAddr []sdk.ValAddress
for _, addr := range strings.Split(s, separator) {
valAddr := sdk.ValAddress([]byte(addr))
parsedAddr = append(parsedAddr, valAddr)
}

return parsedAddr
}
8 changes: 4 additions & 4 deletions proto/osmosis/valset-pref/v1beta1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ option (gogoproto.goproto_getters_all) = false;
// Query defines the gRPC querier service.
service Query {
// Returns the list of ValidatorPreferences for the user.
rpc UserValidatorPreferences(QueryUserValidatorPreferences)
returns (QueryUserValidatorPreferenceResponse) {
rpc UserValidatorPreferences(UserValidatorPreferencesRequest)
returns (UserValidatorPreferencesResponse) {
option (google.api.http).get = "/osmosis/valset-pref/v1beta1/{address}";
}
}

// Request type for UserValidatorPreferences.
message QueryUserValidatorPreferences {
message UserValidatorPreferencesRequest {
// user account address
string address = 1;
}

// Response type the QueryUserValidatorPreferences query request
message QueryUserValidatorPreferenceResponse {
message UserValidatorPreferencesResponse {
repeated ValidatorPreference preferences = 1 [ (gogoproto.nullable) = false ];
}
10 changes: 10 additions & 0 deletions proto/osmosis/valset-pref/v1beta1/query.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
keeper:
path: "github.com/osmosis-labs/osmosis/v13/x/valset-pref"
struct: "Keeper"
client_path: "github.com/osmosis-labs/osmosis/v13/x/valset-pref/client"
queries:
UserValidatorPreferences:
proto_wrapper:
query_func: "k.UserValidatorPreferences"
cli:
cmd: "UserValidatorPreferences"
Binary file modified tests/e2e/scripts/rate_limiter.wasm
Binary file not shown.
57 changes: 57 additions & 0 deletions x/valset-pref/client/cli/query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package valsetprefcli

import (
"fmt"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/client/queryproto"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/types"
"github.com/spf13/cobra"
)

// GetQueryCmd returns the cli query commands for this module.
func GetQueryCmd() *cobra.Command {
// Group valset queries under a subcommand
cmd := &cobra.Command{
Use: types.ModuleName,
Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName),
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}

cmd.AddCommand(GetCmdValSetPref())

return cmd
}

// GetCmdValSetPref takes the address and returns the existing validator set for that address.
func GetCmdValSetPref() *cobra.Command {
cmd := &cobra.Command{
Use: "val-set [address]",
Short: "Query the validator set for a specific user address",

Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := queryproto.NewQueryClient(clientCtx)

res, err := queryClient.UserValidatorPreferences(cmd.Context(), &queryproto.UserValidatorPreferencesRequest{
Address: args[0],
})
if err != nil {
return err
}

return clientCtx.PrintProto(res)
},
}

flags.AddQueryFlagsToCmd(cmd)

return cmd
}
84 changes: 84 additions & 0 deletions x/valset-pref/client/cli/query_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package valsetprefcli_test

import (
gocontext "context"
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"

"github.com/osmosis-labs/osmosis/v13/app/apptesting"
valPref "github.com/osmosis-labs/osmosis/v13/x/valset-pref"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/client/queryproto"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/types"
)

type QueryTestSuite struct {
apptesting.KeeperTestHelper
queryClient queryproto.QueryClient
}

func (s *QueryTestSuite) SetupSuite() {
s.Setup()
s.queryClient = queryproto.NewQueryClient(s.QueryHelper)

// setup 3 validators
valAddrs := s.SetupMultipleValidators(3)
delegator := sdk.AccAddress([]byte("addr1---------------"))
preferences := []types.ValidatorPreference{
{
ValOperAddress: valAddrs[0],
Weight: sdk.NewDecWithPrec(5, 1),
},
{
ValOperAddress: valAddrs[1],
Weight: sdk.NewDecWithPrec(3, 1),
},
{
ValOperAddress: valAddrs[2],
Weight: sdk.NewDecWithPrec(2, 1),
},
}

// setup message server
msgServer := valPref.NewMsgServerImpl(s.App.ValidatorSetPreferenceKeeper)
c := sdk.WrapSDKContext(s.Ctx)

// call the create validator set preference
_, err := msgServer.SetValidatorSetPreference(c, types.NewMsgSetValidatorSetPreference(delegator, preferences))
s.Require().NoError(err)

// creates a test context like blockheader, blockheight and more
s.Commit()
}

func (s *QueryTestSuite) TestQueriesNeverAlterState() {
testCases := []struct {
name string
query string
input interface{}
output interface{}
}{
{
"Query delegators validator set",
"/osmosis.valsetpref.v1beta1.Query/UserValidatorPreferences",
&queryproto.UserValidatorPreferencesRequest{Address: sdk.AccAddress([]byte("addr1---------------")).String()},
&queryproto.UserValidatorPreferencesResponse{},
},
}

for _, tc := range testCases {
tc := tc
s.SetupSuite()

s.Run(tc.name, func() {
err := s.QueryHelper.Invoke(gocontext.Background(), tc.query, tc.input, tc.output)
s.Require().NoError(err)
s.StateNotAltered()
})
}
}

func TestQueryTestSuite(t *testing.T) {
suite.Run(t, new(QueryTestSuite))
}
86 changes: 86 additions & 0 deletions x/valset-pref/client/cli/tx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package valsetprefcli

import (
"fmt"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/osmosis-labs/osmosis/v13/osmoutils"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/types"
"github.com/spf13/cobra"
)

func GetTxCmd() *cobra.Command {
txCmd := &cobra.Command{
Use: types.ModuleName,
Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName),
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}

txCmd.AddCommand(
NewSetValSetCmd(),
)

return txCmd
}

func NewSetValSetCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "set-valset [delegator_addr] [validators] [weights]",
Short: "Creates a new validator set for the delegator with valOperAddress and weight",
Example: "osmosisd tx valset-pref set-valset osmo1... osmovaloper1abc...,osmovaloper1def... 0.56,0.44",

Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}

txf := tx.NewFactoryCLI(clientCtx, cmd.Flags()).WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever)

delAddr, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
return err
}

valAddrs := osmoutils.ParseSdkValAddressFromString(args[1], ",")

weights, err := osmoutils.ParseSdkDecFromString(args[2], ",")
if err != nil {
return err
}

if len(valAddrs) != len(weights) {
return fmt.Errorf("the length of validator addresses and weights not matched")
}

if len(valAddrs) == 0 {
return fmt.Errorf("records is empty")
}

var valset []types.ValidatorPreference
for i, val := range valAddrs {
valset = append(valset, types.ValidatorPreference{
Weight: weights[i],
ValOperAddress: val.String(),
})
}

msg := types.NewMsgSetValidatorSetPreference(
delAddr,
valset,
)

return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg)
},
}

flags.AddTxFlagsToCmd(cmd)

return cmd
}
32 changes: 32 additions & 0 deletions x/valset-pref/client/grpc/grpc_query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package grpc

// THIS FILE IS GENERATED CODE, DO NOT EDIT
// SOURCE AT `proto/osmosis/valset-pref/v1beta1/query.yml`

import (
context "context"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/client"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/client/queryproto"
)

type Querier struct {
Q client.Querier
}

var _ queryproto.QueryServer = Querier{}

func (q Querier) UserValidatorPreferences(grpcCtx context.Context,
req *queryproto.UserValidatorPreferencesRequest,
) (*queryproto.UserValidatorPreferencesResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(grpcCtx)
return q.Q.UserValidatorPreferences(ctx, *req)
}

19 changes: 13 additions & 6 deletions x/valset-pref/client/query_proto_wrap.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
package client

import (
"context"
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"

validatorprefkeeper "github.com/osmosis-labs/osmosis/v13/x/valset-pref"
"github.com/osmosis-labs/osmosis/v13/x/valset-pref/client/queryproto"
)

type Querier struct {
validatorprefkeeper.Keeper
K validatorprefkeeper.Keeper
}

var _ queryproto.QueryServer = Querier{}

func NewQuerier(k validatorprefkeeper.Keeper) Querier {
return Querier{k}
}

func (q Querier) UserValidatorPreferences(ctx context.Context, req *queryproto.QueryUserValidatorPreferences) (*queryproto.QueryUserValidatorPreferenceResponse, error) {
return &queryproto.QueryUserValidatorPreferenceResponse{}, nil
func (q Querier) UserValidatorPreferences(ctx sdk.Context, req queryproto.UserValidatorPreferencesRequest) (*queryproto.UserValidatorPreferencesResponse, error) {
validatorSet, found := q.K.GetValidatorSetPreference(ctx, req.Address)
if !found {
return nil, fmt.Errorf("Validator set not found")
}

return &queryproto.UserValidatorPreferencesResponse{
Preferences: validatorSet.Preferences,
}, nil
}
Loading