Skip to content

Commit

Permalink
refactor(mint): cleanup module (#58)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
Alex Johnson and lumtis authored Oct 1, 2022
1 parent 53940aa commit 622a29a
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 113 deletions.
15 changes: 6 additions & 9 deletions x/mint/abci.go → x/mint/keeper/abci.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package mint
package keeper

import (
"time"

"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
Expand All @@ -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() {
Expand Down
7 changes: 7 additions & 0 deletions x/mint/keeper/abci_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package keeper_test

import "testing"

// TODO add test
func TestBeginBlocker(t *testing.T) {
}
14 changes: 0 additions & 14 deletions x/mint/keeper/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
39 changes: 14 additions & 25 deletions x/mint/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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())
Expand Down
82 changes: 28 additions & 54 deletions x/mint/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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
Expand All @@ -39,35 +39,32 @@ 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) {}

// 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.
Expand All @@ -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,
Expand All @@ -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) {
Expand Down Expand Up @@ -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()),
Expand All @@ -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
}
39 changes: 39 additions & 0 deletions x/mint/module_simulation.go
Original file line number Diff line number Diff line change
@@ -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
}
12 changes: 6 additions & 6 deletions x/mint/types/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
5 changes: 0 additions & 5 deletions x/mint/types/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

0 comments on commit 622a29a

Please sign in to comment.