From e612ae78f4f31e63d7fb6d86771fa26f1e07a2de Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Mon, 28 Aug 2023 12:54:55 +0200 Subject: [PATCH 01/10] ignite scaffold module dao --dep bank,account Signed-off-by: Lorenz Herzberger --- app/app.go | 24 ++ proto/planetmintgo/dao/genesis.proto | 12 + proto/planetmintgo/dao/params.proto | 12 + proto/planetmintgo/dao/query.proto | 26 ++ proto/planetmintgo/dao/tx.proto | 7 + testutil/keeper/dao.go | 54 +++ x/dao/client/cli/query.go | 31 ++ x/dao/client/cli/query_params.go | 36 ++ x/dao/client/cli/tx.go | 36 ++ x/dao/genesis.go | 23 ++ x/dao/genesis_test.go | 29 ++ x/dao/keeper/keeper.go | 54 +++ x/dao/keeper/msg_server.go | 17 + x/dao/keeper/msg_server_test.go | 23 ++ x/dao/keeper/params.go | 16 + x/dao/keeper/params_test.go | 18 + x/dao/keeper/query.go | 7 + x/dao/keeper/query_params.go | 19 + x/dao/keeper/query_params_test.go | 21 ++ x/dao/module.go | 148 ++++++++ x/dao/module_simulation.go | 64 ++++ x/dao/simulation/helpers.go | 15 + x/dao/types/codec.go | 23 ++ x/dao/types/errors.go | 12 + x/dao/types/expected_keepers.go | 18 + x/dao/types/genesis.go | 24 ++ x/dao/types/genesis.pb.go | 320 ++++++++++++++++ x/dao/types/genesis_test.go | 41 ++ x/dao/types/keys.go | 19 + x/dao/types/params.go | 39 ++ x/dao/types/params.pb.go | 263 +++++++++++++ x/dao/types/query.pb.go | 537 +++++++++++++++++++++++++++ x/dao/types/query.pb.gw.go | 153 ++++++++ x/dao/types/tx.pb.go | 80 ++++ x/dao/types/types.go | 1 + 35 files changed, 2222 insertions(+) create mode 100644 proto/planetmintgo/dao/genesis.proto create mode 100644 proto/planetmintgo/dao/params.proto create mode 100644 proto/planetmintgo/dao/query.proto create mode 100644 proto/planetmintgo/dao/tx.proto create mode 100644 testutil/keeper/dao.go create mode 100644 x/dao/client/cli/query.go create mode 100644 x/dao/client/cli/query_params.go create mode 100644 x/dao/client/cli/tx.go create mode 100644 x/dao/genesis.go create mode 100644 x/dao/genesis_test.go create mode 100644 x/dao/keeper/keeper.go create mode 100644 x/dao/keeper/msg_server.go create mode 100644 x/dao/keeper/msg_server_test.go create mode 100644 x/dao/keeper/params.go create mode 100644 x/dao/keeper/params_test.go create mode 100644 x/dao/keeper/query.go create mode 100644 x/dao/keeper/query_params.go create mode 100644 x/dao/keeper/query_params_test.go create mode 100644 x/dao/module.go create mode 100644 x/dao/module_simulation.go create mode 100644 x/dao/simulation/helpers.go create mode 100644 x/dao/types/codec.go create mode 100644 x/dao/types/errors.go create mode 100644 x/dao/types/expected_keepers.go create mode 100644 x/dao/types/genesis.go create mode 100644 x/dao/types/genesis.pb.go create mode 100644 x/dao/types/genesis_test.go create mode 100644 x/dao/types/keys.go create mode 100644 x/dao/types/params.go create mode 100644 x/dao/types/params.pb.go create mode 100644 x/dao/types/query.pb.go create mode 100644 x/dao/types/query.pb.gw.go create mode 100644 x/dao/types/tx.pb.go create mode 100644 x/dao/types/types.go diff --git a/app/app.go b/app/app.go index 27cfef0..46317a1 100644 --- a/app/app.go +++ b/app/app.go @@ -117,6 +117,9 @@ import ( assetmodulekeeper "planetmint-go/x/asset/keeper" assetmoduletypes "planetmint-go/x/asset/types" + daomodule "planetmint-go/x/dao" + daomodulekeeper "planetmint-go/x/dao/keeper" + daomoduletypes "planetmint-go/x/dao/types" // this line is used by starport scaffolding # stargate/app/moduleImport appparams "planetmint-go/app/params" @@ -179,6 +182,7 @@ var ( consensus.AppModuleBasic{}, machinemodule.AppModuleBasic{}, assetmodule.AppModuleBasic{}, + daomodule.AppModuleBasic{}, // this line is used by starport scaffolding # stargate/app/moduleBasic ) @@ -192,6 +196,7 @@ var ( stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, govtypes.ModuleName: {authtypes.Burner}, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + daomoduletypes.ModuleName: {authtypes.Minter, authtypes.Burner, authtypes.Staking}, // this line is used by starport scaffolding # stargate/app/maccPerms } ) @@ -257,6 +262,8 @@ type App struct { MachineKeeper machinemodulekeeper.Keeper AssetKeeper assetmodulekeeper.Keeper + + DaoKeeper daomodulekeeper.Keeper // this line is used by starport scaffolding # stargate/app/keeperDeclaration // mm is the module manager @@ -305,6 +312,7 @@ func New( capabilitytypes.StoreKey, group.StoreKey, icacontrollertypes.StoreKey, consensusparamtypes.StoreKey, machinemoduletypes.StoreKey, machinemoduletypes.TAIndexKey, machinemoduletypes.IssuerPlanetmintIndexKey, machinemoduletypes.IssuerLiquidIndexKey, assetmoduletypes.StoreKey, + daomoduletypes.StoreKey, // this line is used by starport scaffolding # stargate/app/storeKey ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) @@ -549,6 +557,17 @@ func New( ) assetModule := assetmodule.NewAppModule(appCodec, app.AssetKeeper, app.AccountKeeper, app.BankKeeper) + app.DaoKeeper = *daomodulekeeper.NewKeeper( + appCodec, + keys[daomoduletypes.StoreKey], + keys[daomoduletypes.MemStoreKey], + app.GetSubspace(daomoduletypes.ModuleName), + + app.BankKeeper, + app.AccountKeeper, + ) + daoModule := daomodule.NewAppModule(appCodec, app.DaoKeeper, app.AccountKeeper, app.BankKeeper) + // this line is used by starport scaffolding # stargate/app/keeperDefinition /**** IBC Routing ****/ @@ -612,6 +631,7 @@ func New( icaModule, machineModule, assetModule, + daoModule, // this line is used by starport scaffolding # stargate/app/appModule crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), // always be last to make sure that it checks for all invariants and not only part of them @@ -646,6 +666,7 @@ func New( consensusparamtypes.ModuleName, machinemoduletypes.ModuleName, assetmoduletypes.ModuleName, + daomoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/beginBlockers ) @@ -673,6 +694,7 @@ func New( consensusparamtypes.ModuleName, machinemoduletypes.ModuleName, assetmoduletypes.ModuleName, + daomoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/endBlockers ) @@ -705,6 +727,7 @@ func New( consensusparamtypes.ModuleName, machinemoduletypes.ModuleName, assetmoduletypes.ModuleName, + daomoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/initGenesis } app.mm.SetOrderInitGenesis(genesisModuleOrder...) @@ -931,6 +954,7 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(icahosttypes.SubModuleName) paramsKeeper.Subspace(machinemoduletypes.ModuleName) paramsKeeper.Subspace(assetmoduletypes.ModuleName) + paramsKeeper.Subspace(daomoduletypes.ModuleName) // this line is used by starport scaffolding # stargate/app/paramSubspace return paramsKeeper diff --git a/proto/planetmintgo/dao/genesis.proto b/proto/planetmintgo/dao/genesis.proto new file mode 100644 index 0000000..105c5fd --- /dev/null +++ b/proto/planetmintgo/dao/genesis.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package planetmintgo.dao; + +import "gogoproto/gogo.proto"; +import "planetmintgo/dao/params.proto"; + +option go_package = "planetmint-go/x/dao/types"; + +// GenesisState defines the dao module's genesis state. +message GenesisState { + Params params = 1 [(gogoproto.nullable) = false]; +} diff --git a/proto/planetmintgo/dao/params.proto b/proto/planetmintgo/dao/params.proto new file mode 100644 index 0000000..b820d0c --- /dev/null +++ b/proto/planetmintgo/dao/params.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package planetmintgo.dao; + +import "gogoproto/gogo.proto"; + +option go_package = "planetmint-go/x/dao/types"; + +// Params defines the parameters for the module. +message Params { + option (gogoproto.goproto_stringer) = false; + +} diff --git a/proto/planetmintgo/dao/query.proto b/proto/planetmintgo/dao/query.proto new file mode 100644 index 0000000..aa61f0a --- /dev/null +++ b/proto/planetmintgo/dao/query.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; +package planetmintgo.dao; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; +import "planetmintgo/dao/params.proto"; + +option go_package = "planetmint-go/x/dao/types"; + +// Query defines the gRPC querier service. +service Query { + // Parameters queries the parameters of the module. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/planetmint-go/dao/params"; + } +} + +// QueryParamsRequest is request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is response type for the Query/Params RPC method. +message QueryParamsResponse { + // params holds all the parameters of this module. + Params params = 1 [(gogoproto.nullable) = false]; +} \ No newline at end of file diff --git a/proto/planetmintgo/dao/tx.proto b/proto/planetmintgo/dao/tx.proto new file mode 100644 index 0000000..1fc9159 --- /dev/null +++ b/proto/planetmintgo/dao/tx.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; +package planetmintgo.dao; + +option go_package = "planetmint-go/x/dao/types"; + +// Msg defines the Msg service. +service Msg {} \ No newline at end of file diff --git a/testutil/keeper/dao.go b/testutil/keeper/dao.go new file mode 100644 index 0000000..c1c0dac --- /dev/null +++ b/testutil/keeper/dao.go @@ -0,0 +1,54 @@ +package keeper + +import ( + "testing" + + tmdb "github.com/cometbft/cometbft-db" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/store" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + typesparams "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/stretchr/testify/require" + "planetmint-go/x/dao/keeper" + "planetmint-go/x/dao/types" +) + +func DaoKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { + storeKey := sdk.NewKVStoreKey(types.StoreKey) + memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) + + db := tmdb.NewMemDB() + stateStore := store.NewCommitMultiStore(db) + stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) + stateStore.MountStoreWithDB(memStoreKey, storetypes.StoreTypeMemory, nil) + require.NoError(t, stateStore.LoadLatestVersion()) + + registry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(registry) + + paramsSubspace := typesparams.NewSubspace(cdc, + types.Amino, + storeKey, + memStoreKey, + "DaoParams", + ) + k := keeper.NewKeeper( + cdc, + storeKey, + memStoreKey, + paramsSubspace, + nil, + nil, + ) + + ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) + + // Initialize params + k.SetParams(ctx, types.DefaultParams()) + + return k, ctx +} diff --git a/x/dao/client/cli/query.go b/x/dao/client/cli/query.go new file mode 100644 index 0000000..9417165 --- /dev/null +++ b/x/dao/client/cli/query.go @@ -0,0 +1,31 @@ +package cli + +import ( + "fmt" + // "strings" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + // "github.com/cosmos/cosmos-sdk/client/flags" + // sdk "github.com/cosmos/cosmos-sdk/types" + + "planetmint-go/x/dao/types" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string) *cobra.Command { + // Group dao 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(CmdQueryParams()) + // this line is used by starport scaffolding # 1 + + return cmd +} diff --git a/x/dao/client/cli/query_params.go b/x/dao/client/cli/query_params.go new file mode 100644 index 0000000..8a44d23 --- /dev/null +++ b/x/dao/client/cli/query_params.go @@ -0,0 +1,36 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + + "planetmint-go/x/dao/types" +) + +func CmdQueryParams() *cobra.Command { + cmd := &cobra.Command{ + Use: "params", + Short: "shows the parameters of the module", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/dao/client/cli/tx.go b/x/dao/client/cli/tx.go new file mode 100644 index 0000000..1e15e8f --- /dev/null +++ b/x/dao/client/cli/tx.go @@ -0,0 +1,36 @@ +package cli + +import ( + "fmt" + "time" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + // "github.com/cosmos/cosmos-sdk/client/flags" + "planetmint-go/x/dao/types" +) + +var ( + DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) +) + +const ( + flagPacketTimeoutTimestamp = "packet-timeout-timestamp" + listSeparator = "," +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + // this line is used by starport scaffolding # 1 + + return cmd +} diff --git a/x/dao/genesis.go b/x/dao/genesis.go new file mode 100644 index 0000000..f56c7f8 --- /dev/null +++ b/x/dao/genesis.go @@ -0,0 +1,23 @@ +package dao + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "planetmint-go/x/dao/keeper" + "planetmint-go/x/dao/types" +) + +// InitGenesis initializes the module's state from a provided genesis state. +func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { + // this line is used by starport scaffolding # genesis/module/init + k.SetParams(ctx, genState.Params) +} + +// ExportGenesis returns the module's exported genesis +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { + genesis := types.DefaultGenesis() + genesis.Params = k.GetParams(ctx) + + // this line is used by starport scaffolding # genesis/module/export + + return genesis +} diff --git a/x/dao/genesis_test.go b/x/dao/genesis_test.go new file mode 100644 index 0000000..1944e40 --- /dev/null +++ b/x/dao/genesis_test.go @@ -0,0 +1,29 @@ +package dao_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + keepertest "planetmint-go/testutil/keeper" + "planetmint-go/testutil/nullify" + "planetmint-go/x/dao" + "planetmint-go/x/dao/types" +) + +func TestGenesis(t *testing.T) { + genesisState := types.GenesisState{ + Params: types.DefaultParams(), + + // this line is used by starport scaffolding # genesis/test/state + } + + k, ctx := keepertest.DaoKeeper(t) + dao.InitGenesis(ctx, *k, genesisState) + got := dao.ExportGenesis(ctx, *k) + require.NotNil(t, got) + + nullify.Fill(&genesisState) + nullify.Fill(got) + + // this line is used by starport scaffolding # genesis/test/assert +} diff --git a/x/dao/keeper/keeper.go b/x/dao/keeper/keeper.go new file mode 100644 index 0000000..37d46fd --- /dev/null +++ b/x/dao/keeper/keeper.go @@ -0,0 +1,54 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + + "planetmint-go/x/dao/types" +) + +type ( + Keeper struct { + cdc codec.BinaryCodec + storeKey storetypes.StoreKey + memKey storetypes.StoreKey + paramstore paramtypes.Subspace + + bankKeeper types.BankKeeper + accountKeeper types.AccountKeeper + } +) + +func NewKeeper( + cdc codec.BinaryCodec, + storeKey, + memKey storetypes.StoreKey, + ps paramtypes.Subspace, + + bankKeeper types.BankKeeper, + accountKeeper types.AccountKeeper, +) *Keeper { + // set KeyTable if it has not already been set + if !ps.HasKeyTable() { + ps = ps.WithKeyTable(types.ParamKeyTable()) + } + + return &Keeper{ + cdc: cdc, + storeKey: storeKey, + memKey: memKey, + paramstore: ps, + + bankKeeper: bankKeeper, + accountKeeper: accountKeeper, + } +} + +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} diff --git a/x/dao/keeper/msg_server.go b/x/dao/keeper/msg_server.go new file mode 100644 index 0000000..1bd6e33 --- /dev/null +++ b/x/dao/keeper/msg_server.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "planetmint-go/x/dao/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} diff --git a/x/dao/keeper/msg_server_test.go b/x/dao/keeper/msg_server_test.go new file mode 100644 index 0000000..f8bdc7e --- /dev/null +++ b/x/dao/keeper/msg_server_test.go @@ -0,0 +1,23 @@ +package keeper_test + +import ( + "context" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + keepertest "planetmint-go/testutil/keeper" + "planetmint-go/x/dao/keeper" + "planetmint-go/x/dao/types" +) + +func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) { + k, ctx := keepertest.DaoKeeper(t) + return keeper.NewMsgServerImpl(*k), sdk.WrapSDKContext(ctx) +} + +func TestMsgServer(t *testing.T) { + ms, ctx := setupMsgServer(t) + require.NotNil(t, ms) + require.NotNil(t, ctx) +} diff --git a/x/dao/keeper/params.go b/x/dao/keeper/params.go new file mode 100644 index 0000000..66f2c20 --- /dev/null +++ b/x/dao/keeper/params.go @@ -0,0 +1,16 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "planetmint-go/x/dao/types" +) + +// GetParams get all parameters as types.Params +func (k Keeper) GetParams(ctx sdk.Context) types.Params { + return types.NewParams() +} + +// SetParams set the params +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramstore.SetParamSet(ctx, ¶ms) +} diff --git a/x/dao/keeper/params_test.go b/x/dao/keeper/params_test.go new file mode 100644 index 0000000..60329c4 --- /dev/null +++ b/x/dao/keeper/params_test.go @@ -0,0 +1,18 @@ +package keeper_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + testkeeper "planetmint-go/testutil/keeper" + "planetmint-go/x/dao/types" +) + +func TestGetParams(t *testing.T) { + k, ctx := testkeeper.DaoKeeper(t) + params := types.DefaultParams() + + k.SetParams(ctx, params) + + require.EqualValues(t, params, k.GetParams(ctx)) +} diff --git a/x/dao/keeper/query.go b/x/dao/keeper/query.go new file mode 100644 index 0000000..7a14572 --- /dev/null +++ b/x/dao/keeper/query.go @@ -0,0 +1,7 @@ +package keeper + +import ( + "planetmint-go/x/dao/types" +) + +var _ types.QueryServer = Keeper{} diff --git a/x/dao/keeper/query_params.go b/x/dao/keeper/query_params.go new file mode 100644 index 0000000..50144bb --- /dev/null +++ b/x/dao/keeper/query_params.go @@ -0,0 +1,19 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "planetmint-go/x/dao/types" +) + +func (k Keeper) Params(goCtx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(goCtx) + + return &types.QueryParamsResponse{Params: k.GetParams(ctx)}, nil +} diff --git a/x/dao/keeper/query_params_test.go b/x/dao/keeper/query_params_test.go new file mode 100644 index 0000000..f492998 --- /dev/null +++ b/x/dao/keeper/query_params_test.go @@ -0,0 +1,21 @@ +package keeper_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + testkeeper "planetmint-go/testutil/keeper" + "planetmint-go/x/dao/types" +) + +func TestParamsQuery(t *testing.T) { + keeper, ctx := testkeeper.DaoKeeper(t) + wctx := sdk.WrapSDKContext(ctx) + params := types.DefaultParams() + keeper.SetParams(ctx, params) + + response, err := keeper.Params(wctx, &types.QueryParamsRequest{}) + require.NoError(t, err) + require.Equal(t, &types.QueryParamsResponse{Params: params}, response) +} diff --git a/x/dao/module.go b/x/dao/module.go new file mode 100644 index 0000000..e2a9c36 --- /dev/null +++ b/x/dao/module.go @@ -0,0 +1,148 @@ +package dao + +import ( + "context" + "encoding/json" + "fmt" + // this line is used by starport scaffolding # 1 + + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + abci "github.com/cometbft/cometbft/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "planetmint-go/x/dao/client/cli" + "planetmint-go/x/dao/keeper" + "planetmint-go/x/dao/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface that defines the independent methods a Cosmos SDK module needs to implement. +type AppModuleBasic struct { + cdc codec.BinaryCodec +} + +func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the name of the module as a string +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the amino codec for the module, which is used to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} + +// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns a default GenesisState for the module, marshalled to json.RawMessage. The default GenesisState need to be defined by the module developer and is primarily used for testing +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + return genState.Validate() +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) +} + +// GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the root query command for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(types.StoreKey) +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper +} + +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(cdc), + keeper: keeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + } +} + +// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted) +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the module's genesis initialization. It returns no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { + var genState types.GenesisState + // Initialize global index to index in genesis state + cdc.MustUnmarshalJSON(gs, &genState) + + InitGenesis(ctx, am.keeper, genState) + + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + genState := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(genState) +} + +// ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1 +func (AppModule) ConsensusVersion() uint64 { return 1 } + +// BeginBlock contains the logic that is automatically triggered at the beginning of each block +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock contains the logic that is automatically triggered at the end of each block +func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} diff --git a/x/dao/module_simulation.go b/x/dao/module_simulation.go new file mode 100644 index 0000000..074c999 --- /dev/null +++ b/x/dao/module_simulation.go @@ -0,0 +1,64 @@ +package dao + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" + "planetmint-go/testutil/sample" + daosimulation "planetmint-go/x/dao/simulation" + "planetmint-go/x/dao/types" +) + +// avoid unused import issue +var ( + _ = sample.AccAddress + _ = daosimulation.FindAccount + _ = simulation.MsgEntryKind + _ = baseapp.Paramspace + _ = rand.Rand{} +) + +const ( +// this line is used by starport scaffolding # simapp/module/const +) + +// GenerateGenesisState creates a randomized GenState of the module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + accs := make([]string, len(simState.Accounts)) + for i, acc := range simState.Accounts { + accs[i] = acc.Address.String() + } + daoGenesis := types.GenesisState{ + Params: types.DefaultParams(), + // this line is used by starport scaffolding # simapp/module/genesisState + } + simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&daoGenesis) +} + +// RegisterStoreDecoder registers a decoder. +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalContent { + return nil +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + operations := make([]simtypes.WeightedOperation, 0) + + // this line is used by starport scaffolding # simapp/module/operation + + return operations +} + +// ProposalMsgs returns msgs used for governance proposals for simulations. +func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { + return []simtypes.WeightedProposalMsg{ + // this line is used by starport scaffolding # simapp/module/OpMsg + } +} diff --git a/x/dao/simulation/helpers.go b/x/dao/simulation/helpers.go new file mode 100644 index 0000000..92c437c --- /dev/null +++ b/x/dao/simulation/helpers.go @@ -0,0 +1,15 @@ +package simulation + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// FindAccount find a specific address from an account list +func FindAccount(accs []simtypes.Account, address string) (simtypes.Account, bool) { + creator, err := sdk.AccAddressFromBech32(address) + if err != nil { + panic(err) + } + return simtypes.FindAccount(accs, creator) +} diff --git a/x/dao/types/codec.go b/x/dao/types/codec.go new file mode 100644 index 0000000..844157a --- /dev/null +++ b/x/dao/types/codec.go @@ -0,0 +1,23 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + // this line is used by starport scaffolding # 1 + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +func RegisterCodec(cdc *codec.LegacyAmino) { + // this line is used by starport scaffolding # 2 +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + // this line is used by starport scaffolding # 3 + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +var ( + Amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) +) diff --git a/x/dao/types/errors.go b/x/dao/types/errors.go new file mode 100644 index 0000000..6f18062 --- /dev/null +++ b/x/dao/types/errors.go @@ -0,0 +1,12 @@ +package types + +// DONTCOVER + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// x/dao module sentinel errors +var ( + ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") +) diff --git a/x/dao/types/expected_keepers.go b/x/dao/types/expected_keepers.go new file mode 100644 index 0000000..6aa6e97 --- /dev/null +++ b/x/dao/types/expected_keepers.go @@ -0,0 +1,18 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// AccountKeeper defines the expected account keeper used for simulations (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + // Methods imported from account should be defined here +} + +// BankKeeper defines the expected interface needed to retrieve account balances. +type BankKeeper interface { + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + // Methods imported from bank should be defined here +} diff --git a/x/dao/types/genesis.go b/x/dao/types/genesis.go new file mode 100644 index 0000000..0af9b44 --- /dev/null +++ b/x/dao/types/genesis.go @@ -0,0 +1,24 @@ +package types + +import ( +// this line is used by starport scaffolding # genesis/types/import +) + +// DefaultIndex is the default global index +const DefaultIndex uint64 = 1 + +// DefaultGenesis returns the default genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + // this line is used by starport scaffolding # genesis/types/default + Params: DefaultParams(), + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + // this line is used by starport scaffolding # genesis/types/validate + + return gs.Params.Validate() +} diff --git a/x/dao/types/genesis.pb.go b/x/dao/types/genesis.pb.go new file mode 100644 index 0000000..bc4b02b --- /dev/null +++ b/x/dao/types/genesis.pb.go @@ -0,0 +1,320 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: planetmintgo/dao/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// GenesisState defines the dao module's genesis state. +type GenesisState struct { + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_cae3132315bdc9f8, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "planetmintgo.dao.GenesisState") +} + +func init() { proto.RegisterFile("planetmintgo/dao/genesis.proto", fileDescriptor_cae3132315bdc9f8) } + +var fileDescriptor_cae3132315bdc9f8 = []byte{ + // 180 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0xc8, 0x49, 0xcc, + 0x4b, 0x2d, 0xc9, 0xcd, 0xcc, 0x2b, 0x49, 0xcf, 0xd7, 0x4f, 0x49, 0xcc, 0xd7, 0x4f, 0x4f, 0xcd, + 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0x96, 0xd7, 0x4b, + 0x49, 0xcc, 0x97, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x4b, 0xea, 0x83, 0x58, 0x10, 0x75, 0x52, + 0xb2, 0x18, 0xe6, 0x14, 0x24, 0x16, 0x25, 0xe6, 0x42, 0x8d, 0x51, 0x72, 0xe3, 0xe2, 0x71, 0x87, + 0x98, 0x1b, 0x5c, 0x92, 0x58, 0x92, 0x2a, 0x64, 0xc6, 0xc5, 0x06, 0x91, 0x97, 0x60, 0x54, 0x60, + 0xd4, 0xe0, 0x36, 0x92, 0xd0, 0x43, 0xb7, 0x47, 0x2f, 0x00, 0x2c, 0xef, 0xc4, 0x72, 0xe2, 0x9e, + 0x3c, 0x43, 0x10, 0x54, 0xb5, 0x93, 0xf1, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, + 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, + 0x44, 0x49, 0x22, 0x0c, 0xd0, 0x4d, 0xcf, 0xd7, 0xaf, 0x00, 0xbb, 0xa1, 0xa4, 0xb2, 0x20, 0xb5, + 0x38, 0x89, 0x0d, 0xec, 0x06, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x2a, 0x6a, 0x86, 0x44, + 0xec, 0x00, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/dao/types/genesis_test.go b/x/dao/types/genesis_test.go new file mode 100644 index 0000000..92d79fd --- /dev/null +++ b/x/dao/types/genesis_test.go @@ -0,0 +1,41 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + "planetmint-go/x/dao/types" +) + +func TestGenesisState_Validate(t *testing.T) { + tests := []struct { + desc string + genState *types.GenesisState + valid bool + }{ + { + desc: "default is valid", + genState: types.DefaultGenesis(), + valid: true, + }, + { + desc: "valid genesis state", + genState: &types.GenesisState{ + + // this line is used by starport scaffolding # types/genesis/validField + }, + valid: true, + }, + // this line is used by starport scaffolding # types/genesis/testcase + } + for _, tc := range tests { + t.Run(tc.desc, func(t *testing.T) { + err := tc.genState.Validate() + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/x/dao/types/keys.go b/x/dao/types/keys.go new file mode 100644 index 0000000..452930c --- /dev/null +++ b/x/dao/types/keys.go @@ -0,0 +1,19 @@ +package types + +const ( + // ModuleName defines the module name + ModuleName = "dao" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // RouterKey defines the module's message routing key + RouterKey = ModuleName + + // MemStoreKey defines the in-memory store key + MemStoreKey = "mem_dao" +) + +func KeyPrefix(p string) []byte { + return []byte(p) +} diff --git a/x/dao/types/params.go b/x/dao/types/params.go new file mode 100644 index 0000000..357196a --- /dev/null +++ b/x/dao/types/params.go @@ -0,0 +1,39 @@ +package types + +import ( + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "gopkg.in/yaml.v2" +) + +var _ paramtypes.ParamSet = (*Params)(nil) + +// ParamKeyTable the param key table for launch module +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// NewParams creates a new Params instance +func NewParams() Params { + return Params{} +} + +// DefaultParams returns a default set of parameters +func DefaultParams() Params { + return NewParams() +} + +// ParamSetPairs get the params.ParamSet +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{} +} + +// Validate validates the set of params +func (p Params) Validate() error { + return nil +} + +// String implements the Stringer interface. +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} diff --git a/x/dao/types/params.pb.go b/x/dao/types/params.pb.go new file mode 100644 index 0000000..57ac512 --- /dev/null +++ b/x/dao/types/params.pb.go @@ -0,0 +1,263 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: planetmintgo/dao/params.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Params defines the parameters for the module. +type Params struct { +} + +func (m *Params) Reset() { *m = Params{} } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_a58575036b3ad531, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func init() { + proto.RegisterType((*Params)(nil), "planetmintgo.dao.Params") +} + +func init() { proto.RegisterFile("planetmintgo/dao/params.proto", fileDescriptor_a58575036b3ad531) } + +var fileDescriptor_a58575036b3ad531 = []byte{ + // 138 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0xc8, 0x49, 0xcc, + 0x4b, 0x2d, 0xc9, 0xcd, 0xcc, 0x2b, 0x49, 0xcf, 0xd7, 0x4f, 0x49, 0xcc, 0xd7, 0x2f, 0x48, 0x2c, + 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0x96, 0xd6, 0x4b, 0x49, + 0xcc, 0x97, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x4b, 0xea, 0x83, 0x58, 0x10, 0x75, 0x4a, 0x7c, + 0x5c, 0x6c, 0x01, 0x60, 0x7d, 0x56, 0x2c, 0x33, 0x16, 0xc8, 0x33, 0x38, 0x19, 0x9f, 0x78, 0x24, + 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, + 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x24, 0xc2, 0x44, 0xdd, 0xf4, 0x7c, 0xfd, 0x0a, + 0xb0, 0x9d, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0xb3, 0x8c, 0x01, 0x01, 0x00, 0x00, + 0xff, 0xff, 0x0a, 0x81, 0x96, 0x2f, 0x94, 0x00, 0x00, 0x00, +} + +func (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintParams(dAtA []byte, offset int, v uint64) int { + offset -= sovParams(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozParams(x uint64) (n int) { + return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipParams(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/dao/types/query.pb.go b/x/dao/types/query.pb.go new file mode 100644 index 0000000..6abc3cd --- /dev/null +++ b/x/dao/types/query.pb.go @@ -0,0 +1,537 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: planetmintgo/dao/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/query" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryParamsRequest is request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_07bad0eeb5b27724, []int{0} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params holds all the parameters of this module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_07bad0eeb5b27724, []int{1} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "planetmintgo.dao.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "planetmintgo.dao.QueryParamsResponse") +} + +func init() { proto.RegisterFile("planetmintgo/dao/query.proto", fileDescriptor_07bad0eeb5b27724) } + +var fileDescriptor_07bad0eeb5b27724 = []byte{ + // 290 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0xc8, 0x49, 0xcc, + 0x4b, 0x2d, 0xc9, 0xcd, 0xcc, 0x2b, 0x49, 0xcf, 0xd7, 0x4f, 0x49, 0xcc, 0xd7, 0x2f, 0x2c, 0x4d, + 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0x96, 0xd5, 0x4b, 0x49, 0xcc, + 0x97, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x4b, 0xea, 0x83, 0x58, 0x10, 0x75, 0x52, 0x32, 0xe9, + 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, 0x89, 0x05, 0x99, 0xfa, 0x89, 0x79, 0x79, 0xf9, 0x25, 0x89, + 0x25, 0x99, 0xf9, 0x79, 0xc5, 0x50, 0x59, 0xad, 0xe4, 0xfc, 0xe2, 0xdc, 0xfc, 0x62, 0xfd, 0xa4, + 0xc4, 0xe2, 0x54, 0x88, 0xf1, 0xfa, 0x65, 0x86, 0x49, 0xa9, 0x25, 0x89, 0x86, 0xfa, 0x05, 0x89, + 0xe9, 0x99, 0x79, 0x60, 0xc5, 0x50, 0xb5, 0xb2, 0x18, 0xee, 0x29, 0x48, 0x2c, 0x4a, 0xcc, 0x85, + 0x1a, 0xa5, 0x24, 0xc2, 0x25, 0x14, 0x08, 0x32, 0x20, 0x00, 0x2c, 0x18, 0x94, 0x5a, 0x58, 0x9a, + 0x5a, 0x5c, 0xa2, 0xe4, 0xcb, 0x25, 0x8c, 0x22, 0x5a, 0x5c, 0x90, 0x9f, 0x57, 0x9c, 0x2a, 0x64, + 0xc6, 0xc5, 0x06, 0xd1, 0x2c, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa1, 0x87, 0xee, 0x1d, + 0x3d, 0x88, 0x0e, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xa0, 0xaa, 0x8d, 0x1a, 0x19, 0xb9, + 0x58, 0xc1, 0xe6, 0x09, 0x55, 0x70, 0xb1, 0x41, 0x54, 0x08, 0xa9, 0x60, 0xea, 0xc5, 0x74, 0x88, + 0x94, 0x2a, 0x01, 0x55, 0x10, 0x87, 0x29, 0x29, 0x36, 0x5d, 0x7e, 0x32, 0x99, 0x49, 0x5a, 0x48, + 0x52, 0x1f, 0xa1, 0x5c, 0x17, 0xc5, 0xbb, 0x4e, 0xc6, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, + 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, + 0x2c, 0xc7, 0x10, 0x25, 0x89, 0xaa, 0xa7, 0x02, 0xac, 0xab, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, + 0x0d, 0x1c, 0x48, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8b, 0xac, 0x64, 0x90, 0xd5, 0x01, + 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Parameters queries the parameters of the module. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/planetmintgo.dao.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Parameters queries the parameters of the module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/planetmintgo.dao.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "planetmintgo.dao.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "planetmintgo/dao/query.proto", +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/dao/types/query.pb.gw.go b/x/dao/types/query.pb.gw.go new file mode 100644 index 0000000..02e40c9 --- /dev/null +++ b/x/dao/types/query.pb.gw.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: planetmintgo/dao/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"planetmint-go", "dao", "params"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage +) diff --git a/x/dao/types/tx.pb.go b/x/dao/types/tx.pb.go new file mode 100644 index 0000000..ea1feab --- /dev/null +++ b/x/dao/types/tx.pb.go @@ -0,0 +1,80 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: planetmintgo/dao/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +func init() { proto.RegisterFile("planetmintgo/dao/tx.proto", fileDescriptor_7117c47dbc1828c7) } + +var fileDescriptor_7117c47dbc1828c7 = []byte{ + // 113 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2c, 0xc8, 0x49, 0xcc, + 0x4b, 0x2d, 0xc9, 0xcd, 0xcc, 0x2b, 0x49, 0xcf, 0xd7, 0x4f, 0x49, 0xcc, 0xd7, 0x2f, 0xa9, 0xd0, + 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0x96, 0xd2, 0x4b, 0x49, 0xcc, 0x37, 0x62, 0xe5, + 0x62, 0xf6, 0x2d, 0x4e, 0x77, 0x32, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, + 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, + 0x28, 0x24, 0xd3, 0x74, 0xd3, 0xf3, 0xf5, 0x2b, 0x20, 0x06, 0x56, 0x16, 0xa4, 0x16, 0x27, 0xb1, + 0x81, 0x0d, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x41, 0x8a, 0x85, 0xdb, 0x71, 0x00, 0x00, + 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "planetmintgo.dao.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{}, + Metadata: "planetmintgo/dao/tx.proto", +} diff --git a/x/dao/types/types.go b/x/dao/types/types.go new file mode 100644 index 0000000..ab1254f --- /dev/null +++ b/x/dao/types/types.go @@ -0,0 +1 @@ +package types From f9de021debf8bb2ce3ca9b5cce8f6bcaf685e801 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Mon, 28 Aug 2023 17:24:00 +0200 Subject: [PATCH 02/10] added EndBlocker and started implementing e2e test suite Signed-off-by: Lorenz Herzberger --- tests/e2e/dao/cli_test.go | 14 +++++++ tests/e2e/dao/suite.go | 66 +++++++++++++++++++++++++++++++++ x/dao/abci.go | 12 ++++++ x/dao/keeper/keeper.go | 48 ++++++++++++++++++++++++ x/dao/module.go | 11 ++++-- x/dao/types/expected_keepers.go | 4 ++ 6 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 tests/e2e/dao/cli_test.go create mode 100644 tests/e2e/dao/suite.go create mode 100644 x/dao/abci.go diff --git a/tests/e2e/dao/cli_test.go b/tests/e2e/dao/cli_test.go new file mode 100644 index 0000000..8149550 --- /dev/null +++ b/tests/e2e/dao/cli_test.go @@ -0,0 +1,14 @@ +package dao + +import ( + "planetmint-go/testutil/network" + "testing" + + "github.com/stretchr/testify/suite" +) + +func TestE2ETestSuite(t *testing.T) { + cfg := network.DefaultConfig() + cfg.NumValidators = 1 + suite.Run(t, NewE2ETestSuite(cfg)) +} diff --git a/tests/e2e/dao/suite.go b/tests/e2e/dao/suite.go new file mode 100644 index 0000000..106d865 --- /dev/null +++ b/tests/e2e/dao/suite.go @@ -0,0 +1,66 @@ +package dao + +import ( + "fmt" + "planetmint-go/testutil/network" + "planetmint-go/testutil/sample" + + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + + clitestutil "planetmint-go/testutil/cli" + + auth "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + bank "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + "github.com/stretchr/testify/suite" +) + +// E2ETestSuite struct definition of dao suite +type E2ETestSuite struct { + suite.Suite + + cfg network.Config + network *network.Network +} + +// NewE2ETestSuite returns configured dao E2ETestSuite +func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { + return &E2ETestSuite{cfg: cfg} +} + +// SetupSuite initializes dao E2ETestSuite +func (s *E2ETestSuite) SetupSuite() { + s.T().Log("setting up e2e test suite") + + s.network = network.New(s.T()) +} + +// TearDownSuite clean up after testing +func (s *E2ETestSuite) TearDownSuite() { + s.T().Log("tearing down e2e test suite") +} + +func (s *E2ETestSuite) TestDistributeCollectedFees() { + val := s.network.Validators[0] + + kb := val.ClientCtx.Keyring + account, err := kb.NewAccount(sample.Name, sample.Mnemonic, keyring.DefaultBIP39Passphrase, sample.DefaultDerivationPath, hd.Secp256k1) + s.Require().NoError(err) + + addr, _ := account.GetAddress() + + // sending funds to machine to initialize account on chain + args := []string{ + val.Moniker, + addr.String(), + sample.Amount, + "--yes", + fmt.Sprintf("--%s=%s", flags.FlagFees, sample.Fees), + } + _, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) + s.Require().NoError(err) + + out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, auth.GetAccountsCmd(), []string{}) + fmt.Println(out) +} diff --git a/x/dao/abci.go b/x/dao/abci.go new file mode 100644 index 0000000..7e7167d --- /dev/null +++ b/x/dao/abci.go @@ -0,0 +1,12 @@ +package dao + +import ( + "planetmint-go/x/dao/keeper" + + abci "github.com/cometbft/cometbft/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func EndBlocker(ctx sdk.Context, req abci.RequestEndBlock, k keeper.Keeper) { + k.DistributeCollectedFees(ctx) +} diff --git a/x/dao/keeper/keeper.go b/x/dao/keeper/keeper.go index 37d46fd..8868e62 100644 --- a/x/dao/keeper/keeper.go +++ b/x/dao/keeper/keeper.go @@ -3,10 +3,13 @@ package keeper import ( "fmt" + "cosmossdk.io/math" "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "planetmint-go/x/dao/types" @@ -52,3 +55,48 @@ func NewKeeper( func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } + +func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { + ctx = sdk.UnwrapSDKContext(ctx) + + balances := make(map[string]math.Int) + totalStake := math.ZeroInt() + k.accountKeeper.IterateAccounts(ctx, func(acc authtypes.AccountI) bool { + addr := acc.GetAddress() + balance := k.bankKeeper.SpendableCoins(ctx, addr) + found, stake := balance.Find("stake") + if found { + totalStake = totalStake.Add(stake.Amount) + balances[addr.String()] = stake.Amount + } + return false + }) + + distAddr := k.accountKeeper.GetModuleAddress(disttypes.ModuleName) + distSpendableCoins := k.bankKeeper.SpendableCoins(ctx, distAddr) + found, coinToDistribute := distSpendableCoins.Find("token") + + if found { + decTotalAmountToDistribute := sdk.NewDecFromInt(coinToDistribute.Amount) + decTotalStake := sdk.NewDecFromInt(totalStake) + for addr, stake := range balances { + decStake := sdk.NewDecFromInt(stake) + share := decStake.Quo(decTotalStake) + claim := decTotalAmountToDistribute.Mul(share) + if claim.GTE(sdk.OneDec()) { + intClaim := claim.TruncateInt() + coinClaim := sdk.NewCoin("token", intClaim) + accAddress, err := sdk.AccAddressFromBech32(addr) + if err != nil { + panic(err) + } + if !k.bankKeeper.BlockedAddr(accAddress) { + err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, accAddress, sdk.NewCoins(coinClaim)) + if err != nil { + panic(err) + } + } + } + } + } +} diff --git a/x/dao/module.go b/x/dao/module.go index e2a9c36..9028777 100644 --- a/x/dao/module.go +++ b/x/dao/module.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + // this line is used by starport scaffolding # 1 "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -11,14 +12,15 @@ import ( abci "github.com/cometbft/cometbft/abci/types" + "planetmint-go/x/dao/client/cli" + "planetmint-go/x/dao/keeper" + "planetmint-go/x/dao/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "planetmint-go/x/dao/client/cli" - "planetmint-go/x/dao/keeper" - "planetmint-go/x/dao/types" ) var ( @@ -143,6 +145,7 @@ func (AppModule) ConsensusVersion() uint64 { return 1 } func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} // EndBlock contains the logic that is automatically triggered at the end of each block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { +func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { + EndBlocker(ctx, req, am.keeper) return []abci.ValidatorUpdate{} } diff --git a/x/dao/types/expected_keepers.go b/x/dao/types/expected_keepers.go index 6aa6e97..4ddb2ce 100644 --- a/x/dao/types/expected_keepers.go +++ b/x/dao/types/expected_keepers.go @@ -8,11 +8,15 @@ import ( // AccountKeeper defines the expected account keeper used for simulations (noalias) type AccountKeeper interface { GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + GetModuleAddress(module string) sdk.AccAddress + IterateAccounts(sdk.Context, func(types.AccountI) bool) // Methods imported from account should be defined here } // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + BlockedAddr(addr sdk.AccAddress) bool // Methods imported from bank should be defined here } From 05a484c8b9691a5894dbc7947ed1108673a3be83 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Thu, 31 Aug 2023 16:33:22 +0200 Subject: [PATCH 03/10] implement e2e test scenario for fee distribution Signed-off-by: Lorenz Herzberger --- docs/static/openapi.yml | 46 +++++++++++++++++++ go.mod | 2 +- tests/e2e/dao/cli_test.go | 1 - tests/e2e/dao/suite.go | 96 ++++++++++++++++++++++++++++++++------- testutil/sample/sample.go | 6 +++ x/dao/keeper/keeper.go | 7 +-- 6 files changed, 137 insertions(+), 21 deletions(-) diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index d78879f..eef0b8a 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -46473,6 +46473,42 @@ paths: additionalProperties: {} tags: - Query + /planetmint-go/dao/params: + get: + summary: Parameters queries the parameters of the module. + operationId: PlanetmintgoDaoParams + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + description: >- + QueryParamsResponse is response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + '@type': + type: string + additionalProperties: {} + tags: + - Query /planetmint-go/machine/get_machine_by_public_key/{publicKey}: get: summary: Queries a list of GetMachineByPublicKey items. @@ -75329,6 +75365,16 @@ definitions: description: params holds all the parameters of this module. type: object description: QueryParamsResponse is response type for the Query/Params RPC method. + planetmintgo.dao.Params: + type: object + description: Params defines the parameters for the module. + planetmintgo.dao.QueryParamsResponse: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + description: QueryParamsResponse is response type for the Query/Params RPC method. planetmintgo.machine.Machine: type: object properties: diff --git a/go.mod b/go.mod index 0c0c443..e520725 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.19 require ( cosmossdk.io/api v0.3.1 cosmossdk.io/errors v1.0.0-beta.7 + cosmossdk.io/math v1.0.1 github.com/btcsuite/btcd v0.23.0 github.com/btcsuite/btcd/btcutil v1.1.2 github.com/cometbft/cometbft v0.37.2 @@ -39,7 +40,6 @@ require ( cosmossdk.io/core v0.5.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/log v1.1.0 // indirect - cosmossdk.io/math v1.0.1 // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect diff --git a/tests/e2e/dao/cli_test.go b/tests/e2e/dao/cli_test.go index 8149550..bd02179 100644 --- a/tests/e2e/dao/cli_test.go +++ b/tests/e2e/dao/cli_test.go @@ -9,6 +9,5 @@ import ( func TestE2ETestSuite(t *testing.T) { cfg := network.DefaultConfig() - cfg.NumValidators = 1 suite.Run(t, NewE2ETestSuite(cfg)) } diff --git a/tests/e2e/dao/suite.go b/tests/e2e/dao/suite.go index 106d865..00d9165 100644 --- a/tests/e2e/dao/suite.go +++ b/tests/e2e/dao/suite.go @@ -5,17 +5,23 @@ import ( "planetmint-go/testutil/network" "planetmint-go/testutil/sample" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" clitestutil "planetmint-go/testutil/cli" - auth "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" bank "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/suite" ) +var ( + bobAddr sdk.AccAddress + aliceAddr sdk.AccAddress +) + // E2ETestSuite struct definition of dao suite type E2ETestSuite struct { suite.Suite @@ -33,7 +39,43 @@ func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { func (s *E2ETestSuite) SetupSuite() { s.T().Log("setting up e2e test suite") - s.network = network.New(s.T()) + // set accounts for alice and bob in genesis state + var authGenState authtypes.GenesisState + s.cfg.Codec.MustUnmarshalJSON(s.cfg.GenesisState[authtypes.ModuleName], &authGenState) + + bobAddr = sample.Secp256k1AccAddress() + aliceAddr = sample.Secp256k1AccAddress() + + bob := authtypes.NewBaseAccount(bobAddr, nil, 0, 0) + alice := authtypes.NewBaseAccount(aliceAddr, nil, 0, 0) + + accounts, err := authtypes.PackAccounts(authtypes.GenesisAccounts{bob, alice}) + s.Require().NoError(err) + + authGenState.Accounts = append(authGenState.Accounts, accounts...) + s.cfg.GenesisState[authtypes.ModuleName] = s.cfg.Codec.MustMarshalJSON(&authGenState) + + // set the balances in the genesis state + var bankGenState banktypes.GenesisState + s.cfg.Codec.MustUnmarshalJSON(s.cfg.GenesisState[banktypes.ModuleName], &bankGenState) + + bbalances := sdk.NewCoins( + sdk.NewCoin("rddl", math.NewInt(10000)), + ) + + abalances := sdk.NewCoins( + sdk.NewCoin("rddl", math.NewInt(5000)), + ) + + accountBalances := []banktypes.Balance{ + {Address: bobAddr.String(), Coins: bbalances.Sort()}, + {Address: aliceAddr.String(), Coins: abalances.Sort()}, + } + bankGenState.Balances = append(bankGenState.Balances, accountBalances...) + s.cfg.GenesisState[banktypes.ModuleName] = s.cfg.Codec.MustMarshalJSON(&bankGenState) + + s.cfg.MinGasPrices = fmt.Sprintf("0.000006%s", "node0token") + s.network = network.New(s.T(), s.cfg) } // TearDownSuite clean up after testing @@ -44,23 +86,45 @@ func (s *E2ETestSuite) TearDownSuite() { func (s *E2ETestSuite) TestDistributeCollectedFees() { val := s.network.Validators[0] - kb := val.ClientCtx.Keyring - account, err := kb.NewAccount(sample.Name, sample.Mnemonic, keyring.DefaultBIP39Passphrase, sample.DefaultDerivationPath, hd.Secp256k1) - s.Require().NoError(err) - - addr, _ := account.GetAddress() - - // sending funds to machine to initialize account on chain + // sending funds to alice args := []string{ val.Moniker, - addr.String(), - sample.Amount, + aliceAddr.String(), + "1000stake", "--yes", - fmt.Sprintf("--%s=%s", flags.FlagFees, sample.Fees), + // fmt.Sprintf("--%s=%s", flags.FlagFees, sample.Fees), + fmt.Sprintf("--%s=%s", flags.FlagFees, "10node0token"), } + _, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) + s.Require().NoError(err) + + s.network.WaitForNextBlock() + out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ + aliceAddr.String(), + }) + s.Require().NoError(err) + s.T().Log(out) + + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ + bobAddr.String(), + }) + s.Require().NoError(err) + s.T().Log(out) _, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) s.Require().NoError(err) - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, auth.GetAccountsCmd(), []string{}) - fmt.Println(out) + s.network.WaitForNextBlock() + + s.network.WaitForNextBlock() + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ + aliceAddr.String(), + }) + s.Require().NoError(err) + s.T().Log(out) + + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ + bobAddr.String(), + }) + s.Require().NoError(err) + s.T().Log(out) } diff --git a/testutil/sample/sample.go b/testutil/sample/sample.go index 7ad51c2..d5ca836 100644 --- a/testutil/sample/sample.go +++ b/testutil/sample/sample.go @@ -48,6 +48,12 @@ func AccAddress() string { return sdk.AccAddress(addr).String() } +func Secp256k1AccAddress() sdk.AccAddress { + pk := secp256k1.GenPrivKey().PubKey() + addr := pk.Address() + return sdk.AccAddress(addr) +} + func Machine(name, pubKey string) machinetypes.Machine { metadata := Metadata() _, liquidPubKey := ExtendedKeyPair(config.LiquidNetParams) diff --git a/x/dao/keeper/keeper.go b/x/dao/keeper/keeper.go index 8868e62..77ad9d4 100644 --- a/x/dao/keeper/keeper.go +++ b/x/dao/keeper/keeper.go @@ -64,7 +64,7 @@ func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { k.accountKeeper.IterateAccounts(ctx, func(acc authtypes.AccountI) bool { addr := acc.GetAddress() balance := k.bankKeeper.SpendableCoins(ctx, addr) - found, stake := balance.Find("stake") + found, stake := balance.Find("rddl") if found { totalStake = totalStake.Add(stake.Amount) balances[addr.String()] = stake.Amount @@ -74,7 +74,8 @@ func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { distAddr := k.accountKeeper.GetModuleAddress(disttypes.ModuleName) distSpendableCoins := k.bankKeeper.SpendableCoins(ctx, distAddr) - found, coinToDistribute := distSpendableCoins.Find("token") + // found, coinToDistribute := distSpendableCoins.Find("stake") + found, coinToDistribute := distSpendableCoins.Find("node0token") if found { decTotalAmountToDistribute := sdk.NewDecFromInt(coinToDistribute.Amount) @@ -85,7 +86,7 @@ func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { claim := decTotalAmountToDistribute.Mul(share) if claim.GTE(sdk.OneDec()) { intClaim := claim.TruncateInt() - coinClaim := sdk.NewCoin("token", intClaim) + coinClaim := sdk.NewCoin("node0token", intClaim) accAddress, err := sdk.AccAddressFromBech32(addr) if err != nil { panic(err) From c58dda203414fcd746652ae2f56f8f71f2a38827 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Tue, 5 Sep 2023 11:03:42 +0200 Subject: [PATCH 04/10] add denoms to config Signed-off-by: Lorenz Herzberger --- config/config.go | 9 +++++++++ tests/e2e/dao/suite.go | 13 ++++++++++--- x/dao/keeper/keeper.go | 9 +++++---- 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/config/config.go b/config/config.go index da7e666..c30b4fe 100644 --- a/config/config.go +++ b/config/config.go @@ -14,6 +14,9 @@ const DefaultConfigTemplate = ` osc-service-port = {{ .PlmntConfig.OSCServicePort }} watchmen-endpoint = "{{ .PlmntConfig.WatchmenEndpoint }}" watchmen-port = {{ .PlmntConfig.WatchmenPort }} +token-denom = {{ .PlmntConfig.TokenDenom }} +stake-denom = {{ .PlmntConfig.StakeDenom }} +fee-denom = {{ .PlmntConfig.FeeDenom }} ` // Config defines Planetmint's top level configuration @@ -21,6 +24,9 @@ type Config struct { OSCServicePort int `mapstructure:"osc-service-port" json:"osc-service-port"` WatchmenEndpoint string `mapstructure:"watchmen-endpoint" json:"watchmen-endpoint"` WatchmenPort int `mapstructure:"watchmen-port" json:"watchmen-port"` + TokenDenom string `mapstructure:"token-denom" json:"token-denom"` + StakeDenom string `mapstructure:"stake-denom" json:"stake-denom"` + FeeDenom string `mapstructure:"fee-denom" json:"fee-denom"` } // cosmos-sdk wide global singleton @@ -35,6 +41,9 @@ func DefaultConfig() *Config { OSCServicePort: 8766, WatchmenEndpoint: "lab.r3c.network", WatchmenPort: 7401, + TokenDenom: "plmnt", + StakeDenom: "plmntstake", + FeeDenom: "plmnt", } } diff --git a/tests/e2e/dao/suite.go b/tests/e2e/dao/suite.go index 00d9165..c69d2e1 100644 --- a/tests/e2e/dao/suite.go +++ b/tests/e2e/dao/suite.go @@ -2,6 +2,7 @@ package dao import ( "fmt" + "planetmint-go/config" "planetmint-go/testutil/network" "planetmint-go/testutil/sample" @@ -37,6 +38,10 @@ func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { // SetupSuite initializes dao E2ETestSuite func (s *E2ETestSuite) SetupSuite() { + conf := config.GetConfig() + conf.FeeDenom = "node0token" + conf.SetPlanetmintConfig(conf) + s.T().Log("setting up e2e test suite") // set accounts for alice and bob in genesis state @@ -60,11 +65,13 @@ func (s *E2ETestSuite) SetupSuite() { s.cfg.Codec.MustUnmarshalJSON(s.cfg.GenesisState[banktypes.ModuleName], &bankGenState) bbalances := sdk.NewCoins( - sdk.NewCoin("rddl", math.NewInt(10000)), + sdk.NewCoin(conf.TokenDenom, math.NewInt(10000)), + sdk.NewCoin(conf.StakeDenom, math.NewInt(10000)), ) abalances := sdk.NewCoins( - sdk.NewCoin("rddl", math.NewInt(5000)), + sdk.NewCoin(conf.TokenDenom, math.NewInt(10000)), + sdk.NewCoin(conf.StakeDenom, math.NewInt(5000)), ) accountBalances := []banktypes.Balance{ @@ -74,7 +81,7 @@ func (s *E2ETestSuite) SetupSuite() { bankGenState.Balances = append(bankGenState.Balances, accountBalances...) s.cfg.GenesisState[banktypes.ModuleName] = s.cfg.Codec.MustMarshalJSON(&bankGenState) - s.cfg.MinGasPrices = fmt.Sprintf("0.000006%s", "node0token") + s.cfg.MinGasPrices = fmt.Sprintf("0.000006%s", conf.FeeDenom) s.network = network.New(s.T(), s.cfg) } diff --git a/x/dao/keeper/keeper.go b/x/dao/keeper/keeper.go index 77ad9d4..442a1fa 100644 --- a/x/dao/keeper/keeper.go +++ b/x/dao/keeper/keeper.go @@ -12,6 +12,7 @@ import ( disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "planetmint-go/config" "planetmint-go/x/dao/types" ) @@ -58,13 +59,14 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { ctx = sdk.UnwrapSDKContext(ctx) + conf := config.GetConfig() balances := make(map[string]math.Int) totalStake := math.ZeroInt() k.accountKeeper.IterateAccounts(ctx, func(acc authtypes.AccountI) bool { addr := acc.GetAddress() balance := k.bankKeeper.SpendableCoins(ctx, addr) - found, stake := balance.Find("rddl") + found, stake := balance.Find(conf.StakeDenom) if found { totalStake = totalStake.Add(stake.Amount) balances[addr.String()] = stake.Amount @@ -74,8 +76,7 @@ func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { distAddr := k.accountKeeper.GetModuleAddress(disttypes.ModuleName) distSpendableCoins := k.bankKeeper.SpendableCoins(ctx, distAddr) - // found, coinToDistribute := distSpendableCoins.Find("stake") - found, coinToDistribute := distSpendableCoins.Find("node0token") + found, coinToDistribute := distSpendableCoins.Find(conf.FeeDenom) if found { decTotalAmountToDistribute := sdk.NewDecFromInt(coinToDistribute.Amount) @@ -86,7 +87,7 @@ func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { claim := decTotalAmountToDistribute.Mul(share) if claim.GTE(sdk.OneDec()) { intClaim := claim.TruncateInt() - coinClaim := sdk.NewCoin("node0token", intClaim) + coinClaim := sdk.NewCoin(conf.FeeDenom, intClaim) accAddress, err := sdk.AccAddressFromBech32(addr) if err != nil { panic(err) From 6283299d9467f14118dc2d0f34e32607e16c32aa Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Tue, 5 Sep 2023 12:12:10 +0200 Subject: [PATCH 05/10] sanitize test case Signed-off-by: Lorenz Herzberger --- tests/e2e/dao/suite.go | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/tests/e2e/dao/suite.go b/tests/e2e/dao/suite.go index c69d2e1..fe8e9bc 100644 --- a/tests/e2e/dao/suite.go +++ b/tests/e2e/dao/suite.go @@ -15,6 +15,7 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" bank "github.com/cosmos/cosmos-sdk/x/bank/client/cli" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) @@ -38,6 +39,7 @@ func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { // SetupSuite initializes dao E2ETestSuite func (s *E2ETestSuite) SetupSuite() { + // set FeeDenom to node0token because the sending account is initialized with no plmnt tokens conf := config.GetConfig() conf.FeeDenom = "node0token" conf.SetPlanetmintConfig(conf) @@ -60,7 +62,7 @@ func (s *E2ETestSuite) SetupSuite() { authGenState.Accounts = append(authGenState.Accounts, accounts...) s.cfg.GenesisState[authtypes.ModuleName] = s.cfg.Codec.MustMarshalJSON(&authGenState) - // set the balances in the genesis state + // set the balances in genesis state var bankGenState banktypes.GenesisState s.cfg.Codec.MustUnmarshalJSON(s.cfg.GenesisState[banktypes.ModuleName], &bankGenState) @@ -91,47 +93,39 @@ func (s *E2ETestSuite) TearDownSuite() { } func (s *E2ETestSuite) TestDistributeCollectedFees() { + conf := config.GetConfig() val := s.network.Validators[0] - // sending funds to alice + // sending funds to alice and pay some fees to be distributed args := []string{ val.Moniker, aliceAddr.String(), "1000stake", "--yes", - // fmt.Sprintf("--%s=%s", flags.FlagFees, sample.Fees), - fmt.Sprintf("--%s=%s", flags.FlagFees, "10node0token"), + fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("10%s", conf.FeeDenom)), } _, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) s.Require().NoError(err) s.network.WaitForNextBlock() - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ - aliceAddr.String(), - }) - s.Require().NoError(err) - s.T().Log(out) - - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ - bobAddr.String(), - }) - s.Require().NoError(err) - s.T().Log(out) _, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) s.Require().NoError(err) s.network.WaitForNextBlock() s.network.WaitForNextBlock() - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ + + // assert that alice has 6 of 20 paid fee tokens based on 5000 stake of 15000 total stake + out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ aliceAddr.String(), }) + assert.Contains(s.T(), out.String(), "6") s.Require().NoError(err) - s.T().Log(out) + // assert that bob has 13 of 20 paid fee tokens based on 10000 stake of 15000 total stake out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ bobAddr.String(), }) + assert.Contains(s.T(), out.String(), "13") s.Require().NoError(err) - s.T().Log(out) } From d32c2c71cfebe4bbf2eb1ce00bfd828179fbc618 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Tue, 5 Sep 2023 12:21:06 +0200 Subject: [PATCH 06/10] add dao lint rule to audit workflow Signed-off-by: Lorenz Herzberger --- .github/workflows/audit.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/audit.yaml b/.github/workflows/audit.yaml index 47f8434..f318bbd 100644 --- a/.github/workflows/audit.yaml +++ b/.github/workflows/audit.yaml @@ -40,6 +40,7 @@ jobs: # Add lint-ignore comment to beginning of files sed -i "1i${LINT}" ./x/asset/types/query.pb.gw.go sed -i "1i${LINT}" ./x/machine/types/query.pb.gw.go + sed -i "1i${LINT}" ./x/dao/types/query.pb.gw.go staticcheck ./... - name: Install golangci-lint From f8d3bec516668444ccc322e34f2b2edf39008681 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Tue, 5 Sep 2023 12:27:41 +0200 Subject: [PATCH 07/10] fix staticcheck errors Signed-off-by: Lorenz Herzberger --- x/dao/client/cli/tx.go | 5 ----- x/dao/module_simulation.go | 9 +++++---- x/dao/types/errors.go | 4 ++-- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/x/dao/client/cli/tx.go b/x/dao/client/cli/tx.go index 1e15e8f..bbc8fe7 100644 --- a/x/dao/client/cli/tx.go +++ b/x/dao/client/cli/tx.go @@ -15,11 +15,6 @@ var ( DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) ) -const ( - flagPacketTimeoutTimestamp = "packet-timeout-timestamp" - listSeparator = "," -) - // GetTxCmd returns the transaction commands for this module func GetTxCmd() *cobra.Command { cmd := &cobra.Command{ diff --git a/x/dao/module_simulation.go b/x/dao/module_simulation.go index 074c999..ba4d5b1 100644 --- a/x/dao/module_simulation.go +++ b/x/dao/module_simulation.go @@ -3,14 +3,15 @@ package dao import ( "math/rand" + "planetmint-go/testutil/sample" + daosimulation "planetmint-go/x/dao/simulation" + "planetmint-go/x/dao/types" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - "planetmint-go/testutil/sample" - daosimulation "planetmint-go/x/dao/simulation" - "planetmint-go/x/dao/types" ) // avoid unused import issue @@ -43,7 +44,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalContent { +func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { return nil } diff --git a/x/dao/types/errors.go b/x/dao/types/errors.go index 6f18062..4ebceb6 100644 --- a/x/dao/types/errors.go +++ b/x/dao/types/errors.go @@ -3,10 +3,10 @@ package types // DONTCOVER import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "cosmossdk.io/errors" ) // x/dao module sentinel errors var ( - ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") + ErrSample = errorsmod.Register(ModuleName, 1100, "sample error") ) From 58c7947045f890aaacbe3139a4b5b3e66bbde0eb Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Tue, 5 Sep 2023 12:34:35 +0200 Subject: [PATCH 08/10] fix lint errors Signed-off-by: Lorenz Herzberger --- tests/e2e/dao/suite.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/e2e/dao/suite.go b/tests/e2e/dao/suite.go index fe8e9bc..14d5470 100644 --- a/tests/e2e/dao/suite.go +++ b/tests/e2e/dao/suite.go @@ -107,13 +107,17 @@ func (s *E2ETestSuite) TestDistributeCollectedFees() { _, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) s.Require().NoError(err) - s.network.WaitForNextBlock() + err = s.network.WaitForNextBlock() + s.Require().NoError(err) + _, err = clitestutil.ExecTestCLICmd(val.ClientCtx, bank.NewSendTxCmd(), args) s.Require().NoError(err) - s.network.WaitForNextBlock() + err = s.network.WaitForNextBlock() + s.Require().NoError(err) - s.network.WaitForNextBlock() + err = s.network.WaitForNextBlock() + s.Require().NoError(err) // assert that alice has 6 of 20 paid fee tokens based on 5000 stake of 15000 total stake out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, bank.GetBalancesCmd(), []string{ From 364b91068330a502a4eaa3c877db584b28d11e00 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Tue, 5 Sep 2023 12:47:16 +0200 Subject: [PATCH 09/10] add nolint to generated dao module code Signed-off-by: Lorenz Herzberger --- x/dao/module.go | 1 + 1 file changed, 1 insertion(+) diff --git a/x/dao/module.go b/x/dao/module.go index 9028777..356beac 100644 --- a/x/dao/module.go +++ b/x/dao/module.go @@ -72,6 +72,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + //nolint:errcheck types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) } From a7e627ff49a23a4e387931cca592ee7faa713783 Mon Sep 17 00:00:00 2001 From: Lorenz Herzberger Date: Wed, 6 Sep 2023 09:25:58 +0200 Subject: [PATCH 10/10] reduce complexity on fee distribution Signed-off-by: Lorenz Herzberger --- x/dao/client/cli/query.go | 3 -- x/dao/keeper/keeper.go | 62 ++++++++++++++++++++++++++++----------- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/x/dao/client/cli/query.go b/x/dao/client/cli/query.go index 9417165..1a19b61 100644 --- a/x/dao/client/cli/query.go +++ b/x/dao/client/cli/query.go @@ -2,13 +2,10 @@ package cli import ( "fmt" - // "strings" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" - // "github.com/cosmos/cosmos-sdk/client/flags" - // sdk "github.com/cosmos/cosmos-sdk/types" "planetmint-go/x/dao/types" ) diff --git a/x/dao/keeper/keeper.go b/x/dao/keeper/keeper.go index 442a1fa..0d3afd2 100644 --- a/x/dao/keeper/keeper.go +++ b/x/dao/keeper/keeper.go @@ -79,26 +79,54 @@ func (k Keeper) DistributeCollectedFees(ctx sdk.Context) { found, coinToDistribute := distSpendableCoins.Find(conf.FeeDenom) if found { - decTotalAmountToDistribute := sdk.NewDecFromInt(coinToDistribute.Amount) - decTotalStake := sdk.NewDecFromInt(totalStake) - for addr, stake := range balances { - decStake := sdk.NewDecFromInt(stake) - share := decStake.Quo(decTotalStake) - claim := decTotalAmountToDistribute.Mul(share) - if claim.GTE(sdk.OneDec()) { - intClaim := claim.TruncateInt() - coinClaim := sdk.NewCoin(conf.FeeDenom, intClaim) - accAddress, err := sdk.AccAddressFromBech32(addr) + err := k.processBalances(ctx, balances, totalStake, coinToDistribute) + if err != nil { + ctx.Logger().Error("Error processing balances:", err) + } + } +} + +// Check if the address is blocked +func (k Keeper) isAddressBlocked(accAddress sdk.AccAddress) bool { + return k.bankKeeper.BlockedAddr(accAddress) +} + +// Send coins from the module to the account +func (k Keeper) sendCoinsFromModuleToAccount(ctx sdk.Context, accAddress sdk.AccAddress, coinClaim sdk.Coin) error { + return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, accAddress, sdk.NewCoins(coinClaim)) +} + +// Calculate the claim for an address +func calculateClaimForAddress(stake math.Int, totalStake math.Int, coinToDistribute sdk.Coin) sdk.Dec { + decTotalAmountToDistribute := sdk.NewDecFromInt(coinToDistribute.Amount) + decTotalStake := sdk.NewDecFromInt(totalStake) + decStake := sdk.NewDecFromInt(stake) + + share := decStake.Quo(decTotalStake) + return decTotalAmountToDistribute.Mul(share) +} + +func (k Keeper) processBalances(ctx sdk.Context, balances map[string]math.Int, totalStake math.Int, coinToDistribute sdk.Coin) error { + conf := config.GetConfig() + for addr, stake := range balances { + claim := calculateClaimForAddress(stake, totalStake, coinToDistribute) + + if claim.GTE(sdk.OneDec()) { + intClaim := claim.TruncateInt() + coinClaim := sdk.NewCoin(conf.FeeDenom, intClaim) + + accAddress, err := sdk.AccAddressFromBech32(addr) + if err != nil { + return err + } + + if !k.isAddressBlocked(accAddress) { + err = k.sendCoinsFromModuleToAccount(ctx, accAddress, coinClaim) if err != nil { - panic(err) - } - if !k.bankKeeper.BlockedAddr(accAddress) { - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, accAddress, sdk.NewCoins(coinClaim)) - if err != nil { - panic(err) - } + return err } } } } + return nil }