diff --git a/go.mod b/go.mod index dd43102a..64675dd7 100644 --- a/go.mod +++ b/go.mod @@ -4,18 +4,25 @@ go 1.21 require ( cosmossdk.io/api v0.7.2 + cosmossdk.io/client/v2 v2.0.0-beta.1 + cosmossdk.io/collections v0.4.0 + cosmossdk.io/core v0.11.0 + cosmossdk.io/depinject v1.0.0-alpha.4 cosmossdk.io/errors v1.0.0 cosmossdk.io/log v1.2.1 cosmossdk.io/math v1.2.0 cosmossdk.io/store v1.0.0 + cosmossdk.io/tools/confix v0.1.0 + cosmossdk.io/x/circuit v0.1.0 cosmossdk.io/x/evidence v0.1.0 cosmossdk.io/x/feegrant v0.1.0 + cosmossdk.io/x/tx v0.12.0 cosmossdk.io/x/upgrade v0.1.0 github.com/CosmWasm/wasmd v0.50.0 github.com/Masterminds/sprig/v3 v3.2.3 - github.com/armon/go-metrics v0.4.1 github.com/cometbft/cometbft v0.38.1 github.com/cometbft/cometbft-db v0.8.0 + github.com/cosmos/cosmos-db v1.0.0 github.com/cosmos/cosmos-proto v1.0.0-beta.3 github.com/cosmos/cosmos-sdk v0.50.1 github.com/cosmos/gogoproto v1.4.11 @@ -25,6 +32,7 @@ require ( github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 github.com/grpc-ecosystem/grpc-gateway v1.16.0 + github.com/hashicorp/go-metrics v0.5.1 github.com/ichiban/prolog v1.1.0 github.com/ignite/cli v0.27.1 github.com/nuts-foundation/go-did v0.4.0 @@ -35,6 +43,7 @@ require ( github.com/spf13/cast v1.5.1 github.com/spf13/cobra v1.8.0 github.com/spf13/pflag v1.0.5 + github.com/spf13/viper v1.17.0 github.com/stretchr/testify v1.8.4 golang.org/x/net v0.19.0 google.golang.org/genproto/googleapis/api v0.0.0-20231012201019-e917dd12ba7a @@ -62,10 +71,6 @@ require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v1.1.3 // indirect cloud.google.com/go/storage v1.30.1 // indirect - cosmossdk.io/collections v0.4.0 // indirect - cosmossdk.io/core v0.11.0 // indirect - cosmossdk.io/depinject v1.0.0-alpha.4 // indirect - cosmossdk.io/x/tx v0.12.0 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -96,13 +101,14 @@ require ( github.com/cockroachdb/redact v1.1.5 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/cosmos-db v1.0.0 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.0.0 // indirect github.com/cosmos/ics23/go v0.10.0 // indirect github.com/cosmos/ledger-cosmos-go v0.13.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect + github.com/creachadair/atomicfile v0.3.1 // indirect + github.com/creachadair/tomledit v0.0.24 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect @@ -150,7 +156,6 @@ require ( github.com/hashicorp/go-getter v1.7.1 // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/go-metrics v0.5.1 // indirect github.com/hashicorp/go-plugin v1.5.2 // indirect github.com/hashicorp/go-safetemp v1.0.0 // indirect github.com/hashicorp/go-version v1.6.0 // indirect @@ -225,7 +230,6 @@ require ( github.com/smarty/assertions v1.15.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.10.0 // indirect - github.com/spf13/viper v1.17.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/tendermint/go-amino v0.16.0 // indirect diff --git a/go.sum b/go.sum index 868e190d..2c978782 100644 --- a/go.sum +++ b/go.sum @@ -205,6 +205,8 @@ cosmossdk.io/math v1.2.0 h1:8gudhTkkD3NxOP2YyyJIYYmt6dQ55ZfJkDOaxXpy7Ig= cosmossdk.io/math v1.2.0/go.mod h1:l2Gnda87F0su8a/7FEKJfFdJrM0JZRXQaohlgJeyQh0= cosmossdk.io/store v1.0.0 h1:6tnPgTpTSIskaTmw/4s5C9FARdgFflycIc9OX8i1tOI= cosmossdk.io/store v1.0.0/go.mod h1:ABMprwjvx6IpMp8l06TwuMrj6694/QP5NIW+X6jaTYc= +cosmossdk.io/tools/confix v0.1.0 h1:2OOZTtQsDT5e7P3FM5xqM0bPfluAxZlAwxqaDmYBE+E= +cosmossdk.io/tools/confix v0.1.0/go.mod h1:TdXKVYs4gEayav5wM+JHT+kTU2J7fozFNqoVaN+8CdY= cosmossdk.io/x/circuit v0.1.0 h1:IAej8aRYeuOMritczqTlljbUVHq1E85CpBqaCTwYgXs= cosmossdk.io/x/circuit v0.1.0/go.mod h1:YDzblVE8+E+urPYQq5kq5foRY/IzhXovSYXb4nwd39w= cosmossdk.io/x/evidence v0.1.0 h1:J6OEyDl1rbykksdGynzPKG5R/zm6TacwW2fbLTW4nCk= @@ -276,8 +278,6 @@ github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= -github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= @@ -416,6 +416,10 @@ github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwc github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creachadair/atomicfile v0.3.1 h1:yQORkHjSYySh/tv5th1dkKcn02NEW5JleB84sjt+W4Q= +github.com/creachadair/atomicfile v0.3.1/go.mod h1:mwfrkRxFKwpNAflYZzytbSwxvbK6fdGRRlp0KEQc0qU= +github.com/creachadair/tomledit v0.0.24 h1:5Xjr25R2esu1rKCbQEmjZYlrhFkDspoAbAKb6QKQDhQ= +github.com/creachadair/tomledit v0.0.24/go.mod h1:9qHbShRWQzSCcn617cMzg4eab1vbLCOjOshAWSzWr8U= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= diff --git a/x/mint/abci.go b/x/mint/abci.go index 0255a250..3f069e9e 100644 --- a/x/mint/abci.go +++ b/x/mint/abci.go @@ -1,6 +1,7 @@ package mint import ( + "context" "time" "github.com/cosmos/cosmos-sdk/telemetry" @@ -11,22 +12,30 @@ import ( ) // BeginBlocker mints new tokens for the previous block. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { +func BeginBlocker(ctx context.Context, k keeper.Keeper) error { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) // fetch stored params - params := k.GetParams(ctx) + params, err := k.Params.Get(ctx) + if err != nil { + return err + } // recalculate inflation rate totalSupply := k.TokenSupply(ctx, params.MintDenom) - bondedRatio := k.BondedRatio(ctx) + bondedRatio, err := k.BondedRatio(ctx) + if err != nil { + return err + } minter, err := types.NewMinterWithInflationCoef(params.InflationCoef, bondedRatio, totalSupply) if err != nil { panic(err) } - k.SetMinter(ctx, minter) + if err = k.Minter.Set(ctx, minter); err != nil { + return err + } // mint coins, update supply mintedCoin := minter.BlockProvision(params) @@ -47,7 +56,8 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { defer telemetry.ModuleSetGauge(types.ModuleName, float32(mintedCoin.Amount.Int64()), "minted_tokens") } - ctx.EventManager().EmitEvent( + sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeMint, sdk.NewAttribute(types.AttributeKeyBondedRatio, bondedRatio.String()), @@ -56,4 +66,6 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()), ), ) + + return nil } diff --git a/x/mint/keeper/genesis.go b/x/mint/keeper/genesis.go index 7f6b088c..19ab12b4 100644 --- a/x/mint/keeper/genesis.go +++ b/x/mint/keeper/genesis.go @@ -1,26 +1,35 @@ package keeper import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okp4/okp4d/x/mint/types" ) -// InitGenesis new mint genesis. -func (k Keeper) InitGenesis(ctx sdk.Context, ak types.AccountKeeper, data *types.GenesisState) { - k.SetMinter(ctx, data.Minter) - err := k.SetParams(ctx, data.Params) - if err != nil { - panic(errorsmod.Wrapf(err, "error setting params")) +// InitGenesis new mint genesis +func (keeper Keeper) InitGenesis(ctx sdk.Context, ak types.AccountKeeper, data *types.GenesisState) { + if err := keeper.Minter.Set(ctx, data.Minter); err != nil { + panic(err) + } + + if err := keeper.Params.Set(ctx, data.Params); err != nil { + panic(err) } + ak.GetModuleAccount(ctx, types.ModuleName) } // ExportGenesis returns a GenesisState for a given context and keeper. -func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - minter := k.GetMinter(ctx) - params := k.GetParams(ctx) +func (keeper Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { + minter, err := keeper.Minter.Get(ctx) + if err != nil { + panic(err) + } + + params, err := keeper.Params.Get(ctx) + if err != nil { + panic(err) + } + return types.NewGenesisState(minter, params) } diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 959484a9..d303e933 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -6,8 +6,8 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -58,10 +58,10 @@ func (s *GenesisTestSuite) SetupTest() { func (s *GenesisTestSuite) TestImportExportGenesis() { genesisState := types.DefaultGenesisState() - genesisState.Minter = types.NewMinter(sdk.OneDec(), sdk.NewDecWithPrec(20, 2)) + genesisState.Minter = types.NewMinter(sdk.OneDec(), math.LegacyNewDecWithPrec(20, 2)) genesisState.Params = types.NewParams( "testDenom", - sdk.NewDecWithPrec(69, 2), + math.LegacyNewDecWithPrec(69, 2), uint64(60*60*8766/5), ) diff --git a/x/mint/keeper/grpc_query.go b/x/mint/keeper/grpc_query.go index ce2006c7..8a940450 100644 --- a/x/mint/keeper/grpc_query.go +++ b/x/mint/keeper/grpc_query.go @@ -3,35 +3,47 @@ package keeper import ( "context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/okp4/okp4d/x/mint/types" ) -var _ types.QueryServer = Keeper{} +var _ types.QueryServer = queryServer{} + +func NewQueryServerImpl(k Keeper) types.QueryServer { + return queryServer{k} +} + +type queryServer struct { + k Keeper +} // Params returns params of the mint module. -func (k Keeper) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - params := k.GetParams(ctx) +func (q queryServer) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + params, err := q.k.Params.Get(c) + if err != nil { + return nil, err + } return &types.QueryParamsResponse{Params: params}, nil } // Inflation returns minter.Inflation of the mint module. -func (k Keeper) Inflation(c context.Context, _ *types.QueryInflationRequest) (*types.QueryInflationResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - minter := k.GetMinter(ctx) +func (q queryServer) Inflation(c context.Context, _ *types.QueryInflationRequest) (*types.QueryInflationResponse, error) { + minter, err := q.k.Minter.Get(c) + if err != nil { + return nil, err + } return &types.QueryInflationResponse{Inflation: minter.Inflation}, nil } // AnnualProvisions returns minter.AnnualProvisions of the mint module. -func (k Keeper) AnnualProvisions(c context.Context, +func (q queryServer) AnnualProvisions(c context.Context, _ *types.QueryAnnualProvisionsRequest, ) (*types.QueryAnnualProvisionsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - minter := k.GetMinter(ctx) + minter, err := q.k.Minter.Get(c) + if err != nil { + return nil, err + } return &types.QueryAnnualProvisionsResponse{AnnualProvisions: minter.AnnualProvisions}, nil } diff --git a/x/mint/keeper/grpc_query_test.go b/x/mint/keeper/grpc_query_test.go index c150871a..7019e411 100644 --- a/x/mint/keeper/grpc_query_test.go +++ b/x/mint/keeper/grpc_query_test.go @@ -4,9 +4,12 @@ import ( gocontext "context" "testing" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" @@ -30,8 +33,8 @@ type MintTestSuite struct { func (suite *MintTestSuite) SetupTest() { encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(suite.T(), key, sdk.NewTransientStoreKey("transient_test")) + key := storetypes.NewKVStoreKey(types.StoreKey) + testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx // gomock initializations @@ -44,7 +47,7 @@ func (suite *MintTestSuite) SetupTest() { suite.mintKeeper = keeper.NewKeeper( encCfg.Codec, - key, + runtime.NewKVStoreService(key), stakingKeeper, accountKeeper, bankKeeper, @@ -52,12 +55,13 @@ func (suite *MintTestSuite) SetupTest() { authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - err := suite.mintKeeper.SetParams(suite.ctx, types.DefaultParams()) + err := suite.mintKeeper.Params.Set(suite.ctx, types.DefaultParams()) + suite.Require().NoError(err) + err = suite.mintKeeper.Minter.Set(suite.ctx, types.DefaultInitialMinter()) suite.Require().NoError(err) - suite.mintKeeper.SetMinter(suite.ctx, types.DefaultInitialMinter()) queryHelper := baseapp.NewQueryServerTestHelper(testCtx.Ctx, encCfg.InterfaceRegistry) - types.RegisterQueryServer(queryHelper, suite.mintKeeper) + types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.mintKeeper)) suite.queryClient = types.NewQueryClient(queryHelper) } @@ -65,15 +69,21 @@ func (suite *MintTestSuite) SetupTest() { func (suite *MintTestSuite) TestGRPCParams() { params, err := suite.queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) suite.Require().NoError(err) - suite.Require().Equal(params.Params, suite.mintKeeper.GetParams(suite.ctx)) + kParams, err := suite.mintKeeper.Params.Get(suite.ctx) + suite.Require().NoError(err) + suite.Require().Equal(params.Params, kParams) inflation, err := suite.queryClient.Inflation(gocontext.Background(), &types.QueryInflationRequest{}) suite.Require().NoError(err) - suite.Require().Equal(inflation.Inflation, suite.mintKeeper.GetMinter(suite.ctx).Inflation) + minter, err := suite.mintKeeper.Minter.Get(suite.ctx) + suite.Require().NoError(err) + suite.Require().Equal(inflation.Inflation, minter) annualProvisions, err := suite.queryClient.AnnualProvisions(gocontext.Background(), &types.QueryAnnualProvisionsRequest{}) suite.Require().NoError(err) - suite.Require().Equal(annualProvisions.AnnualProvisions, suite.mintKeeper.GetMinter(suite.ctx).AnnualProvisions) + minter, err = suite.mintKeeper.Minter.Get(suite.ctx) + suite.Require().NoError(err) + suite.Require().Equal(annualProvisions.AnnualProvisions, minter) } func TestMintTestSuite(t *testing.T) { diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 91ac6c65..af7d4402 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -1,12 +1,16 @@ package keeper import ( - "github.com/cometbft/cometbft/libs/log" + "context" + + "cosmossdk.io/core/store" + + "cosmossdk.io/collections" + "cosmossdk.io/log" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okp4/okp4d/x/mint/types" @@ -14,19 +18,23 @@ import ( // Keeper of the mint store. type Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey + cdc codec.BinaryCodec + storeService store.KVStoreService // the address capable of executing a MsgUpdateParams message. Typically, this should be the x/gov module account. authority sdk.AccAddress stakingKeeper types.StakingKeeper bankKeeper types.BankKeeper feeCollectorName string + + Schema collections.Schema + Params collections.Item[types.Params] + Minter collections.Item[types.Minter] } // NewKeeper creates a new mint Keeper instance. func NewKeeper( cdc codec.BinaryCodec, - key storetypes.StoreKey, + storeService store.KVStoreService, sk types.StakingKeeper, ak types.AccountKeeper, bk types.BankKeeper, @@ -47,14 +55,25 @@ func NewKeeper( panic(err) } - return Keeper{ + sb := collections.NewSchemaBuilder(storeService) + k := Keeper{ cdc: cdc, - storeKey: key, + storeService: storeService, authority: addr, stakingKeeper: sk, bankKeeper: bk, feeCollectorName: feeCollectorName, + Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)), + Minter: collections.NewItem(sb, types.MinterKey, "minter", codec.CollValue[types.Minter](cdc)), + } + + schema, err := sb.Build() + if err != nil { + panic(err) } + k.Schema = schema + + return k } // GetAuthority returns the x/mint module's authority. @@ -63,76 +82,32 @@ func (k Keeper) GetAuthority() string { } // Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+types.ModuleName) -} - -// GetMinter get the minter. -func (k Keeper) GetMinter(ctx sdk.Context) (minter types.Minter) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.MinterKey) - if b == nil { - panic("stored minter should not have been nil") - } - - k.cdc.MustUnmarshal(b, &minter) - return -} - -// SetMinter set the minter. -func (k Keeper) SetMinter(ctx sdk.Context, minter types.Minter) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&minter) - store.Set(types.MinterKey, b) -} - -// GetParams returns the total set of minting parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) - if bz == nil { - return params - } - k.cdc.MustUnmarshal(bz, ¶ms) - return params -} - -// SetParams sets the total set of minting parameters. -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - if err := params.Validate(); err != nil { - return err - } - - store := ctx.KVStore(k.storeKey) - bz, err := k.cdc.Marshal(¶ms) - if err != nil { - return err - } - store.Set(types.ParamsKey, bz) - return nil +func (k Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return sdkCtx.Logger().With("module", "x/"+types.ModuleName) } // TokenSupply implements an alias call to the underlying bank keeper's // TokenSupply to be used in BeginBlocker. -func (k Keeper) TokenSupply(ctx sdk.Context, denom string) math.Int { +func (k Keeper) TokenSupply(ctx context.Context, denom string) math.Int { return k.bankKeeper.GetSupply(ctx, denom).Amount } // StakingTokenSupply implements an alias call to the underlying staking keeper's // StakingTokenSupply to be used in BeginBlocker. -func (k Keeper) StakingTokenSupply(ctx sdk.Context) math.Int { +func (k Keeper) StakingTokenSupply(ctx context.Context) (math.Int, error) { return k.stakingKeeper.StakingTokenSupply(ctx) } // BondedRatio implements an alias call to the underlying staking keeper's // BondedRatio to be used in BeginBlocker. -func (k Keeper) BondedRatio(ctx sdk.Context) sdk.Dec { +func (k Keeper) BondedRatio(ctx context.Context) (math.LegacyDec, error) { 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 { +func (k Keeper) MintCoins(ctx context.Context, newCoins sdk.Coins) error { if newCoins.Empty() { // skip as no coins need to be minted return nil @@ -143,6 +118,6 @@ func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error { // 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 { +func (k Keeper) AddCollectedFees(ctx context.Context, fees sdk.Coins) error { return k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, k.feeCollectorName, fees) } diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 4623bc10..53b7d280 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -78,7 +78,7 @@ func (s *IntegrationTestSuite) TestParams() { name: "set invalid params", input: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationCoef: sdk.NewDecWithPrec(-73, 2), + InflationCoef: math.LegacyNewDecWithPrec(-73, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, expectErr: true, @@ -87,7 +87,7 @@ func (s *IntegrationTestSuite) TestParams() { name: "set full valid params", input: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationCoef: sdk.NewDecWithPrec(73, 2), + InflationCoef: math.LegacyNewDecWithPrec(73, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, expectErr: false, @@ -118,7 +118,7 @@ func (s *IntegrationTestSuite) TestAliasFunctions() { s.stakingKeeper.EXPECT().StakingTokenSupply(s.ctx).Return(stakingTokenSupply) s.Require().Equal(s.mintKeeper.StakingTokenSupply(s.ctx), stakingTokenSupply) - bondedRatio := sdk.NewDecWithPrec(15, 2) + bondedRatio := math.LegacyNewDecWithPrec(15, 2) s.stakingKeeper.EXPECT().BondedRatio(s.ctx).Return(bondedRatio) s.Require().Equal(s.mintKeeper.BondedRatio(s.ctx), bondedRatio) diff --git a/x/mint/keeper/migrations.go b/x/mint/keeper/migrations.go index 8ed612a9..cf45891b 100644 --- a/x/mint/keeper/migrations.go +++ b/x/mint/keeper/migrations.go @@ -17,5 +17,5 @@ func NewMigrator(keeper Keeper) Migrator { } func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, ctx.KVStore(m.keeper.storeKey), m.keeper.cdc) + return v3.MigrateStore(ctx, m.keeper.storeService.OpenKVStore(ctx), m.keeper.cdc) } diff --git a/x/mint/keeper/msg_server.go b/x/mint/keeper/msg_server.go index 4114b03d..9f46a832 100644 --- a/x/mint/keeper/msg_server.go +++ b/x/mint/keeper/msg_server.go @@ -34,7 +34,7 @@ func (ms msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdatePara } ctx := sdk.UnwrapSDKContext(goCtx) - if err := ms.SetParams(ctx, req.Params); err != nil { + if err := ms.Params.Set(ctx, req.Params); err != nil { return nil, err } diff --git a/x/mint/keeper/msg_server_test.go b/x/mint/keeper/msg_server_test.go index ac18821b..24c30c40 100644 --- a/x/mint/keeper/msg_server_test.go +++ b/x/mint/keeper/msg_server_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okp4/okp4d/x/mint/types" @@ -25,7 +26,7 @@ func (s *IntegrationTestSuite) TestUpdateParams() { Authority: s.mintKeeper.GetAuthority(), Params: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationCoef: sdk.NewDecWithPrec(-73, 2), + InflationCoef: math.LegacyNewDecWithPrec(-73, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, }, @@ -37,7 +38,7 @@ func (s *IntegrationTestSuite) TestUpdateParams() { Authority: s.mintKeeper.GetAuthority(), Params: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationCoef: sdk.NewDecWithPrec(73, 2), + InflationCoef: math.LegacyNewDecWithPrec(73, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, }, diff --git a/x/mint/migrations/v3/migrations.go b/x/mint/migrations/v3/migrations.go index 1ba114eb..b9dba248 100644 --- a/x/mint/migrations/v3/migrations.go +++ b/x/mint/migrations/v3/migrations.go @@ -1,6 +1,7 @@ package v3 import ( + storetypes "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,7 +13,7 @@ import ( // version 3. // This version include new/deleted parameters in store. func MigrateStore(ctx sdk.Context, - store sdk.KVStore, + store storetypes.KVStore, cdc codec.BinaryCodec, ) error { logger := ctx.Logger(). @@ -24,8 +25,11 @@ func MigrateStore(ctx sdk.Context, logger.Debug("migrate old mint params with new params") var oldParams oldTypes.Params - d := store.Get(types.ParamsKey) - err := cdc.Unmarshal(d, &oldParams) + d, err := store.Get(types.ParamsKey) + if err != nil { + return err + } + err = cdc.Unmarshal(d, &oldParams) if err != nil { return err } @@ -42,7 +46,10 @@ func MigrateStore(ctx sdk.Context, logger.Debug("migrate minter store") var oldMinter oldTypes.Minter - d = store.Get(types.MinterKey) + d, err = store.Get(types.MinterKey) + if err != nil { + return err + } err = cdc.Unmarshal(d, &oldMinter) if err != nil { return err diff --git a/x/mint/migrations/v3/types/minter.pb.go b/x/mint/migrations/v3/types/minter.pb.go index 14252479..657e8232 100644 --- a/x/mint/migrations/v3/types/minter.pb.go +++ b/x/mint/migrations/v3/types/minter.pb.go @@ -5,19 +5,23 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" io "io" math "math" math_bits "math/bits" + + github_com_cosmos_cosmos_sdk_types "cosmossdk.io/math" + + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" ) // Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +var ( + _ = proto.Marshal + _ = fmt.Errorf + _ = 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. @@ -33,9 +37,9 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // and `target_supply` 230M. type Minter struct { // current annual inflation rate - Inflation github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=inflation,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"inflation"` + Inflation github_com_cosmos_cosmos_sdk_types.LegacyDec `protobuf:"bytes,1,opt,name=inflation,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"inflation"` // current annual expected provisions - AnnualProvisions github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=annual_provisions,json=annualProvisions,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"annual_provisions"` + AnnualProvisions github_com_cosmos_cosmos_sdk_types.LegacyDec `protobuf:"bytes,2,opt,name=annual_provisions,json=annualProvisions,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"annual_provisions"` // target supply at end of period TargetSupply github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=target_supply,json=targetSupply,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"target_supply"` } @@ -46,9 +50,11 @@ func (*Minter) ProtoMessage() {} func (*Minter) Descriptor() ([]byte, []int) { return fileDescriptor_06339c129491fd39, []int{0} } + func (m *Minter) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } + func (m *Minter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Minter.Marshal(b, m, deterministic) @@ -61,12 +67,15 @@ func (m *Minter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return b[:n], nil } } + func (m *Minter) XXX_Merge(src proto.Message) { xxx_messageInfo_Minter.Merge(m, src) } + func (m *Minter) XXX_Size() int { return m.Size() } + func (m *Minter) XXX_DiscardUnknown() { xxx_messageInfo_Minter.DiscardUnknown(m) } @@ -83,7 +92,7 @@ type Params struct { // type of coin to mint MintDenom string `protobuf:"bytes,1,opt,name=mint_denom,json=mintDenom,proto3" json:"mint_denom,omitempty"` // annual reduction factor inflation rate change - AnnualReductionFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=annual_reduction_factor,json=annualReductionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"annual_reduction_factor"` + AnnualReductionFactor github_com_cosmos_cosmos_sdk_types.LegacyDec `protobuf:"bytes,2,opt,name=annual_reduction_factor,json=annualReductionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"annual_reduction_factor"` // expected blocks per year BlocksPerYear uint64 `protobuf:"varint,3,opt,name=blocks_per_year,json=blocksPerYear,proto3" json:"blocks_per_year,omitempty"` } @@ -93,9 +102,11 @@ func (*Params) ProtoMessage() {} func (*Params) Descriptor() ([]byte, []int) { return fileDescriptor_06339c129491fd39, []int{1} } + 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) @@ -108,12 +119,15 @@ func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -278,6 +292,7 @@ func encodeVarintMint(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } + func (m *Minter) Size() (n int) { if m == nil { return 0 @@ -314,9 +329,11 @@ func (m *Params) Size() (n int) { func sovMint(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } + func sozMint(x uint64) (n int) { return sovMint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } + func (m *Minter) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -469,6 +486,7 @@ func (m *Minter) Unmarshal(dAtA []byte) error { } return nil } + func (m *Params) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -604,6 +622,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { } return nil } + func skipMint(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/mint/migrations/v3/types/params.go b/x/mint/migrations/v3/types/params.go index 85b9a5ee..e7c6a100 100644 --- a/x/mint/migrations/v3/types/params.go +++ b/x/mint/migrations/v3/types/params.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "cosmossdk.io/math" + "sigs.k8s.io/yaml" sdk "github.com/cosmos/cosmos-sdk/types" @@ -18,7 +20,7 @@ var ( ) func NewParams( - mintDenom string, annualReductionFactor sdk.Dec, blocksPerYear uint64, + mintDenom string, annualReductionFactor math.LegacyDec, blocksPerYear uint64, ) Params { return Params{ MintDenom: mintDenom, @@ -31,8 +33,8 @@ func NewParams( func DefaultParams() Params { return Params{ MintDenom: sdk.DefaultBondDenom, - AnnualReductionFactor: sdk.NewDecWithPrec(20, 2), // Tha annual reduction factor is configured to 20% per year - BlocksPerYear: uint64(60 * 60 * 8766 / 5), // assuming 5-second block times + AnnualReductionFactor: math.LegacyNewDecWithPrec(20, 2), // Tha annual reduction factor is configured to 20% per year + BlocksPerYear: uint64(60 * 60 * 8766 / 5), // assuming 5-second block times } } @@ -68,7 +70,7 @@ func validateMintDenom(i interface{}) error { } func validateAnnualReductionFactor(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } @@ -76,7 +78,7 @@ func validateAnnualReductionFactor(i interface{}) error { if v.IsNegative() { return fmt.Errorf("annual reduction factor cannot be negative: %s", v) } - if v.GT(sdk.OneDec()) { + if v.GT(math.LegacyOneDec()) { return fmt.Errorf("annual reduction factor too large: %s", v) } diff --git a/x/mint/module.go b/x/mint/module.go index b9d133d9..0cacd89f 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -5,10 +5,10 @@ import ( "encoding/json" "fmt" - "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/okp4/okp4d/x/mint/client/cli" "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" + "cosmossdk.io/core/appmodule" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -16,17 +16,21 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/okp4/okp4d/x/mint/client/cli" "github.com/okp4/okp4d/x/mint/keeper" "github.com/okp4/okp4d/x/mint/simulation" "github.com/okp4/okp4d/x/mint/types" ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModule{} _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} + _ module.HasServices = AppModule{} + + _ appmodule.AppModule = AppModule{} + _ appmodule.HasBeginBlocker = AppModule{} ) // AppModuleBasic defines the basic application module used by the mint module. @@ -34,8 +38,6 @@ type AppModuleBasic struct { cdc codec.Codec } -var _ module.AppModuleBasic = AppModuleBasic{} - // Name returns the mint module's name. func (AppModuleBasic) Name() string { return types.ModuleName @@ -65,6 +67,11 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingCo return types.ValidateGenesis(data) } +// GetQueryCmd returns no root query command for the wasm module. +func (b AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the mint module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { @@ -72,14 +79,6 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *r } } -// GetTxCmd returns no root tx command for the mint module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } - -// GetQueryCmd returns the root query command for the mint module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - // AppModule implements an application module for the mint module. type AppModule struct { AppModuleBasic @@ -97,19 +96,15 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper) } } -// Name returns the mint module's name. -func (AppModule) Name() string { - return types.ModuleName -} +func (am AppModule) IsOnePerModuleType() {} -// RegisterInvariants registers the mint module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} +func (am AppModule) IsAppModule() {} // 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) + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) migrator := keeper.NewMigrator(am.keeper) @@ -130,12 +125,11 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the mint module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) am.keeper.InitGenesis(ctx, am.authKeeper, &genesisState) - return []abci.ValidatorUpdate{} } // ExportGenesis returns the exported genesis state as raw bytes for the mint @@ -149,8 +143,8 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw func (AppModule) ConsensusVersion() uint64 { return 3 } // BeginBlock returns the begin blocker for the mint module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) +func (am AppModule) BeginBlock(ctx context.Context) error { + return BeginBlocker(ctx, am.keeper) } // AppModuleSimulation functions @@ -166,8 +160,8 @@ func (AppModule) ProposalMsgs(_ module.SimulationState) []simtypes.WeightedPropo } // RegisterStoreDecoder registers a decoder for mint module's types. -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) +func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { + sdr[types.StoreKey] = simtypes.NewStoreDecoderFuncFromCollectionsSchema(am.keeper.Schema) } // WeightedOperations doesn't return any mint module operation. diff --git a/x/mint/module_test.go b/x/mint/module_test.go index a692efa7..34db3e6d 100644 --- a/x/mint/module_test.go +++ b/x/mint/module_test.go @@ -3,9 +3,10 @@ package mint_test import ( "testing" - "github.com/stretchr/testify/require" + "cosmossdk.io/depinject" + "cosmossdk.io/log" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" @@ -17,10 +18,14 @@ import ( func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { var accountKeeper authkeeper.AccountKeeper - app, err := simtestutil.SetupAtGenesis(testutil.AppConfig, &accountKeeper) + app, err := simtestutil.SetupAtGenesis( + depinject.Configs( + testutil.AppConfig, + depinject.Supply(log.NewNopLogger()), + ), &accountKeeper) require.NoError(t, err) - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) + ctx := app.BaseApp.NewContext(false) acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) require.NotNil(t, acc) } diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index c54d5bbb..da8def1c 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -7,6 +7,8 @@ import ( "fmt" "math/rand" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -20,13 +22,13 @@ const ( ) // GenInflation randomized Inflation. -func GenInflation(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) +func GenInflation(r *rand.Rand) math.LegacyDec { + return math.LegacyNewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflationCoefMax randomized AnnualReductionFactor. -func GenInflationCoefMax(_ *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(73, 3) +func GenInflationCoefMax(_ *rand.Rand) math.LegacyDec { + return math.LegacyNewDecWithPrec(73, 3) } // RandomizedGenState generates a random GenesisState for mint. @@ -34,17 +36,17 @@ func GenInflationCoefMax(_ *rand.Rand) sdk.Dec { //nolint:forbidigo func RandomizedGenState(simState *module.SimulationState) { // minter - var inflation sdk.Dec + var inflation math.LegacyDec simState.AppParams.GetOrGenerate( - simState.Cdc, Inflation, &inflation, simState.Rand, + Inflation, &inflation, simState.Rand, func(r *rand.Rand) { inflation = GenInflation(r) }, ) // params - var inflationCoef sdk.Dec + var inflationCoef math.LegacyDec simState.AppParams.GetOrGenerate( - simState.Cdc, InflationCoef, &inflationCoef, simState.Rand, + InflationCoef, &inflationCoef, simState.Rand, func(r *rand.Rand) { inflationCoef = GenInflationCoefMax(r) }, ) diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 6fcdf4f9..b858869f 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -8,11 +8,10 @@ import ( "github.com/stretchr/testify/require" - sdkmath "cosmossdk.io/math" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" codectypes "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" @@ -35,7 +34,7 @@ func TestRandomizedGenState(t *testing.T) { Rand: r, NumBonded: 3, Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), + InitialStake: math.NewInt(1000), GenState: make(map[string]json.RawMessage), } @@ -44,8 +43,8 @@ func TestRandomizedGenState(t *testing.T) { var mintGenesis types.GenesisState simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &mintGenesis) - inflationCoef := sdk.NewDecWithPrec(3, 2) - bondedRatio := sdk.NewDecWithPrec(2, 1) + inflationCoef := math.LegacyNewDecWithPrec(3, 2) + bondedRatio := math.LegacyNewDecWithPrec(2, 1) minter, _ := types.NewMinterWithInflationCoef(inflationCoef, bondedRatio, simState.InitialStake) require.Equal(t, uint64(6311520), mintGenesis.Params.BlocksPerYear) diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 1818cb9c..72edfbdb 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -3,6 +3,8 @@ package simulation import ( "math/rand" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -36,7 +38,7 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) params := types.DefaultParams() params.BlocksPerYear = uint64(simtypes.RandIntBetween(r, 1, 1000000)) - params.InflationCoef = sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 100)), 2) + params.InflationCoef = math.LegacyNewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 100)), 2) params.MintDenom = simtypes.RandStringOfLength(r, 10) return &types.MsgUpdateParams{ diff --git a/x/mint/simulation/proposals_test.go b/x/mint/simulation/proposals_test.go index 7e1a2176..d7fac019 100644 --- a/x/mint/simulation/proposals_test.go +++ b/x/mint/simulation/proposals_test.go @@ -4,6 +4,8 @@ import ( "math/rand" "testing" + "cosmossdk.io/math" + "gotest.tools/v3/assert" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" @@ -40,6 +42,6 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) assert.Equal(t, uint64(122877), msgUpdateParams.Params.BlocksPerYear) - assert.DeepEqual(t, sdk.NewDecWithPrec(95, 2), msgUpdateParams.Params.InflationCoef) + assert.DeepEqual(t, math.LegacyNewDecWithPrec(95, 2), msgUpdateParams.Params.InflationCoef) assert.Equal(t, "eAerqyNEUz", msgUpdateParams.Params.MintDenom) } diff --git a/x/mint/testutil/expected_keepers_mocks.go b/x/mint/testutil/expected_keepers_mocks.go index 5355af18..3d05852c 100644 --- a/x/mint/testutil/expected_keepers_mocks.go +++ b/x/mint/testutil/expected_keepers_mocks.go @@ -5,14 +5,12 @@ package testutil import ( + context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" - math "cosmossdk.io/math" - types "github.com/cosmos/cosmos-sdk/types" - types0 "github.com/cosmos/cosmos-sdk/x/auth/types" + gomock "github.com/golang/mock/gomock" ) // MockStakingKeeper is a mock of StakingKeeper interface. @@ -39,11 +37,12 @@ func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { } // BondedRatio mocks base method. -func (m *MockStakingKeeper) BondedRatio(ctx types.Context) types.Dec { +func (m *MockStakingKeeper) BondedRatio(ctx context.Context) (math.LegacyDec, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BondedRatio", ctx) - ret0, _ := ret[0].(types.Dec) - return ret0 + ret0, _ := ret[0].(math.LegacyDec) + ret1, _ := ret[1].(error) + return ret0, ret1 } // BondedRatio indicates an expected call of BondedRatio. @@ -53,11 +52,12 @@ func (mr *MockStakingKeeperMockRecorder) BondedRatio(ctx interface{}) *gomock.Ca } // StakingTokenSupply mocks base method. -func (m *MockStakingKeeper) StakingTokenSupply(ctx types.Context) math.Int { +func (m *MockStakingKeeper) StakingTokenSupply(ctx context.Context) (math.Int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "StakingTokenSupply", ctx) ret0, _ := ret[0].(math.Int) - return ret0 + ret1, _ := ret[1].(error) + return ret0, ret1 } // StakingTokenSupply indicates an expected call of StakingTokenSupply. @@ -90,10 +90,10 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types0.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) - ret0, _ := ret[0].(types0.ModuleAccountI) + ret0, _ := ret[0].(types.ModuleAccountI) return ret0 } @@ -118,7 +118,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types0.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(arg0 context.Context, arg1 types.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) } @@ -153,7 +153,7 @@ func (m *MockBankKeeper) EXPECT() *MockBankKeeperMockRecorder { } // GetSupply mocks base method. -func (m *MockBankKeeper) GetSupply(ctx types.Context, denom string) types.Coin { +func (m *MockBankKeeper) GetSupply(ctx context.Context, denom string) types.Coin { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSupply", ctx, denom) ret0, _ := ret[0].(types.Coin) @@ -167,7 +167,7 @@ func (mr *MockBankKeeperMockRecorder) GetSupply(ctx, denom interface{}) *gomock. } // MintCoins mocks base method. -func (m *MockBankKeeper) MintCoins(ctx types.Context, name string, amt types.Coins) error { +func (m *MockBankKeeper) MintCoins(ctx context.Context, name string, amt types.Coins) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "MintCoins", ctx, name, amt) ret0, _ := ret[0].(error) @@ -181,7 +181,7 @@ func (mr *MockBankKeeperMockRecorder) MintCoins(ctx, name, amt interface{}) *gom } // SendCoinsFromModuleToAccount mocks base method. -func (m *MockBankKeeper) SendCoinsFromModuleToAccount(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins) error { +func (m *MockBankKeeper) SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendCoinsFromModuleToAccount", ctx, senderModule, recipientAddr, amt) ret0, _ := ret[0].(error) @@ -195,7 +195,7 @@ func (mr *MockBankKeeperMockRecorder) SendCoinsFromModuleToAccount(ctx, senderMo } // SendCoinsFromModuleToModule mocks base method. -func (m *MockBankKeeper) SendCoinsFromModuleToModule(ctx types.Context, senderModule, recipientModule string, amt types.Coins) error { +func (m *MockBankKeeper) SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule string, amt types.Coins) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendCoinsFromModuleToModule", ctx, senderModule, recipientModule, amt) ret0, _ := ret[0].(error) diff --git a/x/mint/types/expected_keepers.go b/x/mint/types/expected_keepers.go index 919a6841..cf0ec5d6 100644 --- a/x/mint/types/expected_keepers.go +++ b/x/mint/types/expected_keepers.go @@ -1,16 +1,17 @@ package types // noalias import ( + "context" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) // StakingKeeper defines the expected staking keeper. type StakingKeeper interface { - StakingTokenSupply(ctx sdk.Context) math.Int - BondedRatio(ctx sdk.Context) sdk.Dec + StakingTokenSupply(ctx context.Context) (math.Int, error) + BondedRatio(ctx context.Context) (math.LegacyDec, error) } // AccountKeeper defines the contract required for account APIs. @@ -18,15 +19,15 @@ type AccountKeeper interface { GetModuleAddress(name string) sdk.AccAddress // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, types.ModuleAccountI) - GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI + SetModuleAccount(context.Context, sdk.ModuleAccountI) + GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI } // BankKeeper defines the contract needed to be fulfilled for banking and supply // dependencies. type BankKeeper interface { - GetSupply(ctx sdk.Context, denom string) sdk.Coin - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error + GetSupply(ctx context.Context, denom string) sdk.Coin + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule string, amt sdk.Coins) error + MintCoins(ctx context.Context, name string, amt sdk.Coins) error } diff --git a/x/mint/types/minter.go b/x/mint/types/minter.go index 17995f8f..a920f4bd 100644 --- a/x/mint/types/minter.go +++ b/x/mint/types/minter.go @@ -10,7 +10,7 @@ import ( // NewMinter returns a new Minter object with the given inflation, annual // provisions values. -func NewMinter(inflation, annualProvisions sdk.Dec) Minter { +func NewMinter(inflation, annualProvisions math.LegacyDec) Minter { return Minter{ Inflation: inflation, AnnualProvisions: annualProvisions, @@ -18,15 +18,15 @@ func NewMinter(inflation, annualProvisions sdk.Dec) Minter { } // NewMinterWithInitialInflation returns an initial Minter object with a given inflation value and zero annual provisions. -func NewMinterWithInitialInflation(inflation sdk.Dec) Minter { +func NewMinterWithInitialInflation(inflation math.LegacyDec) Minter { return NewMinter( inflation, - sdk.NewDec(0), + math.LegacyNewDec(0), ) } // NewMinterWithInflationCoef returns a new Minter with updated inflation and annual provisions values. -func NewMinterWithInflationCoef(inflationCoef sdk.Dec, bondedRatio sdk.Dec, totalSupply math.Int) (Minter, error) { +func NewMinterWithInflationCoef(inflationCoef math.LegacyDec, bondedRatio math.LegacyDec, totalSupply math.Int) (Minter, error) { inflationRate, err := inflationRate(inflationCoef, bondedRatio) if err != nil { return Minter{}, err @@ -40,7 +40,7 @@ func NewMinterWithInflationCoef(inflationCoef sdk.Dec, bondedRatio sdk.Dec, tota // which uses an inflation rate of 0%. func DefaultInitialMinter() Minter { return NewMinterWithInitialInflation( - sdk.NewDec(0), + math.LegacyNewDec(0), ) } @@ -55,7 +55,7 @@ func (m Minter) Validate() error { // inflationRate returns the inflation rate computed from the current bonded ratio // and the inflation parameter. -func inflationRate(inflationCoef sdk.Dec, bondedRatio sdk.Dec) (sdk.Dec, error) { +func inflationRate(inflationCoef math.LegacyDec, bondedRatio math.LegacyDec) (math.LegacyDec, error) { if bondedRatio.IsZero() { return math.LegacyZeroDec(), ErrBondedRatioIsZero } @@ -66,6 +66,6 @@ func inflationRate(inflationCoef sdk.Dec, bondedRatio sdk.Dec) (sdk.Dec, error) // BlockProvision returns the provisions for a block based on the annual // provisions rate. func (m Minter) BlockProvision(params Params) sdk.Coin { - provisionAmt := m.AnnualProvisions.QuoInt(sdk.NewIntFromUint64(params.BlocksPerYear)) + provisionAmt := m.AnnualProvisions.QuoInt(math.NewIntFromUint64(params.BlocksPerYear)) return sdk.NewCoin(params.MintDenom, provisionAmt.TruncateInt()) } diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index 45ad74e7..afde1b78 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -17,40 +17,40 @@ func TestNextInflation(t *testing.T) { Convey("Given a test cases", t, func() { cases := []struct { name string - inflationRatio sdk.Dec - bondedRatio sdk.Dec + inflationRatio math.LegacyDec + bondedRatio math.LegacyDec totalSupply math.Int - expectedInflation sdk.Dec - expectedAnnualProvisions sdk.Dec + expectedInflation math.LegacyDec + expectedAnnualProvisions math.LegacyDec expectedErr error }{ { name: "inflation ratio is 0", inflationRatio: sdk.NewDec(0), - bondedRatio: sdk.NewDecWithPrec(20, 2), + bondedRatio: math.LegacyNewDecWithPrec(20, 2), totalSupply: math.NewInt(1000), expectedInflation: sdk.NewDec(0), expectedAnnualProvisions: sdk.NewDec(0), }, { name: "inflation ratio is 0.03", - inflationRatio: sdk.NewDecWithPrec(3, 2), - bondedRatio: sdk.NewDecWithPrec(2, 1), + inflationRatio: math.LegacyNewDecWithPrec(3, 2), + bondedRatio: math.LegacyNewDecWithPrec(2, 1), totalSupply: math.NewInt(1000), - expectedInflation: sdk.NewDecWithPrec(15, 2), + expectedInflation: math.LegacyNewDecWithPrec(15, 2), expectedAnnualProvisions: sdk.NewDec(150), }, { name: "bonded ratio is 0", - inflationRatio: sdk.NewDecWithPrec(3, 2), + inflationRatio: math.LegacyNewDecWithPrec(3, 2), bondedRatio: sdk.NewDec(0), totalSupply: math.NewInt(1000), expectedErr: fmt.Errorf("bonded ratio is zero"), }, { name: "negative inflation ratio", - inflationRatio: sdk.NewDecWithPrec(3, 2), - bondedRatio: sdk.NewDecWithPrec(-2, 1), + inflationRatio: math.LegacyNewDecWithPrec(3, 2), + bondedRatio: math.LegacyNewDecWithPrec(-2, 1), totalSupply: math.NewInt(1000), expectedErr: fmt.Errorf("mint parameter Inflation should be positive, is -0.150000000000000000"), }, @@ -83,11 +83,11 @@ func TestNextInflation(t *testing.T) { // previously using math.Int operations: // BenchmarkBlockProvision-4 5000000 220 ns/op // -// using sdk.Dec operations: (current implementation) +// using math.LegacyDec operations: (current implementation) // BenchmarkBlockProvision-4 3000000 429 ns/op. func BenchmarkBlockProvision(b *testing.B) { b.ReportAllocs() - minter := NewMinterWithInitialInflation(sdk.NewDecWithPrec(1, 1)) + minter := NewMinterWithInitialInflation(math.LegacyNewDecWithPrec(1, 1)) params := DefaultParams() s1 := rand.NewSource(100) @@ -106,7 +106,7 @@ func BenchmarkNextInflation(b *testing.B) { b.ReportAllocs() params := DefaultParams() - bondedRatio := sdk.NewDecWithPrec(66, 2) + bondedRatio := math.LegacyNewDecWithPrec(66, 2) totalSupply := sdk.NewInt(100000000000000) // run the NextInflationRate function b.N times diff --git a/x/mint/types/params.go b/x/mint/types/params.go index 933cab09..d775796e 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "cosmossdk.io/math" + "sigs.k8s.io/yaml" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,7 +14,7 @@ import ( // NewParams creates a new Params object. func NewParams( - mintDenom string, inflationCoef sdk.Dec, blocksPerYear uint64, + mintDenom string, inflationCoef math.LegacyDec, blocksPerYear uint64, ) Params { return Params{ MintDenom: mintDenom, @@ -25,7 +27,7 @@ func NewParams( func DefaultParams() Params { return Params{ MintDenom: sdk.DefaultBondDenom, - InflationCoef: sdk.NewDecWithPrec(3, 2), + InflationCoef: math.LegacyNewDecWithPrec(3, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), // assuming 5-second block times } } @@ -62,7 +64,7 @@ func validateMintDenom(i interface{}) error { } func validateInflationCoef(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } @@ -70,7 +72,7 @@ func validateInflationCoef(i interface{}) error { if v.IsNegative() { return fmt.Errorf("inflation coefficient cannot be negative: %s", v) } - if v.GT(sdk.OneDec()) { + if v.GT(math.LegacyOneDec()) { // while there's no theoretical limit to the inflation rate, a coefficient of // 1 or more would lead to hyper-hyperinflation. return fmt.Errorf("inflation coefficient too large: %s", v) diff --git a/x/vesting/testutil/expected_keepers_mocks.go b/x/vesting/testutil/expected_keepers_mocks.go index 1df8f8eb..f27d3b35 100644 --- a/x/vesting/testutil/expected_keepers_mocks.go +++ b/x/vesting/testutil/expected_keepers_mocks.go @@ -1,5 +1,5 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: x/auth/vesting/types/expected_keepers.go +// Source: x/vesting/types/expected_keepers.go // Package testutil is a generated GoMock package. package testutil