From 622a29aeabdb3d3b68b385306161fbedf09dc488 Mon Sep 17 00:00:00 2001 From: Alex Johnson Date: Sat, 1 Oct 2022 16:48:53 -0400 Subject: [PATCH] refactor(`mint`): cleanup module (#58) * remove old keys * refactor gen state * refactor module * fix * move abci into keeper * refactor begin blocker * refactor begin blocker * cleanup * format * format Co-authored-by: Lucas Btd --- x/mint/{ => keeper}/abci.go | 15 +++--- x/mint/keeper/abci_test.go | 7 +++ x/mint/keeper/integration_test.go | 14 ------ x/mint/keeper/keeper.go | 39 ++++++--------- x/mint/module.go | 82 +++++++++++-------------------- x/mint/module_simulation.go | 39 +++++++++++++++ x/mint/types/genesis.go | 12 ++--- x/mint/types/keys.go | 5 -- 8 files changed, 100 insertions(+), 113 deletions(-) rename x/mint/{ => keeper}/abci.go (82%) create mode 100644 x/mint/keeper/abci_test.go create mode 100644 x/mint/module_simulation.go diff --git a/x/mint/abci.go b/x/mint/keeper/abci.go similarity index 82% rename from x/mint/abci.go rename to x/mint/keeper/abci.go index 2a20e04..dee7611 100644 --- a/x/mint/abci.go +++ b/x/mint/keeper/abci.go @@ -1,4 +1,4 @@ -package mint +package keeper import ( "time" @@ -6,12 +6,11 @@ import ( "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ignite/modules/x/mint/keeper" "github.com/ignite/modules/x/mint/types" ) // BeginBlocker mints new coins for the previous block. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) error { +func (k Keeper) BeginBlocker(ctx sdk.Context) error { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) // fetch stored minter & params @@ -27,17 +26,15 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) error { // mint coins, update supply mintedCoin := minter.BlockProvision(params) - mintedCoins := sdk.NewCoins(mintedCoin) - - err := k.MintCoins(ctx, mintedCoins) + err := k.MintCoin(ctx, mintedCoin) if err != nil { - panic(err) + return err } // distribute minted coins according to the defined proportions - err = k.DistributeMintedCoins(ctx, mintedCoin) + err = k.DistributeMintedCoin(ctx, mintedCoin) if err != nil { - panic(err) + return err } if mintedCoin.Amount.IsInt64() { diff --git a/x/mint/keeper/abci_test.go b/x/mint/keeper/abci_test.go new file mode 100644 index 0000000..80ceadc --- /dev/null +++ b/x/mint/keeper/abci_test.go @@ -0,0 +1,7 @@ +package keeper_test + +import "testing" + +// TODO add test +func TestBeginBlocker(t *testing.T) { +} diff --git a/x/mint/keeper/integration_test.go b/x/mint/keeper/integration_test.go index 36fc830..e288463 100644 --- a/x/mint/keeper/integration_test.go +++ b/x/mint/keeper/integration_test.go @@ -4,26 +4,12 @@ import ( "encoding/json" "github.com/cosmos/cosmos-sdk/simapp" - sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" testapp "github.com/ignite/modules/app" "github.com/ignite/modules/testutil" - "github.com/ignite/modules/x/mint/types" ) -// returns context and an app with updated mint keeper -func createTestApp(isCheckTx bool) (*testapp.App, sdk.Context) { - app := setup(isCheckTx) - - ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) - app.MintKeeper.SetParams(ctx, types.DefaultParams()) - app.MintKeeper.SetMinter(ctx, types.DefaultInitialMinter()) - - return app, ctx -} - func setup(isCheckTx bool) *testapp.App { app, genesisState := testutil.GenApp(!isCheckTx, 5) if !isCheckTx { diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 423c7b9..063aa4a 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -57,7 +57,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", "x/"+types.ModuleName) } -// get the minter +// GetMinter gets the minter func (k Keeper) GetMinter(ctx sdk.Context) (minter types.Minter) { store := ctx.KVStore(k.storeKey) b := store.Get(types.MinterKey) @@ -69,7 +69,7 @@ func (k Keeper) GetMinter(ctx sdk.Context) (minter types.Minter) { return } -// set the minter +// SetMinter sets the minter func (k Keeper) SetMinter(ctx sdk.Context, minter types.Minter) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshal(&minter) @@ -99,42 +99,31 @@ func (k Keeper) BondedRatio(ctx sdk.Context) sdk.Dec { return k.stakingKeeper.BondedRatio(ctx) } -// MintCoins implements an alias call to the underlying supply keeper's -// MintCoins to be used in BeginBlocker. -func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error { - if newCoins.Empty() { - // skip as no coins need to be minted - return nil - } - - return k.bankKeeper.MintCoins(ctx, types.ModuleName, newCoins) -} - -// AddCollectedFees implements an alias call to the underlying supply keeper's -// AddCollectedFees to be used in BeginBlocker. -func (k Keeper) AddCollectedFees(ctx sdk.Context, fees sdk.Coins) error { - return k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, k.feeCollectorName, fees) +// MintCoin implements an alias call to the underlying supply keeper's +// MintCoin to be used in BeginBlocker. +func (k Keeper) MintCoin(ctx sdk.Context, coin sdk.Coin) error { + return k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(coin)) } -// GetProportions gets the balance of the `MintedDenom` from minted coins and returns coins according to the `AllocationRatio`. -func (k Keeper) GetProportions(ctx sdk.Context, mintedCoin sdk.Coin, ratio sdk.Dec) sdk.Coin { +// GetProportion gets the balance of the `MintedDenom` from minted coins and returns coins according to the `AllocationRatio`. +func (k Keeper) GetProportion(ctx sdk.Context, mintedCoin sdk.Coin, ratio sdk.Dec) sdk.Coin { return sdk.NewCoin(mintedCoin.Denom, sdk.NewDecFromInt(mintedCoin.Amount).Mul(ratio).TruncateInt()) } -// DistributeMintedCoins implements distribution of minted coins from mint -// DistributeMintedCoins to be used in BeginBlocker. -func (k Keeper) DistributeMintedCoins(ctx sdk.Context, mintedCoin sdk.Coin) error { +// DistributeMintedCoin implements distribution of minted coins from mint +// to be used in BeginBlocker. +func (k Keeper) DistributeMintedCoin(ctx sdk.Context, mintedCoin sdk.Coin) error { params := k.GetParams(ctx) proportions := params.DistributionProportions // allocate staking rewards into fee collector account to be moved to on next begin blocker by staking module - stakingRewardsCoins := sdk.NewCoins(k.GetProportions(ctx, mintedCoin, proportions.Staking)) + stakingRewardsCoins := sdk.NewCoins(k.GetProportion(ctx, mintedCoin, proportions.Staking)) err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, k.feeCollectorName, stakingRewardsCoins) if err != nil { return err } - fundedAddrsCoin := k.GetProportions(ctx, mintedCoin, proportions.FundedAddresses) + fundedAddrsCoin := k.GetProportion(ctx, mintedCoin, proportions.FundedAddresses) fundedAddrsCoins := sdk.NewCoins(fundedAddrsCoin) if len(params.FundedAddresses) == 0 { // fund community pool when rewards address is empty @@ -148,7 +137,7 @@ func (k Keeper) DistributeMintedCoins(ctx sdk.Context, mintedCoin sdk.Coin) erro } else { // allocate developer rewards to developer addresses by weight for _, w := range params.FundedAddresses { - fundedAddrCoins := sdk.NewCoins(k.GetProportions(ctx, fundedAddrsCoin, w.Weight)) + fundedAddrCoins := sdk.NewCoins(k.GetProportion(ctx, fundedAddrsCoin, w.Weight)) devAddr, err := sdk.AccAddressFromBech32(w.Address) if err != nil { return errorsignite.Critical(err.Error()) diff --git a/x/mint/module.go b/x/mint/module.go index 15bad31..caa9531 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -4,22 +4,18 @@ import ( "context" "encoding/json" "fmt" - "math/rand" "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" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" "github.com/ignite/modules/x/mint/client/cli" "github.com/ignite/modules/x/mint/keeper" - "github.com/ignite/modules/x/mint/simulation" "github.com/ignite/modules/x/mint/types" ) @@ -29,6 +25,10 @@ var ( _ module.AppModuleSimulation = AppModule{} ) +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + // AppModuleBasic defines the basic application module used by the mint module. type AppModuleBasic struct { cdc codec.Codec @@ -39,8 +39,7 @@ func (AppModuleBasic) Name() string { return types.ModuleName } -// RegisterLegacyAminoCodec registers the mint module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} +func (AppModuleBasic) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {} // RegisterInterfaces registers the module's interface types func (b AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} @@ -48,26 +47,24 @@ func (b AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} // DefaultGenesis returns default genesis state as raw bytes for the mint // module. func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) + return cdc.MustMarshalJSON(types.DefaultGenesis()) } // ValidateGenesis performs genesis state validation for the mint module. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + 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 types.ValidateGenesis(data) -} - -// RegisterRESTRoutes registers the REST routes for the mint module. -func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) { + return genState.Validate() } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the mint module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } } // GetTxCmd returns no root tx command for the mint module. @@ -87,7 +84,11 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper) AppModule { +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + ak types.AccountKeeper, +) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -100,22 +101,22 @@ func (AppModule) Name() string { return types.ModuleName } -// RegisterInvariants registers the mint module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// Route returns the message routing key for the mint module. -func (AppModule) Route() sdk.Route { return sdk.Route{} } - -// QuerierRoute returns the mint module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute +// Route returns the mint module's message routing key. +func (am AppModule) Route() sdk.Route { + return sdk.Route{} } -// LegacyQuerierHandler returns the mint module sdk.Querier. +// QuerierRoute returns the mint module's query routing key. +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler returns the mint module's Querier. func (am AppModule) LegacyQuerierHandler(_ *codec.LegacyAmino) sdk.Querier { return nil } +// RegisterInvariants registers the mint module invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + // RegisterServices registers a gRPC query service to respond to the // module-specific gRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { @@ -144,7 +145,7 @@ func (AppModule) ConsensusVersion() uint64 { return 1 } // BeginBlock returns the begin blocker for the mint module. func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - if err := BeginBlocker(ctx, am.keeper); err != nil { + if err := am.keeper.BeginBlocker(ctx); err != nil { ctx.Logger().Error( fmt.Sprintf("error minting new coins: %s", err.Error()), @@ -157,30 +158,3 @@ func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } - -// AppModuleSimulation functions - -// GenerateGenesisState creates a randomized GenState of the mint module. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { - return nil -} - -// RandomizedParams creates randomized mint param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { - return simulation.ParamChanges(r) -} - -// RegisterStoreDecoder registers a decoder for mint module's types. -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) -} - -// WeightedOperations doesn't return any mint module operation. -func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { - return nil -} diff --git a/x/mint/module_simulation.go b/x/mint/module_simulation.go new file mode 100644 index 0000000..420b84f --- /dev/null +++ b/x/mint/module_simulation.go @@ -0,0 +1,39 @@ +package mint + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + + "github.com/ignite/modules/x/mint/simulation" + "github.com/ignite/modules/x/mint/types" +) + +// AppModuleSimulation functions + +// GenerateGenesisState creates a randomized GenState of the mint module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { + return nil +} + +// RandomizedParams creates randomized mint param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { + return simulation.ParamChanges(r) +} + +// RegisterStoreDecoder registers a decoder for mint module's types. +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) +} + +// WeightedOperations doesn't return any mint module operation. +func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { + return nil +} diff --git a/x/mint/types/genesis.go b/x/mint/types/genesis.go index 3d2f761..2e212d6 100644 --- a/x/mint/types/genesis.go +++ b/x/mint/types/genesis.go @@ -8,20 +8,20 @@ func NewGenesisState(minter Minter, params Params) *GenesisState { } } -// DefaultGenesisState creates a default GenesisState object -func DefaultGenesisState() *GenesisState { +// DefaultGenesis creates a default GenesisState object +func DefaultGenesis() *GenesisState { return &GenesisState{ Minter: DefaultInitialMinter(), Params: DefaultParams(), } } -// ValidateGenesis validates the provided genesis state to ensure the +// Validate validates the provided genesis state to ensure the // expected invariants holds. -func ValidateGenesis(data GenesisState) error { - if err := data.Params.Validate(); err != nil { +func (gs GenesisState) Validate() error { + if err := gs.Params.Validate(); err != nil { return err } - return ValidateMinter(data.Minter) + return ValidateMinter(gs.Minter) } diff --git a/x/mint/types/keys.go b/x/mint/types/keys.go index e1c7787..c0842b9 100644 --- a/x/mint/types/keys.go +++ b/x/mint/types/keys.go @@ -12,9 +12,4 @@ const ( // QuerierRoute is the querier route for the minting store. QuerierRoute = StoreKey - - // Query endpoints supported by the minting querier - QueryParameters = "parameters" - QueryInflation = "inflation" - QueryAnnualProvisions = "annual_provisions" )