Skip to content

Commit

Permalink
valset query ready
Browse files Browse the repository at this point in the history
  • Loading branch information
stackman27 committed Nov 30, 2022
1 parent 9284351 commit 1f1041c
Show file tree
Hide file tree
Showing 16 changed files with 407 additions and 183 deletions.
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 (UserValidatorPreferenceResponse) {
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 UserValidatorPreferenceResponse {
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.
42 changes: 4 additions & 38 deletions x/twap/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,47 +51,12 @@ func (k Keeper) GetArithmeticTwap(
quoteAssetDenom string,
startTime time.Time,
endTime time.Time,
) (sdk.Dec, error) {
arithmeticStrategy := &arithmetic{k}
return k.getTwap(ctx, poolId, baseAssetDenom, quoteAssetDenom, startTime, endTime, arithmeticStrategy)
}

// GetArithmeticTwapToNow returns GetArithmeticTwap on the input, with endTime being fixed to ctx.BlockTime()
// This function does not mutate records.
func (k Keeper) GetArithmeticTwapToNow(
ctx sdk.Context,
poolId uint64,
baseAssetDenom string,
quoteAssetDenom string,
startTime time.Time,
) (sdk.Dec, error) {
arithmeticStrategy := &arithmetic{k}
return k.getTwapToNow(ctx, poolId, baseAssetDenom, quoteAssetDenom, startTime, arithmeticStrategy)
}

// GetBeginBlockAccumulatorRecord returns a TwapRecord struct corresponding to the state of pool `poolId`
// as of the beginning of the block this is called on.
// This uses the state of the beginning of the block, as if there were swaps since the block has started,
// these swaps have had no time to be arbitraged back.
// This accumulator can be stored, to compute wider ranged twaps.
func (k Keeper) GetBeginBlockAccumulatorRecord(ctx sdk.Context, poolId uint64, asset0Denom string, asset1Denom string) (types.TwapRecord, error) {
return k.getMostRecentRecord(ctx, poolId, asset0Denom, asset1Denom)
}

func (k Keeper) getTwap(
ctx sdk.Context,
poolId uint64,
baseAssetDenom string,
quoteAssetDenom string,
startTime time.Time,
endTime time.Time,
strategy twapStrategy,
) (sdk.Dec, error) {
if startTime.After(endTime) {
return sdk.Dec{}, types.StartTimeAfterEndTimeError{StartTime: startTime, EndTime: endTime}
}
if endTime.Equal(ctx.BlockTime()) {
return k.getTwapToNow(ctx, poolId, baseAssetDenom, quoteAssetDenom, startTime, strategy)
return k.GetArithmeticTwapToNow(ctx, poolId, baseAssetDenom, quoteAssetDenom, startTime)
} else if endTime.After(ctx.BlockTime()) {
return sdk.Dec{}, types.EndTimeInFutureError{EndTime: endTime, BlockTime: ctx.BlockTime()}
}
Expand All @@ -106,13 +71,14 @@ func (k Keeper) getTwap(
return computeTwap(startRecord, endRecord, quoteAssetDenom, arithmeticTwapType)
}

func (k Keeper) getTwapToNow(
// GetArithmeticTwapToNow returns GetArithmeticTwap on the input, with endTime being fixed to ctx.BlockTime()
// This function does not mutate records.
func (k Keeper) GetArithmeticTwapToNow(
ctx sdk.Context,
poolId uint64,
baseAssetDenom string,
quoteAssetDenom string,
startTime time.Time,
strategy twapStrategy,
) (sdk.Dec, error) {
if startTime.After(ctx.BlockTime()) {
return sdk.Dec{}, types.StartTimeAfterEndTimeError{StartTime: startTime, EndTime: ctx.BlockTime()}
Expand Down
40 changes: 0 additions & 40 deletions x/twap/strategy.go

This file was deleted.

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
}
83 changes: 83 additions & 0 deletions x/valset-pref/client/cli/query_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package valsetprefcli_test

import (
gocontext "context"
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"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"
"github.com/stretchr/testify/suite"
)

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.UserValidatorPreferenceResponse{},
},
}

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))
}
Loading

0 comments on commit 1f1041c

Please sign in to comment.