From cc533a639fd049fe56f154ba6435b881caa8dafe Mon Sep 17 00:00:00 2001 From: Masih Yeganeh Date: Mon, 25 Nov 2024 19:09:35 +0330 Subject: [PATCH] Use KVStoreService instead of StoreKey (#1028) * Using KVStoreService instead of KVStore in modules * Using KVStoreService instead of KVStore in DEX * Fix keeper_dex * Fix keeper_store * Fix keeper_ob_iterator * Fix linting * Fix remaining changes * Addressing some of the review comments * Address remaining review comments * Fix tests * Fix linting errors * Fix remaining linting errors * Merge branch 'master' into masih/kv-store-service --- app/app.go | 19 ++- app/upgrade/v5/upgrade.go | 7 +- build/go.mod | 2 +- build/go.sum | 4 +- go.work.sum | 1 + x/asset/ft/genesis.go | 23 ++- x/asset/ft/genesis_test.go | 3 +- x/asset/ft/keeper/before_send_test.go | 3 +- x/asset/ft/keeper/grpc_query.go | 33 ++-- x/asset/ft/keeper/invariant_test.go | 2 +- x/asset/ft/keeper/keeper.go | 169 ++++++++++++------ x/asset/ft/keeper/keeper_dex.go | 41 +++-- x/asset/ft/keeper/keeper_dex_test.go | 22 ++- x/asset/ft/keeper/keeper_extension_test.go | 9 +- x/asset/ft/keeper/keeper_test.go | 30 ++-- x/asset/ft/keeper/token_upgrade.go | 38 +++-- x/asset/ft/keeper/token_upgrade_test.go | 2 +- x/asset/ft/keeper/token_upgradev1.go | 28 +-- x/asset/ft/keeper/token_upgradev1_test.go | 9 +- x/asset/ft/migrations/v3/definitions.go | 6 +- x/asset/ft/migrations/v3/definitions_test.go | 2 +- x/asset/nft/genesis.go | 7 +- x/asset/nft/genesis_test.go | 3 +- x/asset/nft/keeper/grpc_query.go | 10 +- x/asset/nft/keeper/keeper.go | 171 +++++++++++-------- x/customparams/keeper/genesis.go | 6 +- x/customparams/keeper/genesis_test.go | 4 +- x/customparams/keeper/grpc_query.go | 10 +- x/customparams/keeper/keeper.go | 30 ++-- x/delay/keeper/keeper.go | 63 ++++--- x/dex/genesis.go | 7 +- x/dex/genesis_test.go | 3 +- x/dex/keeper/grpc_query.go | 10 +- x/dex/keeper/keeper.go | 74 ++++---- x/dex/keeper/keeper_ft_test.go | 4 +- x/dex/keeper/keeper_matching.go | 5 +- x/dex/keeper/keeper_matching_fuzz_test.go | 33 ++-- x/dex/keeper/keeper_matching_test.go | 31 +++- x/dex/keeper/keeper_ob_iterator.go | 9 +- x/dex/keeper/keeper_ob_iterator_fuzz_test.go | 10 +- x/dex/keeper/keeper_ob_iterator_test.go | 3 +- x/dex/keeper/keeper_store.go | 8 +- x/dex/keeper/keeper_test.go | 28 +-- x/dex/types/expected_keepers.go | 4 +- x/feemodel/ante/ante.go | 10 +- x/feemodel/keeper/grpc.go | 10 +- x/feemodel/keeper/keeper.go | 96 ++++++----- x/feemodel/keeper/keeper_test.go | 31 ++-- x/feemodel/module.go | 38 +++-- x/feemodel/module_test.go | 18 +- x/wbank/keeper/keeper.go | 27 ++- x/wbank/types/expected_keepers.go | 2 +- x/wstaking/keeper/msg_server.go | 6 +- x/wstaking/types/expected_keepers.go | 2 +- 54 files changed, 786 insertions(+), 440 deletions(-) diff --git a/app/app.go b/app/app.go index 0957dd992..152e1b2d4 100644 --- a/app/app.go +++ b/app/app.go @@ -412,7 +412,12 @@ func New( ) delayRouter := delaytypes.NewRouter() - app.DelayKeeper = delaykeeper.NewKeeper(appCodec, keys[delaytypes.StoreKey], delayRouter, app.interfaceRegistry) + app.DelayKeeper = delaykeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[delaytypes.StoreKey]), + delayRouter, + app.interfaceRegistry, + ) originalBankKeeper := bankkeeper.NewBaseKeeper( appCodec, @@ -425,7 +430,7 @@ func New( app.WasmPermissionedKeeper = wasmkeeper.NewGovPermissionKeeper(&app.WasmKeeper) app.AssetFTKeeper = assetftkeeper.NewKeeper( appCodec, - keys[assetfttypes.StoreKey], + runtime.NewKVStoreService(keys[assetfttypes.StoreKey]), // for the assetft we use the clear bank keeper without the assets integration to prevent cycling calls. originalBankKeeper, app.DelayKeeper, @@ -549,14 +554,14 @@ func New( ) app.FeeModelKeeper = feemodelkeeper.NewKeeper( - keys[feemodeltypes.StoreKey], - tkeys[feemodeltypes.TransientStoreKey], + runtime.NewKVStoreService(keys[feemodeltypes.StoreKey]), + runtime.NewTransientStoreService(tkeys[feemodeltypes.TransientStoreKey]), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.CustomParamsKeeper = customparamskeeper.NewKeeper( - keys[customparamstypes.StoreKey], + runtime.NewKVStoreService(keys[customparamstypes.StoreKey]), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -579,7 +584,7 @@ func New( ) app.AssetNFTKeeper = assetnftkeeper.NewKeeper( appCodec, - keys[assetnfttypes.StoreKey], + runtime.NewKVStoreService(keys[assetnfttypes.StoreKey]), nftKeeper, // for the assetnft we use the clear bank keeper without the assets integration // because it interacts only with native token. @@ -818,7 +823,7 @@ func New( app.DEXKeeper = dexkeeper.NewKeeper( appCodec, - keys[dextypes.StoreKey], + runtime.NewKVStoreService(keys[dextypes.StoreKey]), app.AccountKeeper, authkeeper.NewQueryServer(app.AccountKeeper), app.AssetFTKeeper, diff --git a/app/upgrade/v5/upgrade.go b/app/upgrade/v5/upgrade.go index 28c9d676c..b6ef0a8cd 100644 --- a/app/upgrade/v5/upgrade.go +++ b/app/upgrade/v5/upgrade.go @@ -59,9 +59,14 @@ func New(mm *module.Manager, configurator module.Configurator, } sdkCtx := sdk.UnwrapSDKContext(ctx) - dexParams := dexKeeper.GetParams(sdkCtx) + //nolint:contextcheck // this is correct context passing. + dexParams, err := dexKeeper.GetParams(sdkCtx) + if err != nil { + return nil, err + } // 10core dexParams.OrderReserve = sdk.NewInt64Coin(chosenNetwork.Denom(), 10_000_000) + //nolint:contextcheck // this is correct context passing. if err = dexKeeper.SetParams(sdkCtx, dexParams); err != nil { return nil, err } diff --git a/build/go.mod b/build/go.mod index 27fb9d377..029bac7c1 100644 --- a/build/go.mod +++ b/build/go.mod @@ -28,7 +28,7 @@ replace ( require ( github.com/CoreumFoundation/coreum-tools v0.4.1-0.20240321120602-0a9c50facc68 github.com/CoreumFoundation/coreum/v5 v5.0.0-20241022051641-b49ec5faa621 - github.com/CoreumFoundation/crust v0.0.0-20241119103533-4a2dd90bbd7c + github.com/CoreumFoundation/crust v0.0.0-20241121173755-aee1cf8f8254 github.com/iancoleman/strcase v0.3.0 github.com/pkg/errors v0.9.1 github.com/samber/lo v1.39.0 diff --git a/build/go.sum b/build/go.sum index dc7b2512d..390ab1486 100644 --- a/build/go.sum +++ b/build/go.sum @@ -231,8 +231,8 @@ github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbi github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/CoreumFoundation/coreum-tools v0.4.1-0.20240321120602-0a9c50facc68 h1:Tb9avuSQW3smVGrUnDh/Y+ML4eK802UsvJNZHsBgOGg= github.com/CoreumFoundation/coreum-tools v0.4.1-0.20240321120602-0a9c50facc68/go.mod h1:VD93vCHkxYaT/RhOesXTFgd/GQDW54tr0BqGi5JU1c0= -github.com/CoreumFoundation/crust v0.0.0-20241119103533-4a2dd90bbd7c h1:WOM8Nu9APDJayYpF7vSO8ZUmossqXo0VQB92q8f7BU4= -github.com/CoreumFoundation/crust v0.0.0-20241119103533-4a2dd90bbd7c/go.mod h1:DC2Jq9oOJgDccdSqwxggqoFJ+EMn1wl8hMXAnnK4DSs= +github.com/CoreumFoundation/crust v0.0.0-20241121173755-aee1cf8f8254 h1:W1gJa+DVmhz1qc3Am0NS326Z1lVaspN47Qrz0RiKDYM= +github.com/CoreumFoundation/crust v0.0.0-20241121173755-aee1cf8f8254/go.mod h1:DC2Jq9oOJgDccdSqwxggqoFJ+EMn1wl8hMXAnnK4DSs= github.com/CosmWasm/wasmd v0.53.0 h1:kdaoAi20bIb4VCsxw9pRaT2g5PpIp82Wqrr9DRVN9ao= github.com/CosmWasm/wasmd v0.53.0/go.mod h1:FJl/aWjdpGof3usAMFQpDe07Rkx77PUzp0cygFMOvtw= github.com/CosmWasm/wasmvm/v2 v2.1.2 h1:GkJ5bAsRlLHfIQVg/FY1VHwLyBwlCjAhDea0B8L+e20= diff --git a/go.work.sum b/go.work.sum index 7c8d9d640..b0865e37d 100644 --- a/go.work.sum +++ b/go.work.sum @@ -727,6 +727,7 @@ github.com/CoreumFoundation/crust v0.0.0-20240829115043-b19e0fee4b1f/go.mod h1:a github.com/CoreumFoundation/crust v0.0.0-20240910084945-51add516ee39/go.mod h1:jl7aUqRGQj20pctlDXGs64EZJa8g1jtxDiQOCkxx9Gs= github.com/CoreumFoundation/crust v0.0.0-20240913053503-d54f466836c9/go.mod h1:E9Gyav98jDtWqIr+gAHu9onNQOFf/SGFsYhwbWtO87M= github.com/CoreumFoundation/crust v0.0.0-20241008134118-a7bc074eff93/go.mod h1:rRKCkQ1UpqmKUCsL6XCFQZCo0OXLRVNWCL9h4gt+pq4= +github.com/CoreumFoundation/crust v0.0.0-20241121173755-aee1cf8f8254/go.mod h1:DC2Jq9oOJgDccdSqwxggqoFJ+EMn1wl8hMXAnnK4DSs= github.com/CosmWasm/wasmvm/v2 v2.0.0/go.mod h1:su9lg5qLr7adV95eOfzjZWkGiky8WNaNIHDr7Fpu7Ck= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= diff --git a/x/asset/ft/genesis.go b/x/asset/ft/genesis.go index ca6e18a48..252f768a7 100644 --- a/x/asset/ft/genesis.go +++ b/x/asset/ft/genesis.go @@ -36,14 +36,18 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) URIHash: token.URIHash, } - k.SetDefinition(ctx, issuer, subunit, definition) + if err := k.SetDefinition(ctx, issuer, subunit, definition); err != nil { + panic(err) + } - err = k.SetSymbol(ctx, token.Symbol, issuer) - if err != nil { + if err := k.SetSymbol(ctx, token.Symbol, issuer); err != nil { panic(err) } + if token.GloballyFrozen { - k.SetGlobalFreeze(ctx, token.Denom, true) + if err := k.SetGlobalFreeze(ctx, token.Denom, true); err != nil { + panic(err) + } } } @@ -89,7 +93,9 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) } for _, settings := range genState.DEXSettings { - k.SetDEXSettings(ctx, settings.Denom, settings.DEXSettings) + if err := k.SetDEXSettings(ctx, settings.Denom, settings.DEXSettings); err != nil { + panic(err) + } } } @@ -137,8 +143,13 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { panic(err) } + params, err := k.GetParams(ctx) + if err != nil { + panic(err) + } + return &types.GenesisState{ - Params: k.GetParams(ctx), + Params: params, Tokens: tokens, FrozenBalances: frozenBalances, WhitelistedBalances: whitelistedBalances, diff --git a/x/asset/ft/genesis_test.go b/x/asset/ft/genesis_test.go index b9653e3e0..6f63cc4c1 100644 --- a/x/asset/ft/genesis_test.go +++ b/x/asset/ft/genesis_test.go @@ -164,7 +164,8 @@ func TestInitAndExportGenesis(t *testing.T) { // params - params := ftKeeper.GetParams(ctx) + params, err := ftKeeper.GetParams(ctx) + requireT.NoError(err) assertT.EqualValues(types.DefaultParams(), params) // token definitions diff --git a/x/asset/ft/keeper/before_send_test.go b/x/asset/ft/keeper/before_send_test.go index 1ea6bd153..9b88d4167 100644 --- a/x/asset/ft/keeper/before_send_test.go +++ b/x/asset/ft/keeper/before_send_test.go @@ -9,6 +9,7 @@ import ( wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" @@ -34,7 +35,7 @@ func TestApplyRate(t *testing.T) { issuer := genAccount() dummyAddress := genAccount() key := storetypes.NewKVStoreKey(types.StoreKey) - assetFTKeeper := assetftkeeper.NewKeeper(nil, key, nil, nil, nil, nil, nil, "") + assetFTKeeper := assetftkeeper.NewKeeper(nil, runtime.NewKVStoreService(key), nil, nil, nil, nil, nil, "") testCases := []struct { name string diff --git a/x/asset/ft/keeper/grpc_query.go b/x/asset/ft/keeper/grpc_query.go index 18bb8fb68..24208461f 100644 --- a/x/asset/ft/keeper/grpc_query.go +++ b/x/asset/ft/keeper/grpc_query.go @@ -17,20 +17,20 @@ var _ types.QueryServer = QueryService{} // //nolint:interfacebloat // breaking down this interface is not beneficial. type QueryKeeper interface { - GetParams(ctx sdk.Context) types.Params + GetParams(ctx sdk.Context) (types.Params, error) GetIssuerTokens( ctx sdk.Context, issuer sdk.AccAddress, pagination *query.PageRequest, ) ([]types.Token, *query.PageResponse, error) GetToken(ctx sdk.Context, denom string) (types.Token, error) - GetTokenUpgradeStatuses(ctx sdk.Context, denom string) types.TokenUpgradeStatuses + GetTokenUpgradeStatuses(ctx sdk.Context, denom string) (types.TokenUpgradeStatuses, error) GetFrozenBalances( ctx sdk.Context, addr sdk.AccAddress, pagination *query.PageRequest, ) (sdk.Coins, *query.PageResponse, error) - GetFrozenBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + GetFrozenBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) (sdk.Coin, error) GetWhitelistedBalances( ctx sdk.Context, addr sdk.AccAddress, @@ -64,9 +64,11 @@ func NewQueryService(keeper QueryKeeper, bankKeeper BankKeeper) QueryService { // Params queries the parameters of x/asset/ft module. func (qs QueryService) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - return &types.QueryParamsResponse{ - Params: qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)), - }, nil + params, err := qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)) + if err != nil { + return nil, err + } + return &types.QueryParamsResponse{Params: params}, nil } // Tokens returns fungible tokens query result. @@ -103,8 +105,10 @@ func (qs QueryService) TokenUpgradeStatuses( ctx context.Context, req *types.QueryTokenUpgradeStatusesRequest, ) (*types.QueryTokenUpgradeStatusesResponse, error) { - tokenUpgradeStatuses := qs.keeper.GetTokenUpgradeStatuses(sdk.UnwrapSDKContext(ctx), req.GetDenom()) - + tokenUpgradeStatuses, err := qs.keeper.GetTokenUpgradeStatuses(sdk.UnwrapSDKContext(ctx), req.GetDenom()) + if err != nil { + return nil, err + } return &types.QueryTokenUpgradeStatusesResponse{ Statuses: tokenUpgradeStatuses, }, nil @@ -128,10 +132,16 @@ func (qs QueryService) Balance( ).Amount sdkCtx := sdk.UnwrapSDKContext(ctx) + + frozenBalance, err := qs.keeper.GetFrozenBalance(sdkCtx, account, denom) + if err != nil { + return nil, err + } + return &types.QueryBalanceResponse{ Balance: qs.bankKeeper.GetBalance(ctx, account, denom).Amount, Whitelisted: qs.keeper.GetWhitelistedBalance(sdkCtx, account, denom).Amount, - Frozen: qs.keeper.GetFrozenBalance(sdkCtx, account, denom).Amount, + Frozen: frozenBalance.Amount, Locked: vestingLocked.Add(dexLocked), LockedInVesting: vestingLocked, LockedInDEX: dexLocked, @@ -170,7 +180,10 @@ func (qs QueryService) FrozenBalance( if err != nil { return nil, sdkerrors.Wrap(cosmoserrors.ErrInvalidAddress, "invalid account address") } - balance := qs.keeper.GetFrozenBalance(ctx, account, req.GetDenom()) + balance, err := qs.keeper.GetFrozenBalance(ctx, account, req.GetDenom()) + if err != nil { + return nil, err + } return &types.QueryFrozenBalanceResponse{ Balance: balance, diff --git a/x/asset/ft/keeper/invariant_test.go b/x/asset/ft/keeper/invariant_test.go index 0b2224515..ee64cedf4 100644 --- a/x/asset/ft/keeper/invariant_test.go +++ b/x/asset/ft/keeper/invariant_test.go @@ -197,7 +197,7 @@ func TestBankMetadataExistInvariant(t *testing.T) { requireT.NoError(err) definition.Denom = "invalid" - ftKeeper.SetDefinition(ctx, settings1.Issuer, settings1.Subunit, definition) + requireT.NoError(ftKeeper.SetDefinition(ctx, settings1.Issuer, settings1.Subunit, definition)) // check that state is broken now _, isBroken = keeper.BankMetadataExistInvariant(ftKeeper)(ctx) diff --git a/x/asset/ft/keeper/keeper.go b/x/asset/ft/keeper/keeper.go index 8090a281c..91dd6d971 100644 --- a/x/asset/ft/keeper/keeper.go +++ b/x/asset/ft/keeper/keeper.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" "cosmossdk.io/log" sdkmath "cosmossdk.io/math" @@ -11,6 +12,7 @@ import ( storetypes "cosmossdk.io/store/types" wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" @@ -36,7 +38,7 @@ type ExtensionInstantiateMsg struct { // Keeper is the asset module keeper. type Keeper struct { cdc codec.BinaryCodec - storeKey storetypes.StoreKey + storeService sdkstore.KVStoreService bankKeeper types.BankKeeper delayKeeper types.DelayKeeper wasmKeeper cwasmtypes.WasmKeeper @@ -48,7 +50,7 @@ type Keeper struct { // NewKeeper creates a new instance of the Keeper. func NewKeeper( cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, bankKeeper types.BankKeeper, delayKeeper types.DelayKeeper, wasmKeeper cwasmtypes.WasmKeeper, @@ -58,7 +60,7 @@ func NewKeeper( ) Keeper { return Keeper{ cdc: cdc, - storeKey: storeKey, + storeService: storeService, bankKeeper: bankKeeper, delayKeeper: delayKeeper, wasmKeeper: wasmKeeper, @@ -69,23 +71,23 @@ func NewKeeper( } // GetParams gets the parameters of the module. -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) +func (k Keeper) GetParams(ctx sdk.Context) (types.Params, error) { + bz, err := k.storeService.OpenKVStore(ctx).Get(types.ParamsKey) + if err != nil { + return types.Params{}, err + } var params types.Params k.cdc.MustUnmarshal(bz, ¶ms) - return params + return params, nil } // SetParams sets the parameters of the module. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { return err } - store.Set(types.ParamsKey, bz) - return nil + return k.storeService.OpenKVStore(ctx).Set(types.ParamsKey, bz) } // UpdateParams is a governance operation that sets parameters of the module. @@ -134,7 +136,8 @@ func (k Keeper) GetIssuerTokens( // IterateAllDefinitions iterates over all token definitions and applies the provided callback. // If true is returned from the callback, iteration is halted. func (k Keeper) IterateAllDefinitions(ctx sdk.Context, cb func(types.Definition) (bool, error)) error { - iterator := prefix.NewStore(ctx.KVStore(k.storeKey), types.TokenKeyPrefix).Iterator(nil, nil) + store := k.storeService.OpenKVStore(ctx) + iterator := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), types.TokenKeyPrefix) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { @@ -158,7 +161,10 @@ func (k Keeper) GetDefinition(ctx sdk.Context, denom string) (types.Definition, if err != nil { return types.Definition{}, err } - bz := ctx.KVStore(k.storeKey).Get(types.CreateTokenKey(issuer, subunit)) + bz, err := k.storeService.OpenKVStore(ctx).Get(types.CreateTokenKey(issuer, subunit)) + if err != nil { + return types.Definition{}, err + } if bz == nil { return types.Definition{}, sdkerrors.Wrapf(types.ErrTokenNotFound, "denom: %s", denom) } @@ -222,7 +228,10 @@ func (k Keeper) IssueVersioned(ctx sdk.Context, settings types.IssueSettings, ve ) } - params := k.GetParams(ctx) + params, err := k.GetParams(ctx) + if err != nil { + return "", err + } if params.IssueFee.IsPositive() { if err := k.burn(ctx, settings.Issuer, sdk.NewCoins(params.IssueFee)); err != nil { return "", err @@ -296,7 +305,9 @@ func (k Keeper) IssueVersioned(ctx sdk.Context, settings types.IssueSettings, ve return "", err } - k.SetDefinition(ctx, settings.Issuer, settings.Subunit, definition) + if err := k.SetDefinition(ctx, settings.Issuer, settings.Subunit, definition); err != nil { + return "", err + } if settings.DEXSettings != nil { if err := types.ValidateDEXSettings(*settings.DEXSettings); err != nil { @@ -307,7 +318,9 @@ func (k Keeper) IssueVersioned(ctx sdk.Context, settings types.IssueSettings, ve return "", err } - k.SetDEXSettings(ctx, denom, *settings.DEXSettings) + if err := k.SetDEXSettings(ctx, denom, *settings.DEXSettings); err != nil { + return "", err + } } if err := ctx.EventManager().EmitTypedEvent(&types.EventIssued{ @@ -341,17 +354,23 @@ func (k Keeper) IssueVersioned(ctx sdk.Context, settings types.IssueSettings, ve // SetSymbol saves the symbol to store. func (k Keeper) SetSymbol(ctx sdk.Context, symbol string, issuer sdk.AccAddress) error { symbol = types.NormalizeSymbolForKey(symbol) - if k.isSymbolDuplicated(ctx, symbol, issuer) { + isSymbolDuplicated, err := k.isSymbolDuplicated(ctx, symbol, issuer) + if err != nil { + return err + } + + if isSymbolDuplicated { return sdkerrors.Wrapf(types.ErrInvalidInput, "duplicate symbol %s", symbol) } - ctx.KVStore(k.storeKey).Set(types.CreateSymbolKey(issuer, symbol), types.StoreTrue) - return nil + return k.storeService.OpenKVStore(ctx).Set(types.CreateSymbolKey(issuer, symbol), types.StoreTrue) } // SetDefinition stores the Definition. -func (k Keeper) SetDefinition(ctx sdk.Context, issuer sdk.AccAddress, subunit string, definition types.Definition) { - ctx.KVStore(k.storeKey).Set(types.CreateTokenKey(issuer, subunit), k.cdc.MustMarshal(&definition)) +func (k Keeper) SetDefinition( + ctx sdk.Context, issuer sdk.AccAddress, subunit string, definition types.Definition, +) error { + return k.storeService.OpenKVStore(ctx).Set(types.CreateTokenKey(issuer, subunit), k.cdc.MustMarshal(&definition)) } // SetDenomMetadata registers denom metadata on the bank keeper. @@ -532,8 +551,7 @@ func (k Keeper) GloballyFreeze(ctx sdk.Context, sender sdk.AccAddress, denom str return err } - k.SetGlobalFreeze(ctx, denom, true) - return nil + return k.SetGlobalFreeze(ctx, denom, true) } // GloballyUnfreeze disables global freeze on a fungible token. This function is idempotent. @@ -547,8 +565,7 @@ func (k Keeper) GloballyUnfreeze(ctx sdk.Context, sender sdk.AccAddress, denom s return err } - k.SetGlobalFreeze(ctx, denom, false) - return nil + return k.SetGlobalFreeze(ctx, denom, false) } // GetAccountsFrozenBalances returns the frozen balance on all the account. @@ -575,11 +592,15 @@ func (k Keeper) GetFrozenBalances( } // GetFrozenBalance returns the frozen balance of a denom and account. -func (k Keeper) GetFrozenBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - if k.isGloballyFrozen(ctx, denom) { - return k.bankKeeper.GetBalance(ctx, addr, denom) +func (k Keeper) GetFrozenBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) (sdk.Coin, error) { + isGloballyFrozen, err := k.isGloballyFrozen(ctx, denom) + if err != nil { + return sdk.Coin{}, err } - return k.frozenAccountBalanceStore(ctx, addr).Balance(denom) + if isGloballyFrozen { + return k.bankKeeper.GetBalance(ctx, addr, denom), nil + } + return k.frozenAccountBalanceStore(ctx, addr).Balance(denom), nil } // SetFrozenBalances sets the frozen balances of a specified account. @@ -593,12 +614,12 @@ func (k Keeper) SetFrozenBalances(ctx sdk.Context, addr sdk.AccAddress, coins sd } // SetGlobalFreeze enables/disables global freeze on a fungible token depending on frozen arg. -func (k Keeper) SetGlobalFreeze(ctx sdk.Context, denom string, frozen bool) { +func (k Keeper) SetGlobalFreeze(ctx sdk.Context, denom string, frozen bool) error { + store := k.storeService.OpenKVStore(ctx) if frozen { - ctx.KVStore(k.storeKey).Set(types.CreateGlobalFreezeKey(denom), types.StoreTrue) - return + return store.Set(types.CreateGlobalFreezeKey(denom), types.StoreTrue) } - ctx.KVStore(k.storeKey).Delete(types.CreateGlobalFreezeKey(denom)) + return store.Delete(types.CreateGlobalFreezeKey(denom)) } // Clawback confiscates specified token from the specified account. @@ -666,15 +687,17 @@ func (k Keeper) GetAccountsWhitelistedBalances( ctx sdk.Context, pagination *query.PageRequest, ) ([]types.Balance, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) return collectBalances( - k.cdc, prefix.NewStore(ctx.KVStore(k.storeKey), types.WhitelistedBalancesKeyPrefix), pagination) + k.cdc, prefix.NewStore(runtime.KVStoreAdapter(store), types.WhitelistedBalancesKeyPrefix), pagination) } // IterateAccountsWhitelistedBalances iterates over all whitelisted balances of all accounts // and applies the provided callback. // If true is returned from the callback, iteration is halted. func (k Keeper) IterateAccountsWhitelistedBalances(ctx sdk.Context, cb func(sdk.AccAddress, sdk.Coin) bool) error { - return newBalanceStore(k.cdc, ctx.KVStore(k.storeKey), types.WhitelistedBalancesKeyPrefix).IterateAllBalances(cb) + store := k.storeService.OpenKVStore(ctx) + return newBalanceStore(k.cdc, runtime.KVStoreAdapter(store), types.WhitelistedBalancesKeyPrefix).IterateAllBalances(cb) } // GetWhitelistedBalances returns the whitelisted balance of an account. @@ -706,25 +729,29 @@ func (k Keeper) GetSpendableBalance( ctx sdk.Context, addr sdk.AccAddress, denom string, -) sdk.Coin { +) (sdk.Coin, error) { balance := k.bankKeeper.GetBalance(ctx, addr, denom) if balance.Amount.IsZero() { - return balance + return balance, nil } notLockedAmt := balance.Amount. Sub(k.GetDEXLockedBalance(ctx, addr, denom).Amount). Sub(k.bankKeeper.LockedCoins(ctx, addr).AmountOf(denom)) if notLockedAmt.IsNegative() { - return sdk.NewCoin(denom, sdkmath.ZeroInt()) + return sdk.NewCoin(denom, sdkmath.ZeroInt()), nil + } + frozenBalance, err := k.GetFrozenBalance(ctx, addr, denom) + if err != nil { + return sdk.Coin{}, err } - notFrozenAmt := balance.Amount.Sub(k.GetFrozenBalance(ctx, addr, denom).Amount) + notFrozenAmt := balance.Amount.Sub(frozenBalance.Amount) if notFrozenAmt.IsNegative() { - return sdk.NewCoin(denom, sdkmath.ZeroInt()) + return sdk.NewCoin(denom, sdkmath.ZeroInt()), nil } spendableAmount := sdkmath.MinInt(notLockedAmt, notFrozenAmt) - return sdk.NewCoin(denom, spendableAmount) + return sdk.NewCoin(denom, spendableAmount), nil } // TransferAdmin changes admin of a fungible token. @@ -746,7 +773,9 @@ func (k Keeper) TransferAdmin(ctx sdk.Context, sender, addr sdk.AccAddress, deno } def.Admin = addr.String() - k.SetDefinition(ctx, issuer, subunit, def) + if err := k.SetDefinition(ctx, issuer, subunit, def); err != nil { + return err + } if err := ctx.EventManager().EmitTypedEvent(&types.EventAdminTransferred{ Denom: denom, @@ -784,7 +813,9 @@ func (k Keeper) ClearAdmin(ctx sdk.Context, sender sdk.AccAddress, denom string) def.SendCommissionRate = sdkmath.LegacyZeroDec() } - k.SetDefinition(ctx, issuer, subunit, def) + if err := k.SetDefinition(ctx, issuer, subunit, def); err != nil { + return err + } if err := ctx.EventManager().EmitTypedEvent(&types.EventAdminCleared{ Denom: denom, @@ -880,8 +911,12 @@ func (k Keeper) validateCoinSpendable( return nil } + isGloballyFrozen, err := k.isGloballyFrozen(ctx, def.Denom) + if err != nil { + return err + } if def.IsFeatureEnabled(types.Feature_freezing) && - k.isGloballyFrozen(ctx, def.Denom) && + isGloballyFrozen && !def.HasAdminPrivileges(addr) { return sdkerrors.Wrapf(types.ErrGloballyFrozen, "%s is globally frozen", def.Denom) } @@ -910,7 +945,11 @@ func (k Keeper) validateCoinSpendable( } if def.IsFeatureEnabled(types.Feature_freezing) && !def.HasAdminPrivileges(addr) { - frozenAmt := k.GetFrozenBalance(ctx, addr, def.Denom).Amount + frozenBalance, err := k.GetFrozenBalance(ctx, addr, def.Denom) + if err != nil { + return err + } + frozenAmt := frozenBalance.Amount notFrozenAmt := balance.Amount.Sub(frozenAmt) if notFrozenAmt.LT(amount) { return sdkerrors.Wrapf(cosmoserrors.ErrInsufficientFunds, "%s%s is not available, available %s%s", @@ -974,17 +1013,21 @@ func (k Keeper) validateCoinReceivable( return nil } -func (k Keeper) isSymbolDuplicated(ctx sdk.Context, symbol string, issuer sdk.AccAddress) bool { +func (k Keeper) isSymbolDuplicated(ctx sdk.Context, symbol string, issuer sdk.AccAddress) (bool, error) { compositeKey := types.CreateSymbolKey(issuer, symbol) - rawBytes := ctx.KVStore(k.storeKey).Get(compositeKey) - return rawBytes != nil + rawBytes, err := k.storeService.OpenKVStore(ctx).Get(compositeKey) + if err != nil { + return false, err + } + return rawBytes != nil, nil } func (k Keeper) getDefinitions( ctx sdk.Context, pagination *query.PageRequest, ) ([]types.Definition, *query.PageResponse, error) { - return k.getDefinitionsFromStore(prefix.NewStore(ctx.KVStore(k.storeKey), types.TokenKeyPrefix), pagination) + store := k.storeService.OpenKVStore(ctx) + return k.getDefinitionsFromStore(prefix.NewStore(runtime.KVStoreAdapter(store), types.TokenKeyPrefix), pagination) } func (k Keeper) getDefinitionOrNil(ctx sdk.Context, denom string) (*types.Definition, error) { @@ -1005,8 +1048,9 @@ func (k Keeper) getIssuerDefinitions( issuer sdk.AccAddress, pagination *query.PageRequest, ) ([]types.Definition, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) return k.getDefinitionsFromStore( - prefix.NewStore(ctx.KVStore(k.storeKey), types.CreateIssuerTokensPrefix(issuer)), + prefix.NewStore(runtime.KVStoreAdapter(store), types.CreateIssuerTokensPrefix(issuer)), pagination, ) } @@ -1039,6 +1083,11 @@ func (k Keeper) getTokenFullInfo(ctx sdk.Context, definition types.Definition) ( return types.Token{}, err } + isGloballyFrozen, err := k.isGloballyFrozen(ctx, definition.Denom) + if err != nil { + return types.Token{}, err + } + return types.Token{ Denom: definition.Denom, Issuer: definition.Issuer, @@ -1049,7 +1098,7 @@ func (k Keeper) getTokenFullInfo(ctx sdk.Context, definition types.Definition) ( Features: definition.Features, BurnRate: definition.BurnRate, SendCommissionRate: definition.SendCommissionRate, - GloballyFrozen: k.isGloballyFrozen(ctx, definition.Denom), + GloballyFrozen: isGloballyFrozen, Version: definition.Version, URI: definition.URI, URIHash: definition.URIHash, @@ -1103,17 +1152,20 @@ func (k Keeper) getTokensByDefinitions(ctx sdk.Context, defs []types.Definition) // frozenBalancesStore get the store for the frozen balances of all accounts. func (k Keeper) frozenBalancesStore(ctx sdk.Context) prefix.Store { - return prefix.NewStore(ctx.KVStore(k.storeKey), types.FrozenBalancesKeyPrefix) + store := k.storeService.OpenKVStore(ctx) + return prefix.NewStore(runtime.KVStoreAdapter(store), types.FrozenBalancesKeyPrefix) } // frozenAccountBalanceStore gets the store for the frozen balances of an account. func (k Keeper) frozenAccountBalanceStore(ctx sdk.Context, addr sdk.AccAddress) balanceStore { - return newBalanceStore(k.cdc, ctx.KVStore(k.storeKey), types.CreateFrozenBalancesKey(addr)) + store := k.storeService.OpenKVStore(ctx) + return newBalanceStore(k.cdc, runtime.KVStoreAdapter(store), types.CreateFrozenBalancesKey(addr)) } // frozenAccountBalanceStore gets the store for the frozen balances of an account. func (k Keeper) frozenAccountsBalanceStore(ctx sdk.Context) balanceStore { - return newBalanceStore(k.cdc, ctx.KVStore(k.storeKey), types.FrozenBalancesKeyPrefix) + store := k.storeService.OpenKVStore(ctx) + return newBalanceStore(k.cdc, runtime.KVStoreAdapter(store), types.FrozenBalancesKeyPrefix) } func (k Keeper) freezingChecks(ctx sdk.Context, sender, addr sdk.AccAddress, coin sdk.Coin) error { @@ -1129,8 +1181,12 @@ func (k Keeper) freezingChecks(ctx sdk.Context, sender, addr sdk.AccAddress, coi return def.CheckFeatureAllowed(sender, types.Feature_freezing) } -func (k Keeper) isGloballyFrozen(ctx sdk.Context, denom string) bool { - return bytes.Equal(ctx.KVStore(k.storeKey).Get(types.CreateGlobalFreezeKey(denom)), types.StoreTrue) +func (k Keeper) isGloballyFrozen(ctx sdk.Context, denom string) (bool, error) { + isGloballyFrozen, err := k.storeService.OpenKVStore(ctx).Get(types.CreateGlobalFreezeKey(denom)) + if err != nil { + return false, err + } + return bytes.Equal(isGloballyFrozen, types.StoreTrue), nil } func (k Keeper) validateClawbackAllowed(ctx sdk.Context, sender, addr sdk.AccAddress, coin sdk.Coin) error { @@ -1153,7 +1209,8 @@ func (k Keeper) validateClawbackAllowed(ctx sdk.Context, sender, addr sdk.AccAdd // whitelistedAccountBalanceStore gets the store for the whitelisted balances of an account. func (k Keeper) whitelistedAccountBalanceStore(ctx sdk.Context, addr sdk.AccAddress) balanceStore { - return newBalanceStore(k.cdc, ctx.KVStore(k.storeKey), types.CreateWhitelistedBalancesKey(addr)) + store := k.storeService.OpenKVStore(ctx) + return newBalanceStore(k.cdc, runtime.KVStoreAdapter(store), types.CreateWhitelistedBalancesKey(addr)) } func (k Keeper) validateWhitelistedBalance(ctx sdk.Context, addr sdk.AccAddress, coin sdk.Coin) error { diff --git a/x/asset/ft/keeper/keeper_dex.go b/x/asset/ft/keeper/keeper_dex.go index 73f6a0cf9..73cc8531b 100644 --- a/x/asset/ft/keeper/keeper_dex.go +++ b/x/asset/ft/keeper/keeper_dex.go @@ -4,6 +4,7 @@ import ( sdkerrors "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" "cosmossdk.io/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" @@ -110,13 +111,16 @@ func (k Keeper) DEXCheckOrderAmounts( } // SetDEXSettings sets the DEX settings of a specified denom. -func (k Keeper) SetDEXSettings(ctx sdk.Context, denom string, settings types.DEXSettings) { - ctx.KVStore(k.storeKey).Set(types.CreateDEXSettingsKey(denom), k.cdc.MustMarshal(&settings)) +func (k Keeper) SetDEXSettings(ctx sdk.Context, denom string, settings types.DEXSettings) error { + return k.storeService.OpenKVStore(ctx).Set(types.CreateDEXSettingsKey(denom), k.cdc.MustMarshal(&settings)) } // GetDEXSettings gets the DEX settings of a specified denom. func (k Keeper) GetDEXSettings(ctx sdk.Context, denom string) (types.DEXSettings, error) { - bz := ctx.KVStore(k.storeKey).Get(types.CreateDEXSettingsKey(denom)) + bz, err := k.storeService.OpenKVStore(ctx).Get(types.CreateDEXSettingsKey(denom)) + if err != nil { + return types.DEXSettings{}, err + } if bz == nil { return types.DEXSettings{}, sdkerrors.Wrapf(types.ErrDEXSettingsNotFound, "denom: %s", denom) } @@ -131,8 +135,9 @@ func (k Keeper) GetDEXSettingsWithDenoms( ctx sdk.Context, pagination *query.PageRequest, ) ([]types.DEXSettingsWithDenom, *query.PageResponse, error) { + moduleStore := k.storeService.OpenKVStore(ctx) dexSettings := make([]types.DEXSettingsWithDenom, 0) - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.DEXSettingsKeyPrefix) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.DEXSettingsKeyPrefix) pageRes, err := query.Paginate(store, pagination, func(key, value []byte) error { denom, err := types.DecodeDenomFromKey(key) if err != nil { @@ -468,7 +473,11 @@ func (k Keeper) dexChecksForDefinition(ctx sdk.Context, acc sdk.AccAddress, def } if def.IsFeatureEnabled(types.Feature_freezing) { - if k.isGloballyFrozen(ctx, def.Denom) && + isGloballyFrozen, err := k.isGloballyFrozen(ctx, def.Denom) + if err != nil { + return err + } + if isGloballyFrozen && // sill allow the admin to do the trade, to follow same logic as we have in the sending !def.HasAdminPrivileges(acc) { return sdkerrors.Wrapf( @@ -503,7 +512,11 @@ func (k Keeper) dexExpectedToSpendChecks( } if def.IsFeatureEnabled(types.Feature_freezing) && !def.HasAdminPrivileges(addr) { - frozenAmt := k.GetFrozenBalance(ctx, addr, coin.Denom).Amount + frozenBalance, err := k.GetFrozenBalance(ctx, addr, coin.Denom) + if err != nil { + return err + } + frozenAmt := frozenBalance.Amount notFrozenTotalAmt := balance.Amount.Sub(frozenAmt) if notFrozenTotalAmt.LT(coin.Amount) { return sdkerrors.Wrapf( @@ -564,7 +577,9 @@ func (k Keeper) updateDEXSettings( } } - k.SetDEXSettings(ctx, denom, newSettings) + if err = k.SetDEXSettings(ctx, denom, newSettings); err != nil { + return err + } if err := ctx.EventManager().EmitTypedEvent(&types.EventDEXSettingsChanged{ PreviousSettings: prevSettings, @@ -601,12 +616,14 @@ func (k Keeper) validateCoinIsNotLockedByDEXAndBank( // dexExpectedToReceiveBalancesStore get the store for the DEX expected to receive balances of all accounts. func (k Keeper) dexExpectedToReceiveBalancesStore(ctx sdk.Context) prefix.Store { - return prefix.NewStore(ctx.KVStore(k.storeKey), types.DEXExpectedToReceiveBalancesKeyPrefix) + store := k.storeService.OpenKVStore(ctx) + return prefix.NewStore(runtime.KVStoreAdapter(store), types.DEXExpectedToReceiveBalancesKeyPrefix) } // dexExpectedToReceiveAccountBalanceStore gets the store for the DEX expected to receive balances of an account. func (k Keeper) dexExpectedToReceiveAccountBalanceStore(ctx sdk.Context, addr sdk.AccAddress) balanceStore { - return newBalanceStore(k.cdc, ctx.KVStore(k.storeKey), types.CreateDEXExpectedToReceiveBalancesKey(addr)) + store := k.storeService.OpenKVStore(ctx) + return newBalanceStore(k.cdc, runtime.KVStoreAdapter(store), types.CreateDEXExpectedToReceiveBalancesKey(addr)) } func (k Keeper) shouldRecordExpectedToReceiveBalance(ctx sdk.Context, denom string) (bool, error) { @@ -624,12 +641,14 @@ func (k Keeper) shouldRecordExpectedToReceiveBalance(ctx sdk.Context, denom stri // dexLockedBalancesStore get the store for the DEX locked balances of all accounts. func (k Keeper) dexLockedBalancesStore(ctx sdk.Context) prefix.Store { - return prefix.NewStore(ctx.KVStore(k.storeKey), types.DEXLockedBalancesKeyPrefix) + store := k.storeService.OpenKVStore(ctx) + return prefix.NewStore(runtime.KVStoreAdapter(store), types.DEXLockedBalancesKeyPrefix) } // dexLockedAccountBalanceStore gets the store for the DEX locked balances of an account. func (k Keeper) dexLockedAccountBalanceStore(ctx sdk.Context, addr sdk.AccAddress) balanceStore { - return newBalanceStore(k.cdc, ctx.KVStore(k.storeKey), types.CreateDEXLockedBalancesKey(addr)) + store := k.storeService.OpenKVStore(ctx) + return newBalanceStore(k.cdc, runtime.KVStoreAdapter(store), types.CreateDEXLockedBalancesKey(addr)) } func (k Keeper) getDEXSettingsOrNil(ctx sdk.Context, denom string) (*types.DEXSettings, error) { diff --git a/x/asset/ft/keeper/keeper_dex_test.go b/x/asset/ft/keeper/keeper_dex_test.go index 950a6353d..5b796782c 100644 --- a/x/asset/ft/keeper/keeper_dex_test.go +++ b/x/asset/ft/keeper/keeper_dex_test.go @@ -218,12 +218,16 @@ func TestKeeper_DEXLocked(t *testing.T) { // decrease locked part requireT.NoError(ftKeeper.DEXDecreaseLocked(ctx, acc, sdk.NewInt64Coin(denom, 400))) requireT.Equal(sdk.NewInt64Coin(denom, 600).String(), ftKeeper.GetDEXLockedBalance(ctx, acc, denom).String()) - requireT.Equal(sdk.NewInt64Coin(denom, 400).String(), ftKeeper.GetSpendableBalance(ctx, acc, denom).String()) + spendableBalance, err := ftKeeper.GetSpendableBalance(ctx, acc, denom) + requireT.NoError(err) + requireT.Equal(sdk.NewInt64Coin(denom, 400).String(), spendableBalance.String()) // freeze locked balance requireT.NoError(ftKeeper.Freeze(ctx, issuer, acc, coinToSend)) // 1050 - total, 600 locked by dex, 50 locked by bank, 1000 frozen - requireT.Equal(sdk.NewInt64Coin(denom, 50).String(), ftKeeper.GetSpendableBalance(ctx, acc, denom).String()) + spendableBalance, err = ftKeeper.GetSpendableBalance(ctx, acc, denom) + requireT.NoError(err) + requireT.Equal(sdk.NewInt64Coin(denom, 50).String(), spendableBalance.String()) // decrease locked 2d part, even when it's frozen we allow it requireT.NoError(ftKeeper.DEXDecreaseLocked(ctx, acc, sdk.NewInt64Coin(denom, 600))) @@ -242,7 +246,9 @@ func TestKeeper_DEXLocked(t *testing.T) { // unfreeze part requireT.NoError(ftKeeper.Unfreeze(ctx, issuer, acc, sdk.NewInt64Coin(denom, 300))) - requireT.Equal(sdk.NewInt64Coin(denom, 700).String(), ftKeeper.GetFrozenBalance(ctx, acc, denom).String()) + frozenBalance, err := ftKeeper.GetFrozenBalance(ctx, acc, denom) + requireT.NoError(err) + requireT.Equal(sdk.NewInt64Coin(denom, 700).String(), frozenBalance.String()) // now 700 frozen, 50 locked by vesting, 1050 balance // try to use more than allowed @@ -271,7 +277,9 @@ func TestKeeper_DEXLocked(t *testing.T) { ), fmt.Sprintf("usage of %s for DEX is blocked because the token is globally frozen", denom), ) - requireT.True(ftKeeper.GetSpendableBalance(ctx, acc, denom).IsZero()) + spendableBalance, err = ftKeeper.GetSpendableBalance(ctx, acc, denom) + requireT.NoError(err) + requireT.True(spendableBalance.IsZero()) // globally unfreeze now and check that we can use the previously locked amount requireT.NoError(ftKeeper.GloballyUnfreeze(ctx, issuer, denom)) requireT.NoError( @@ -638,7 +646,7 @@ func TestKeeper_DEXLimitsWithGlobalFreeze(t *testing.T) { ) // globally freeze - ftKeeper.SetGlobalFreeze(ctx, ft1CoinToSend.Denom, true) + requireT.NoError(ftKeeper.SetGlobalFreeze(ctx, ft1CoinToSend.Denom, true)) requireT.ErrorContains( ftKeeper.DEXCheckOrderAmounts( simapp.CopyContextWithMultiStore(ctx), @@ -649,8 +657,8 @@ func TestKeeper_DEXLimitsWithGlobalFreeze(t *testing.T) { fmt.Sprintf("usage of %s for DEX is blocked because the token is globally frozen", ft1CoinToSend.Denom), ) - ftKeeper.SetGlobalFreeze(ctx, ft1CoinToSend.Denom, false) - ftKeeper.SetGlobalFreeze(ctx, ft2CoinToSend.Denom, true) + requireT.NoError(ftKeeper.SetGlobalFreeze(ctx, ft1CoinToSend.Denom, false)) + requireT.NoError(ftKeeper.SetGlobalFreeze(ctx, ft2CoinToSend.Denom, true)) requireT.ErrorContains( ftKeeper.DEXCheckOrderAmounts( simapp.CopyContextWithMultiStore(ctx), diff --git a/x/asset/ft/keeper/keeper_extension_test.go b/x/asset/ft/keeper/keeper_extension_test.go index 0373695cf..d8194f708 100644 --- a/x/asset/ft/keeper/keeper_extension_test.go +++ b/x/asset/ft/keeper/keeper_extension_test.go @@ -399,7 +399,8 @@ func TestKeeper_Extension_FreezeUnfreeze(t *testing.T) { // freeze, query frozen err = ftKeeper.Freeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(120))) requireT.NoError(err) - frozenBalance := ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err := ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(120)), frozenBalance) // try to send more than available coinsToSend := sdk.NewCoins(sdk.NewCoin(denom, sdkmath.NewInt(80))) @@ -420,7 +421,8 @@ func TestKeeper_Extension_FreezeUnfreeze(t *testing.T) { bankBalance := bankKeeper.GetBalance(ctx, recipient, denom) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(100)).String(), bankBalance.String()) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(120)).String(), frozenBalance.String()) // send trigger amount to transfer despite freezing @@ -431,7 +433,8 @@ func TestKeeper_Extension_FreezeUnfreeze(t *testing.T) { bankBalance = bankKeeper.GetBalance(ctx, recipient, denom) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(21)).String(), bankBalance.String()) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(120)).String(), frozenBalance.String()) } diff --git a/x/asset/ft/keeper/keeper_test.go b/x/asset/ft/keeper/keeper_test.go index 931d57855..42beff72a 100644 --- a/x/asset/ft/keeper/keeper_test.go +++ b/x/asset/ft/keeper/keeper_test.go @@ -1125,25 +1125,29 @@ func TestKeeper_FreezeUnfreeze(t *testing.T) { // try to freeze more than balance err = ftKeeper.Freeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(110))) requireT.NoError(err) - frozenBalance := ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err := ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) assertT.EqualValues(sdk.NewCoin(denom, sdkmath.NewInt(110)), frozenBalance) // try to unfreeze more than frozen balance err = ftKeeper.Unfreeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(130))) requireT.ErrorIs(err, cosmoserrors.ErrInsufficientFunds) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) assertT.EqualValues(sdk.NewCoin(denom, sdkmath.NewInt(110)), frozenBalance) // set frozen balance back to zero err = ftKeeper.Unfreeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(110))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) assertT.EqualValues(sdk.NewCoin(denom, sdkmath.NewInt(0)).String(), frozenBalance.String()) // freeze, query frozen err = ftKeeper.Freeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(40))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(40)).String(), frozenBalance.String()) // test query all frozen @@ -1157,7 +1161,8 @@ func TestKeeper_FreezeUnfreeze(t *testing.T) { // increase frozen and query err = ftKeeper.Freeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(40))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(80)), frozenBalance) // try to send more than available @@ -1198,13 +1203,15 @@ func TestKeeper_FreezeUnfreeze(t *testing.T) { // set absolute frozen amount err = ftKeeper.SetFrozen(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(100))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(100)), frozenBalance) // unfreeze, query frozen, and try to send err = ftKeeper.Unfreeze(ctx, issuer, recipient, sdk.NewCoin(denom, sdkmath.NewInt(100))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(0)), frozenBalance) coinsToSend = sdk.NewCoins(sdk.NewCoin(denom, sdkmath.NewInt(40))) // send @@ -2184,7 +2191,8 @@ func TestKeeper_TransferAdmin_FreezeUnfreeze(t *testing.T) { // freeze, query frozen err = ftKeeper.Freeze(ctx, admin, recipient, sdk.NewCoin(denom, sdkmath.NewInt(40))) requireT.NoError(err) - frozenBalance := ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err := ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(40)).String(), frozenBalance.String()) // test query all frozen @@ -2202,13 +2210,15 @@ func TestKeeper_TransferAdmin_FreezeUnfreeze(t *testing.T) { // set absolute frozen amount err = ftKeeper.SetFrozen(ctx, admin, recipient, sdk.NewCoin(denom, sdkmath.NewInt(100))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(100)), frozenBalance) // unfreeze, query frozen err = ftKeeper.Unfreeze(ctx, admin, recipient, sdk.NewCoin(denom, sdkmath.NewInt(100))) requireT.NoError(err) - frozenBalance = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + frozenBalance, err = ftKeeper.GetFrozenBalance(ctx, recipient, denom) + requireT.NoError(err) requireT.Equal(sdk.NewCoin(denom, sdkmath.NewInt(0)), frozenBalance) } diff --git a/x/asset/ft/keeper/token_upgrade.go b/x/asset/ft/keeper/token_upgrade.go index 231b20c3d..c33fa4f2e 100644 --- a/x/asset/ft/keeper/token_upgrade.go +++ b/x/asset/ft/keeper/token_upgrade.go @@ -5,6 +5,7 @@ import ( sdkerrors "cosmossdk.io/errors" "cosmossdk.io/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" @@ -24,7 +25,8 @@ func (k Keeper) ImportPendingTokenUpgrades(ctx sdk.Context, versions []types.Pen // ExportPendingTokenUpgrades exports pending version upgrades. func (k Keeper) ExportPendingTokenUpgrades(ctx sdk.Context) ([]types.PendingTokenUpgrade, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.PendingTokenUpgradeKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.PendingTokenUpgradeKeyPrefix) versions := []types.PendingTokenUpgrade{} _, err := query.Paginate(store, &query.PageRequest{Limit: query.PaginationMaxLimit}, func(key, value []byte) error { version, n := binary.Uvarint(value) @@ -47,34 +49,39 @@ func (k Keeper) ExportPendingTokenUpgrades(ctx sdk.Context) ([]types.PendingToke // SetPendingVersion sets pending version for token upgrade. func (k Keeper) SetPendingVersion(ctx sdk.Context, denom string, version uint32) error { - store := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) key := types.CreatePendingTokenUpgradeKey(denom) - if store.Has(key) { + val, err := store.Has(key) + if err != nil { + return err + } + if val { return sdkerrors.Wrapf(cosmoserrors.ErrUnauthorized, "token upgrade is already pending for denom %q", denom) } value := make([]byte, binary.MaxVarintLen32) n := binary.PutUvarint(value, uint64(version)) - store.Set(key, value[:n]) - - return nil + return store.Set(key, value[:n]) } // ClearPendingVersion clears pending version marker. -func (k Keeper) ClearPendingVersion(ctx sdk.Context, denom string) { - ctx.KVStore(k.storeKey).Delete(types.CreatePendingTokenUpgradeKey(denom)) +func (k Keeper) ClearPendingVersion(ctx sdk.Context, denom string) error { + return k.storeService.OpenKVStore(ctx).Delete(types.CreatePendingTokenUpgradeKey(denom)) } // GetTokenUpgradeStatuses returns the token upgrade statuses of a specified denom. -func (k Keeper) GetTokenUpgradeStatuses(ctx sdk.Context, denom string) types.TokenUpgradeStatuses { - bz := ctx.KVStore(k.storeKey).Get(types.CreateTokenUpgradeStatusesKey(denom)) +func (k Keeper) GetTokenUpgradeStatuses(ctx sdk.Context, denom string) (types.TokenUpgradeStatuses, error) { + bz, err := k.storeService.OpenKVStore(ctx).Get(types.CreateTokenUpgradeStatusesKey(denom)) + if err != nil { + return types.TokenUpgradeStatuses{}, err + } if bz == nil { - return types.TokenUpgradeStatuses{} + return types.TokenUpgradeStatuses{}, nil } var tokenUpgradeStatuses types.TokenUpgradeStatuses k.cdc.MustUnmarshal(bz, &tokenUpgradeStatuses) - return tokenUpgradeStatuses + return tokenUpgradeStatuses, nil } // SetTokenUpgradeStatuses sets the token upgrade statuses of a specified denom. @@ -82,6 +89,9 @@ func (k Keeper) SetTokenUpgradeStatuses( ctx sdk.Context, denom string, tokenUpgradeStatuses types.TokenUpgradeStatuses, -) { - ctx.KVStore(k.storeKey).Set(types.CreateTokenUpgradeStatusesKey(denom), k.cdc.MustMarshal(&tokenUpgradeStatuses)) +) error { + return k.storeService.OpenKVStore(ctx).Set( + types.CreateTokenUpgradeStatusesKey(denom), + k.cdc.MustMarshal(&tokenUpgradeStatuses), + ) } diff --git a/x/asset/ft/keeper/token_upgrade_test.go b/x/asset/ft/keeper/token_upgrade_test.go index c8d536cbf..317a50d4b 100644 --- a/x/asset/ft/keeper/token_upgrade_test.go +++ b/x/asset/ft/keeper/token_upgrade_test.go @@ -30,7 +30,7 @@ func TestOneTokenUpgradeAtATimeIsAllowed(t *testing.T) { requireT.NoError(ftKeeper.SetPendingVersion(ctx, "denom2", 1)) // upgrade happened - ftKeeper.ClearPendingVersion(ctx, "denom") + requireT.NoError(ftKeeper.ClearPendingVersion(ctx, "denom")) // but for second denom it should still fail requireT.Error(ftKeeper.SetPendingVersion(ctx, "denom2", 2)) diff --git a/x/asset/ft/keeper/token_upgradev1.go b/x/asset/ft/keeper/token_upgradev1.go index ae49f3580..d3297664d 100644 --- a/x/asset/ft/keeper/token_upgradev1.go +++ b/x/asset/ft/keeper/token_upgradev1.go @@ -14,7 +14,10 @@ const tokenUpgradeV1Version = 1 // AddDelayedTokenUpgradeV1 stores request for upgrading token to V1. func (k Keeper) AddDelayedTokenUpgradeV1(ctx sdk.Context, sender sdk.AccAddress, denom string, ibcEnabled bool) error { - params := k.GetParams(ctx) + params, err := k.GetParams(ctx) + if err != nil { + return err + } if ctx.BlockTime().After(params.TokenUpgradeDecisionTimeout) { return sdkerrors.Wrapf(cosmoserrors.ErrUnauthorized, "it is no longer possible to upgrade the token") } @@ -53,14 +56,19 @@ func (k Keeper) AddDelayedTokenUpgradeV1(ctx sdk.Context, sender sdk.AccAddress, if err != nil { return err } - k.SetDefinition(ctx, issuer, subunit, def) - k.ClearPendingVersion(ctx, denom) + if err := k.SetDefinition(ctx, issuer, subunit, def); err != nil { + return err + } + if err := k.ClearPendingVersion(ctx, denom); err != nil { + return err + } tokenUpgradeStatuses.V1.EndTime = tokenUpgradeStatuses.V1.StartTime - k.SetTokenUpgradeStatuses(ctx, denom, tokenUpgradeStatuses) - return nil + return k.SetTokenUpgradeStatuses(ctx, denom, tokenUpgradeStatuses) } - k.SetTokenUpgradeStatuses(ctx, denom, tokenUpgradeStatuses) + if err := k.SetTokenUpgradeStatuses(ctx, denom, tokenUpgradeStatuses); err != nil { + return err + } data := &types.DelayedTokenUpgradeV1{ Denom: denom, @@ -88,10 +96,10 @@ func (k Keeper) UpgradeTokenToV1(ctx sdk.Context, data *types.DelayedTokenUpgrad def.Features = append(def.Features, types.Feature_ibc) def.Version = tokenUpgradeV1Version - k.SetDefinition(ctx, issuer, subunit, def) - k.ClearPendingVersion(ctx, data.Denom) - - return nil + if err := k.SetDefinition(ctx, issuer, subunit, def); err != nil { + return err + } + return k.ClearPendingVersion(ctx, data.Denom) } func tokenUpgradeID(version int, denom string) string { diff --git a/x/asset/ft/keeper/token_upgradev1_test.go b/x/asset/ft/keeper/token_upgradev1_test.go index e737ffe7d..ae16166f0 100644 --- a/x/asset/ft/keeper/token_upgradev1_test.go +++ b/x/asset/ft/keeper/token_upgradev1_test.go @@ -27,7 +27,8 @@ func TestTokenUpgradeV1(t *testing.T) { ftKeeper := testApp.AssetFTKeeper delayKeeper := testApp.DelayKeeper - params := ftKeeper.GetParams(ctxSDK) + params, err := ftKeeper.GetParams(ctxSDK) + requireT.NoError(err) params.TokenUpgradeDecisionTimeout = time.Date(2023, 2, 13, 1, 2, 3, 0, time.UTC) requireT.NoError(ftKeeper.SetParams(ctxSDK, params)) @@ -76,7 +77,8 @@ func TestTokenUpgradeV1(t *testing.T) { requireT.Empty(token1.Features) requireT.EqualValues(1, token1.Version) - tokenUpgradeStatuses := ftKeeper.GetTokenUpgradeStatuses(ctxSDK, denom1) + tokenUpgradeStatuses, err := ftKeeper.GetTokenUpgradeStatuses(ctxSDK, denom1) + requireT.NoError(err) requireT.Equal(&types.TokenUpgradeV1Status{ IbcEnabled: false, StartTime: ctxSDK.BlockTime(), @@ -103,7 +105,8 @@ func TestTokenUpgradeV1(t *testing.T) { requireT.Empty(token2.Features) requireT.EqualValues(0, token2.Version) - tokenUpgradeStatuses2 := ftKeeper.GetTokenUpgradeStatuses(ctxSDK, denom2) + tokenUpgradeStatuses2, err := ftKeeper.GetTokenUpgradeStatuses(ctxSDK, denom2) + requireT.NoError(err) requireT.Equal(&types.TokenUpgradeV1Status{ IbcEnabled: true, StartTime: ctxSDK.BlockTime(), diff --git a/x/asset/ft/migrations/v3/definitions.go b/x/asset/ft/migrations/v3/definitions.go index 2e17fac32..4f492d81a 100644 --- a/x/asset/ft/migrations/v3/definitions.go +++ b/x/asset/ft/migrations/v3/definitions.go @@ -10,7 +10,7 @@ import ( // FTKeeper represents ft keeper. type FTKeeper interface { IterateAllDefinitions(ctx sdk.Context, cb func(types.Definition) (bool, error)) error - SetDefinition(ctx sdk.Context, issuer sdk.AccAddress, subunit string, definition types.Definition) + SetDefinition(ctx sdk.Context, issuer sdk.AccAddress, subunit string, definition types.Definition) error } // ParamsKeeper specifies methods of params keeper required by the migration. @@ -28,7 +28,9 @@ func MigrateDefinitions(ctx sdk.Context, keeper FTKeeper) error { } def.Admin = def.Issuer - keeper.SetDefinition(ctx, issuer, subunit, def) + if err := keeper.SetDefinition(ctx, issuer, subunit, def); err != nil { + return false, err + } return false, nil }) } diff --git a/x/asset/ft/migrations/v3/definitions_test.go b/x/asset/ft/migrations/v3/definitions_test.go index 4c19c6fab..ddfad4b00 100644 --- a/x/asset/ft/migrations/v3/definitions_test.go +++ b/x/asset/ft/migrations/v3/definitions_test.go @@ -41,7 +41,7 @@ func TestMigrateDefinitions(t *testing.T) { requireT.NoError(err) def.Admin = "" - keeper.SetDefinition(ctx, issuer, settings.Subunit, def) + requireT.NoError(keeper.SetDefinition(ctx, issuer, settings.Subunit, def)) requireT.NoError(v3.MigrateDefinitions(ctx, keeper)) diff --git a/x/asset/nft/genesis.go b/x/asset/nft/genesis.go index 29fc6191b..7fa0acfb6 100644 --- a/x/asset/nft/genesis.go +++ b/x/asset/nft/genesis.go @@ -123,9 +123,14 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { panic(err) } + params, err := k.GetParams(ctx) + if err != nil { + panic(err) + } + return &types.GenesisState{ ClassDefinitions: classDefinitions, - Params: k.GetParams(ctx), + Params: params, FrozenNFTs: frozen, WhitelistedNFTAccounts: whitelisted, ClassWhitelistedAccounts: classWhitelisted, diff --git a/x/asset/nft/genesis_test.go b/x/asset/nft/genesis_test.go index 7b4d4107a..a4cdad08a 100644 --- a/x/asset/nft/genesis_test.go +++ b/x/asset/nft/genesis_test.go @@ -171,7 +171,8 @@ func TestInitAndExportGenesis(t *testing.T) { } // params - params := nftKeeper.GetParams(ctx) + params, err := nftKeeper.GetParams(ctx) + requireT.NoError(err) assertT.EqualValues(types.DefaultParams(), params) // check that export is equal import diff --git a/x/asset/nft/keeper/grpc_query.go b/x/asset/nft/keeper/grpc_query.go index 1f8cbb8e9..eb1d43f89 100644 --- a/x/asset/nft/keeper/grpc_query.go +++ b/x/asset/nft/keeper/grpc_query.go @@ -16,7 +16,7 @@ var _ types.QueryServer = QueryService{} // //nolint:interfacebloat // breaking down this interface is not beneficial. type QueryKeeper interface { - GetParams(ctx sdk.Context) types.Params + GetParams(ctx sdk.Context) (types.Params, error) GetClass(ctx sdk.Context, classID string) (types.Class, error) GetClasses( ctx sdk.Context, @@ -55,9 +55,11 @@ func NewQueryService(keeper QueryKeeper) QueryService { // Params queries the parameters of x/asset/nft module. func (qs QueryService) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - return &types.QueryParamsResponse{ - Params: qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)), - }, nil + params, err := qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)) + if err != nil { + return nil, err + } + return &types.QueryParamsResponse{Params: params}, nil } // Class returns the asset NFT class. diff --git a/x/asset/nft/keeper/keeper.go b/x/asset/nft/keeper/keeper.go index 638dcee9d..c3ef52f64 100644 --- a/x/asset/nft/keeper/keeper.go +++ b/x/asset/nft/keeper/keeper.go @@ -3,12 +3,14 @@ package keeper import ( "bytes" + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/nft" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" @@ -16,54 +18,54 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/pkg/errors" - "github.com/CoreumFoundation/coreum/v5/pkg/store" + pkgstore "github.com/CoreumFoundation/coreum/v5/pkg/store" "github.com/CoreumFoundation/coreum/v5/x/asset/nft/types" ) // Keeper is the asset module non-fungible token nftKeeper. type Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - nftKeeper types.NFTKeeper - bankKeeper types.BankKeeper - authority string + cdc codec.BinaryCodec + storeService sdkstore.KVStoreService + nftKeeper types.NFTKeeper + bankKeeper types.BankKeeper + authority string } // NewKeeper creates a new instance of the Keeper. func NewKeeper( cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, nftKeeper types.NFTKeeper, bankKeeper types.BankKeeper, authority string, ) Keeper { return Keeper{ - cdc: cdc, - storeKey: storeKey, - nftKeeper: nftKeeper, - bankKeeper: bankKeeper, - authority: authority, + cdc: cdc, + storeService: storeService, + nftKeeper: nftKeeper, + bankKeeper: bankKeeper, + authority: authority, } } // GetParams gets the parameters of the module. -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) +func (k Keeper) GetParams(ctx sdk.Context) (types.Params, error) { + bz, err := k.storeService.OpenKVStore(ctx).Get(types.ParamsKey) + if err != nil { + return types.Params{}, err + } var params types.Params k.cdc.MustUnmarshal(bz, ¶ms) - return params + return params, nil } // SetParams sets the parameters of the module. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { return err } - store.Set(types.ParamsKey, bz) - return nil + return k.storeService.OpenKVStore(ctx).Set(types.ParamsKey, bz) } // UpdateParams is a governance operation that sets parameters of the module. @@ -200,7 +202,10 @@ func (k Keeper) GetClassDefinition(ctx sdk.Context, classID string) (types.Class return types.ClassDefinition{}, err } - bz := ctx.KVStore(k.storeKey).Get(classKey) + bz, err := k.storeService.OpenKVStore(ctx).Get(classKey) + if err != nil { + return types.ClassDefinition{}, err + } if bz == nil { return types.ClassDefinition{}, sdkerrors.Wrapf(types.ErrClassNotFound, "classID: %s", classID) } @@ -213,7 +218,8 @@ func (k Keeper) GetClassDefinition(ctx sdk.Context, classID string) (types.Class // IterateAllClassDefinitions iterates over all class definitions and applies the provided callback. // If true is returned from the callback, iteration is halted. func (k Keeper) IterateAllClassDefinitions(ctx sdk.Context, cb func(types.ClassDefinition) (bool, error)) error { - iterator := prefix.NewStore(ctx.KVStore(k.storeKey), types.NFTClassKeyPrefix).Iterator(nil, nil) + store := k.storeService.OpenKVStore(ctx) + iterator := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), types.NFTClassKeyPrefix) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { @@ -235,6 +241,7 @@ func (k Keeper) IterateAllClassDefinitions(ctx sdk.Context, cb func(types.ClassD func (k Keeper) GetClassDefinitions( ctx sdk.Context, issuer *sdk.AccAddress, pagination *query.PageRequest, ) ([]types.ClassDefinition, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) fetchingKey := types.NFTClassKeyPrefix if issuer != nil { var err error @@ -245,7 +252,7 @@ func (k Keeper) GetClassDefinitions( } definitionsPointers, pageRes, err := query.GenericFilteredPaginate( k.cdc, - prefix.NewStore(ctx.KVStore(k.storeKey), fetchingKey), + prefix.NewStore(runtime.KVStoreAdapter(store), fetchingKey), pagination, // builder func(key []byte, definition *types.ClassDefinition) (*types.ClassDefinition, error) { @@ -275,9 +282,7 @@ func (k Keeper) SetClassDefinition(ctx sdk.Context, definition types.ClassDefini return err } - ctx.KVStore(k.storeKey).Set(classKey, k.cdc.MustMarshal(&definition)) - - return nil + return k.storeService.OpenKVStore(ctx).Set(classKey, k.cdc.MustMarshal(&definition)) } // Mint mints new non-fungible token. @@ -333,7 +338,10 @@ func (k Keeper) Mint(ctx sdk.Context, settings types.MintSettings) error { return sdkerrors.Wrapf(types.ErrInvalidInput, "ID %q has been burnt for the class", settings.ID) } - params := k.GetParams(ctx) + params, err := k.GetParams(ctx) + if err != nil { + return err + } if params.MintFee.IsPositive() { coinsToBurn := sdk.NewCoins(params.MintFee) if err := k.bankKeeper.SendCoinsFromAccountToModule( @@ -495,20 +503,25 @@ func (k Keeper) IsBurnt(ctx sdk.Context, classID, nftID string) (bool, error) { return false, err } - return bytes.Equal(ctx.KVStore(k.storeKey).Get(key), types.StoreTrue), nil + isBurnt, err := k.storeService.OpenKVStore(ctx).Get(key) + if err != nil { + return false, err + } + return bytes.Equal(isBurnt, types.StoreTrue), nil } // GetBurntByClass return the list of burnt NFTs in class. func (k Keeper) GetBurntByClass( ctx sdk.Context, classID string, q *query.PageRequest, ) (*query.PageResponse, []string, error) { + store := k.storeService.OpenKVStore(ctx) key, err := types.CreateClassBurningKey(classID) if err != nil { return nil, nil, err } nfts := []string{} - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), key), q, + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), key), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -549,8 +562,7 @@ func (k Keeper) SetBurnt(ctx sdk.Context, classID, nftID string) error { if err != nil { return err } - ctx.KVStore(k.storeKey).Set(key, types.StoreTrue) - return nil + return k.storeService.OpenKVStore(ctx).Set(key, types.StoreTrue) } // GetBurntNFTs return paginated burnt NFTs. @@ -559,9 +571,10 @@ func (k Keeper) SetBurnt(ctx sdk.Context, classID, nftID string) error { func (k Keeper) GetBurntNFTs( ctx sdk.Context, q *query.PageRequest, ) ([]types.BurntNFT, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) burnt := make([]types.BurntNFT, 0) classIDToBurntNFTIdx := make(map[string]int) - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), types.NFTBurningKeyPrefix), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), types.NFTBurningKeyPrefix), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -613,13 +626,11 @@ func (k Keeper) SetFrozen(ctx sdk.Context, classID, nftID string, frozen bool) e if err != nil { return err } - s := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) if frozen { - s.Set(key, types.StoreTrue) - } else { - s.Delete(key) + return store.Set(key, types.StoreTrue) } - return nil + return store.Delete(key) } // ClassFreeze freezes a non-fungible token. @@ -639,17 +650,16 @@ func (k Keeper) SetClassFrozen(ctx sdk.Context, classID string, account sdk.AccA if err != nil { return err } - s := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) if frozen { - s.Set(key, types.StoreTrue) - } else { - s.Delete(key) + return store.Set(key, types.StoreTrue) } - return nil + return store.Delete(key) } // IsFrozen return whether a non-fungible token is frozen or not. func (k Keeper) IsFrozen(ctx sdk.Context, classID, nftID string) (bool, error) { + store := k.storeService.OpenKVStore(ctx) classDefinition, err := k.GetClassDefinition(ctx, classID) if err != nil { return false, err @@ -668,7 +678,11 @@ func (k Keeper) IsFrozen(ctx sdk.Context, classID, nftID string) (bool, error) { return false, err } - if bytes.Equal(ctx.KVStore(k.storeKey).Get(key), types.StoreTrue) { + val, err := store.Get(key) + if err != nil { + return false, err + } + if bytes.Equal(val, types.StoreTrue) { return true, nil } @@ -678,7 +692,11 @@ func (k Keeper) IsFrozen(ctx sdk.Context, classID, nftID string) (bool, error) { return false, err } - return bytes.Equal(ctx.KVStore(k.storeKey).Get(key), types.StoreTrue), nil + val, err = store.Get(key) + if err != nil { + return false, err + } + return bytes.Equal(val, types.StoreTrue), nil } // IsClassFrozen return whether an account is frozen for an NFT class . @@ -701,16 +719,21 @@ func (k Keeper) IsClassFrozen(ctx sdk.Context, classID string, account sdk.AccAd return false, err } - return bytes.Equal(ctx.KVStore(k.storeKey).Get(key), types.StoreTrue), nil + val, err := k.storeService.OpenKVStore(ctx).Get(key) + if err != nil { + return false, err + } + return bytes.Equal(val, types.StoreTrue), nil } // GetFrozenNFTs return paginated frozen NFTs. // //nolint:dupl func (k Keeper) GetFrozenNFTs(ctx sdk.Context, q *query.PageRequest) ([]types.FrozenNFT, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) frozen := make([]types.FrozenNFT, 0) classIDToFrozenNFTIdx := make(map[string]int) - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), types.NFTFreezingKeyPrefix), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), types.NFTFreezingKeyPrefix), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -751,9 +774,10 @@ func (k Keeper) GetFrozenNFTs(ctx sdk.Context, q *query.PageRequest) ([]types.Fr func (k Keeper) GetAllClassFrozenAccounts( ctx sdk.Context, q *query.PageRequest, ) ([]types.ClassFrozenAccounts, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) frozen := make([]types.ClassFrozenAccounts, 0) classIDToFrozenIdx := make(map[string]int) - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), types.NFTClassFreezingKeyPrefix), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), types.NFTClassFreezingKeyPrefix), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -795,13 +819,14 @@ func (k Keeper) GetAllClassFrozenAccounts( func (k Keeper) GetClassFrozenAccounts( ctx sdk.Context, classID string, q *query.PageRequest, ) ([]string, *query.PageResponse, error) { - compositeKey, err := store.JoinKeysWithLength([]byte(classID)) + store := k.storeService.OpenKVStore(ctx) + compositeKey, err := pkgstore.JoinKeysWithLength([]byte(classID)) if err != nil { return nil, nil, sdkerrors.Wrapf(types.ErrInvalidKey, "failed to create a composite key for nft, err: %s", err) } - key := store.JoinKeys(types.NFTClassFreezingKeyPrefix, compositeKey) + key := pkgstore.JoinKeys(types.NFTClassFreezingKeyPrefix, compositeKey) accounts := []string{} - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), key), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), key), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -879,7 +904,11 @@ func (k Keeper) isClassWhitelisted(ctx sdk.Context, classID string, account sdk. return false, err } - return bytes.Equal(ctx.KVStore(k.storeKey).Get(classKey), types.StoreTrue), nil + val, err := k.storeService.OpenKVStore(ctx).Get(classKey) + if err != nil { + return false, err + } + return bytes.Equal(val, types.StoreTrue), nil } func (k Keeper) isTokenWhitelisted(ctx sdk.Context, classID, nftID string, account sdk.AccAddress) (bool, error) { @@ -892,13 +921,18 @@ func (k Keeper) isTokenWhitelisted(ctx sdk.Context, classID, nftID string, accou return false, err } - return bytes.Equal(ctx.KVStore(k.storeKey).Get(key), types.StoreTrue), nil + val, err := k.storeService.OpenKVStore(ctx).Get(key) + if err != nil { + return false, err + } + return bytes.Equal(val, types.StoreTrue), nil } // GetWhitelistedAccountsForNFT returns all whitelisted accounts for all NFTs. func (k Keeper) GetWhitelistedAccountsForNFT( ctx sdk.Context, classID, nftID string, q *query.PageRequest, ) ([]string, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) if !k.nftKeeper.HasNFT(ctx, classID, nftID) { return nil, nil, sdkerrors.Wrapf( types.ErrNFTNotFound, @@ -908,7 +942,7 @@ func (k Keeper) GetWhitelistedAccountsForNFT( ) } - compositeKey, err := store.JoinKeysWithLength([]byte(classID), []byte(nftID)) + compositeKey, err := pkgstore.JoinKeysWithLength([]byte(classID), []byte(nftID)) if err != nil { return nil, nil, sdkerrors.Wrapf( types.ErrInvalidKey, @@ -916,9 +950,9 @@ func (k Keeper) GetWhitelistedAccountsForNFT( err, ) } - key := store.JoinKeys(types.NFTWhitelistingKeyPrefix, compositeKey) + key := pkgstore.JoinKeys(types.NFTWhitelistingKeyPrefix, compositeKey) accounts := []string{} - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), key), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), key), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -944,13 +978,14 @@ func (k Keeper) GetWhitelistedAccountsForNFT( func (k Keeper) GetWhitelistedAccounts( ctx sdk.Context, q *query.PageRequest, ) ([]types.WhitelistedNFTAccounts, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) type nftUniqueID struct { classID string nftID string } whitelisted := make([]types.WhitelistedNFTAccounts, 0) nftUniqueIDToWhitelistIdx := make(map[nftUniqueID]int) - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), types.NFTWhitelistingKeyPrefix), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), types.NFTWhitelistingKeyPrefix), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -1000,9 +1035,10 @@ func (k Keeper) GetWhitelistedAccounts( func (k Keeper) GetAllClassWhitelistedAccounts( ctx sdk.Context, q *query.PageRequest, ) ([]types.ClassWhitelistedAccounts, *query.PageResponse, error) { + store := k.storeService.OpenKVStore(ctx) whitelisted := make([]types.ClassWhitelistedAccounts, 0) classIDToWhitelistedIdx := make(map[string]int) - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), types.NFTClassWhitelistingKeyPrefix), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), types.NFTClassWhitelistingKeyPrefix), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -1044,15 +1080,16 @@ func (k Keeper) GetAllClassWhitelistedAccounts( func (k Keeper) GetClassWhitelistedAccounts( ctx sdk.Context, classID string, q *query.PageRequest, ) ([]string, *query.PageResponse, error) { - compositeKey, err := store.JoinKeysWithLength([]byte(classID)) + store := k.storeService.OpenKVStore(ctx) + compositeKey, err := pkgstore.JoinKeysWithLength([]byte(classID)) if err != nil { return nil, nil, sdkerrors.Wrapf( types.ErrInvalidKey, "failed to create a composite key for nft, err: %s", err, ) } - key := store.JoinKeys(types.NFTClassWhitelistingKeyPrefix, compositeKey) + key := pkgstore.JoinKeys(types.NFTClassWhitelistingKeyPrefix, compositeKey) accounts := []string{} - pageRes, err := query.Paginate(prefix.NewStore(ctx.KVStore(k.storeKey), key), + pageRes, err := query.Paginate(prefix.NewStore(runtime.KVStoreAdapter(store), key), q, func(key, value []byte) error { if !bytes.Equal(value, types.StoreTrue) { return sdkerrors.Wrapf( @@ -1103,13 +1140,11 @@ func (k Keeper) SetWhitelisting( if err != nil { return err } - s := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) if whitelisting { - s.Set(key, types.StoreTrue) - } else { - s.Delete(key) + return store.Set(key, types.StoreTrue) } - return nil + return store.Delete(key) } // SetClassWhitelisting adds an account to the whitelisting of the Class, if whitelisting is true @@ -1121,13 +1156,11 @@ func (k Keeper) SetClassWhitelisting( if err != nil { return err } - s := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) if whitelisting { - s.Set(key, types.StoreTrue) - } else { - s.Delete(key) + return store.Set(key, types.StoreTrue) } - return nil + return store.Delete(key) } func (k Keeper) isNFTSendable(ctx sdk.Context, classID, nftID string) error { diff --git a/x/customparams/keeper/genesis.go b/x/customparams/keeper/genesis.go index 37515b862..ee74914d8 100644 --- a/x/customparams/keeper/genesis.go +++ b/x/customparams/keeper/genesis.go @@ -15,7 +15,9 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { // ExportGenesis returns the customparams module's exported genesis state. func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - return &types.GenesisState{ - StakingParams: k.GetStakingParams(ctx), + params, err := k.GetStakingParams(ctx) + if err != nil { + panic(err) } + return &types.GenesisState{StakingParams: params} } diff --git a/x/customparams/keeper/genesis_test.go b/x/customparams/keeper/genesis_test.go index c6a6c1c47..8b2815512 100644 --- a/x/customparams/keeper/genesis_test.go +++ b/x/customparams/keeper/genesis_test.go @@ -24,7 +24,9 @@ func TestKeeper_InitAndExportGenesis(t *testing.T) { keeper.InitGenesis(ctx, genState) requireT := require.New(t) - requireT.Equal(sdkmath.OneInt().String(), keeper.GetStakingParams(ctx).MinSelfDelegation.String()) + params, err := keeper.GetStakingParams(ctx) + requireT.NoError(err) + requireT.Equal(sdkmath.OneInt().String(), params.MinSelfDelegation.String()) exportedGetState := keeper.ExportGenesis(ctx) requireT.Equal(genState, *exportedGetState) diff --git a/x/customparams/keeper/grpc_query.go b/x/customparams/keeper/grpc_query.go index 5d934ede9..c592c249c 100644 --- a/x/customparams/keeper/grpc_query.go +++ b/x/customparams/keeper/grpc_query.go @@ -12,7 +12,7 @@ import ( // QueryKeeper defines subscope of keeper methods required by query service. type QueryKeeper interface { - GetStakingParams(ctx sdk.Context) types.StakingParams + GetStakingParams(ctx sdk.Context) (types.StakingParams, error) } // NewQueryService creates query service. @@ -36,7 +36,9 @@ func (qs QueryService) StakingParams( return nil, status.Error(codes.InvalidArgument, "empty request") } - return &types.QueryStakingParamsResponse{ - Params: qs.keeper.GetStakingParams(sdk.UnwrapSDKContext(ctx)), - }, nil + params, err := qs.keeper.GetStakingParams(sdk.UnwrapSDKContext(ctx)) + if err != nil { + return nil, err + } + return &types.QueryStakingParamsResponse{Params: params}, nil } diff --git a/x/customparams/keeper/keeper.go b/x/customparams/keeper/keeper.go index 09328040b..33c916b32 100644 --- a/x/customparams/keeper/keeper.go +++ b/x/customparams/keeper/keeper.go @@ -1,8 +1,8 @@ package keeper import ( + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" - storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -12,42 +12,42 @@ import ( // Keeper is customparams module Keeper. type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.BinaryCodec - authority string + storeService sdkstore.KVStoreService + cdc codec.BinaryCodec + authority string } // NewKeeper returns a new Keeper instance. func NewKeeper( - storeKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, cdc codec.BinaryCodec, authority string, ) Keeper { return Keeper{ - cdc: cdc, - storeKey: storeKey, - authority: authority, + cdc: cdc, + storeService: storeService, + authority: authority, } } // GetStakingParams returns the set of staking parameters. -func (k Keeper) GetStakingParams(ctx sdk.Context) types.StakingParams { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.StakingParamsKey) +func (k Keeper) GetStakingParams(ctx sdk.Context) (types.StakingParams, error) { + bz, err := k.storeService.OpenKVStore(ctx).Get(types.StakingParamsKey) + if err != nil { + return types.StakingParams{}, err + } var params types.StakingParams k.cdc.MustUnmarshal(bz, ¶ms) - return params + return params, nil } // SetStakingParams sets the module staking parameters to the param space. func (k Keeper) SetStakingParams(ctx sdk.Context, params types.StakingParams) error { - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { return err } - store.Set(types.StakingParamsKey, bz) - return nil + return k.storeService.OpenKVStore(ctx).Set(types.StakingParamsKey, bz) } // UpdateStakingParams is a governance operation that sets the staking parameters of the module. diff --git a/x/delay/keeper/keeper.go b/x/delay/keeper/keeper.go index 88e605fb7..e7fb3d863 100644 --- a/x/delay/keeper/keeper.go +++ b/x/delay/keeper/keeper.go @@ -3,11 +3,12 @@ package keeper import ( "time" + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" @@ -18,24 +19,24 @@ import ( // Keeper is delay module Keeper. type Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - router types.Router - registry codectypes.InterfaceRegistry + cdc codec.BinaryCodec + storeService sdkstore.KVStoreService + router types.Router + registry codectypes.InterfaceRegistry } // NewKeeper returns a new Keeper instance. func NewKeeper( cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, router types.Router, registry codectypes.InterfaceRegistry, ) Keeper { return Keeper{ - cdc: cdc, - storeKey: storeKey, - router: router, - registry: registry, + cdc: cdc, + storeService: storeService, + router: router, + registry: registry, } } @@ -66,9 +67,7 @@ func (k Keeper) RemoveExecuteAtBlock(ctx sdk.Context, id string, height uint64) return err } - store := ctx.KVStore(k.storeKey) - store.Delete(key) - return nil + return k.storeService.OpenKVStore(ctx).Delete(key) } // RemoveExecuteAfter removes an item to be executed at after specified time. @@ -78,9 +77,7 @@ func (k Keeper) RemoveExecuteAfter(ctx sdk.Context, id string, time time.Time) e return err } - store := ctx.KVStore(k.storeKey) - store.Delete(key) - return nil + return k.storeService.OpenKVStore(ctx).Delete(key) } // StoreDelayedExecution stores delayed execution item using absolute time. @@ -97,8 +94,12 @@ func (k Keeper) StoreDelayedExecution(ctx sdk.Context, id string, data proto.Mes return err } - store := ctx.KVStore(k.storeKey) - if store.Has(key) { + store := k.storeService.OpenKVStore(ctx) + val, err := store.Has(key) + if err != nil { + return err + } + if val { return sdkerrors.Wrapf(cosmoserrors.ErrUnauthorized, "delayed item is already stored under the key, id: %s", id) } @@ -111,8 +112,7 @@ func (k Keeper) StoreDelayedExecution(ctx sdk.Context, id string, data proto.Mes if err != nil { return sdkerrors.Wrapf(types.ErrInvalidData, "marshaling delayed item failed: %s", err.Error()) } - store.Set(key, b) - return nil + return store.Set(key, b) } // StoreBlockExecution stores block execution item using block height. @@ -130,8 +130,12 @@ func (k Keeper) StoreBlockExecution(ctx sdk.Context, id string, data proto.Messa return err } - store := ctx.KVStore(k.storeKey) - if store.Has(key) { + store := k.storeService.OpenKVStore(ctx) + val, err := store.Has(key) + if err != nil { + return err + } + if val { return sdkerrors.Wrapf(cosmoserrors.ErrUnauthorized, "block item is already stored under the key, id: %s", id) } @@ -144,8 +148,7 @@ func (k Keeper) StoreBlockExecution(ctx sdk.Context, id string, data proto.Messa if err != nil { return sdkerrors.Wrapf(types.ErrInvalidData, "marshaling block item failed: %s", err.Error()) } - store.Set(key, b) - return nil + return store.Set(key, b) } // ExecuteAllItems executes delayed and block items for the current block time and height. @@ -159,7 +162,8 @@ func (k Keeper) ExecuteAllItems(ctx sdk.Context) error { // ExecuteDelayedItems executes delayed logic. func (k Keeper) ExecuteDelayedItems(ctx sdk.Context) error { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.DelayedItemKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.DelayedItemKeyPrefix) // messages will be returned from this iterator in the execution time ascending order iter := store.Iterator(nil, nil) @@ -207,7 +211,8 @@ func (k Keeper) ImportDelayedItems(ctx sdk.Context, items []types.DelayedItem) e // //nolint:dupl // there is not duplication the code is similar in terms of structure, but different in terms of logic func (k Keeper) ExportDelayedItems(ctx sdk.Context) ([]types.DelayedItem, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.DelayedItemKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.DelayedItemKeyPrefix) delayedItems := make([]types.DelayedItem, 0) _, err := query.Paginate(store, &query.PageRequest{Limit: query.PaginationMaxLimit}, func(key, value []byte) error { executionTime, id, err := types.DecodeDelayedItemKey(key) @@ -237,7 +242,8 @@ func (k Keeper) ExportDelayedItems(ctx sdk.Context) ([]types.DelayedItem, error) // ExecuteBlockItems executes block logic. func (k Keeper) ExecuteBlockItems(ctx sdk.Context) error { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.BlockItemKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.BlockItemKeyPrefix) // messages will be returned from this iterator in the execution time ascending order iter := store.Iterator(nil, nil) @@ -284,7 +290,8 @@ func (k Keeper) ImportBlockItems(ctx sdk.Context, items []types.BlockItem) error // //nolint:dupl // there is not duplication the code is similar in terms of structure, but different in terms of logic func (k Keeper) ExportBlockItems(ctx sdk.Context) ([]types.BlockItem, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.BlockItemKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.BlockItemKeyPrefix) blockItems := make([]types.BlockItem, 0) _, err := query.Paginate(store, &query.PageRequest{Limit: query.PaginationMaxLimit}, func(key, value []byte) error { height, id, err := types.DecodeBlockItemKey(key) diff --git a/x/dex/genesis.go b/x/dex/genesis.go index 649e692a8..28e46a324 100644 --- a/x/dex/genesis.go +++ b/x/dex/genesis.go @@ -119,8 +119,13 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { panic(errors.Wrap(err, "failed to get order sequence")) } + params, err := k.GetParams(ctx) + if err != nil { + panic(errors.Wrap(err, "failed to get params")) + } + return &types.GenesisState{ - Params: k.GetParams(ctx), + Params: params, Orders: orders, OrderBooks: orderBooksWithID, OrderSequence: orderSequence, diff --git a/x/dex/genesis_test.go b/x/dex/genesis_test.go index 07d35db64..6b767c920 100644 --- a/x/dex/genesis_test.go +++ b/x/dex/genesis_test.go @@ -173,7 +173,8 @@ func TestInitAndExportGenesis(t *testing.T) { dex.InitGenesis(sdkCtx, dexKeeper, testApp.AccountKeeper, genState) // check imported state - params := dexKeeper.GetParams(sdkCtx) + params, err := dexKeeper.GetParams(sdkCtx) + requireT.NoError(err) requireT.EqualValues(prams, params) // check that export is equal import diff --git a/x/dex/keeper/grpc_query.go b/x/dex/keeper/grpc_query.go index c6fba3f3b..8da2a8ca5 100644 --- a/x/dex/keeper/grpc_query.go +++ b/x/dex/keeper/grpc_query.go @@ -14,7 +14,7 @@ var _ types.QueryServer = QueryService{} // QueryKeeper defines subscope of keeper methods required by query service. type QueryKeeper interface { - GetParams(ctx sdk.Context) types.Params + GetParams(ctx sdk.Context) (types.Params, error) GetOrderByAddressAndID(ctx sdk.Context, acc sdk.AccAddress, orderID string) (types.Order, error) GetOrders( ctx sdk.Context, @@ -45,9 +45,11 @@ type QueryService struct { // Params queries the parameters of x/asset/ft module. func (qs QueryService) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - return &types.QueryParamsResponse{ - Params: qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)), - }, nil + params, err := qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)) + if err != nil { + return nil, err + } + return &types.QueryParamsResponse{Params: params}, nil } // Orders returns creator orders. diff --git a/x/dex/keeper/keeper.go b/x/dex/keeper/keeper.go index eefe9b214..d5b93c5d9 100644 --- a/x/dex/keeper/keeper.go +++ b/x/dex/keeper/keeper.go @@ -3,12 +3,13 @@ package keeper import ( "math/big" + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" "cosmossdk.io/log" sdkmath "cosmossdk.io/math" "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -24,7 +25,7 @@ import ( // Keeper is the dex module keeper. type Keeper struct { cdc codec.BinaryCodec - storeKey storetypes.StoreKey + storeService sdkstore.KVStoreService accountKeeper types.AccountKeeper accountQueryServer types.AccountQueryServer assetFTKeeper types.AssetFTKeeper @@ -35,7 +36,7 @@ type Keeper struct { // NewKeeper creates a new instance of the Keeper. func NewKeeper( cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, accountKeeper types.AccountKeeper, accountQueryServer types.AccountQueryServer, assetFTKeeper types.AssetFTKeeper, @@ -44,7 +45,7 @@ func NewKeeper( ) Keeper { return Keeper{ cdc: cdc, - storeKey: storeKey, + storeService: storeService, accountKeeper: accountKeeper, accountQueryServer: accountQueryServer, assetFTKeeper: assetFTKeeper, @@ -57,7 +58,10 @@ func NewKeeper( func (k Keeper) PlaceOrder(ctx sdk.Context, order types.Order) error { k.logger(ctx).Debug("Placing order.", "order", order) - params := k.GetParams(ctx) + params, err := k.GetParams(ctx) + if err != nil { + return err + } if err := k.validateOrder(ctx, params, order); err != nil { return err } @@ -115,7 +119,9 @@ func (k Keeper) CancelOrdersByDenom(ctx sdk.Context, admin, acc sdk.AccAddress, return err } - iterator := prefix.NewStore(ctx.KVStore(k.storeKey), accountDenomKeyPrefix).Iterator(nil, nil) + store := k.storeService.OpenKVStore(ctx) + + iterator := prefix.NewStore(runtime.KVStoreAdapter(store), accountDenomKeyPrefix).Iterator(nil, nil) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { @@ -185,12 +191,14 @@ func (k Keeper) GetOrderBookOrders( } // GetParams gets the parameters of the module. -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) +func (k Keeper) GetParams(ctx sdk.Context) (types.Params, error) { + bz, err := k.storeService.OpenKVStore(ctx).Get(types.ParamsKey) + if err != nil { + return types.Params{}, err + } var params types.Params k.cdc.MustUnmarshal(bz, ¶ms) - return params + return params, nil } // UpdateParams is a governance operation that sets parameters of the module. @@ -207,13 +215,11 @@ func (k Keeper) UpdateParams(ctx sdk.Context, authority string, params types.Par // SetParams sets the parameters of the module. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { return err } - store.Set(types.ParamsKey, bz) - return nil + return k.storeService.OpenKVStore(ctx).Set(types.ParamsKey, bz) } // GetAccountsOrders returns paginated orders. @@ -221,7 +227,8 @@ func (k Keeper) GetAccountsOrders( ctx sdk.Context, pagination *query.PageRequest, ) ([]types.Order, *query.PageResponse, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.OrderIDToSequenceKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.OrderIDToSequenceKeyPrefix) orderBookIDToOrderBookData := make(map[uint32]types.OrderBookData) accNumberToAddCache := make(map[uint64]sdk.AccAddress) orders, pageRes, err := query.GenericFilteredPaginate( @@ -354,7 +361,8 @@ func (k Keeper) GetAccountsDenomsOrdersCounts( ctx sdk.Context, pagination *query.PageRequest, ) ([]types.AccountDenomOrdersCount, *query.PageResponse, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AccountDenomOrdersCountKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.AccountDenomOrdersCountKeyPrefix) counts, pageRes, err := query.GenericFilteredPaginate( k.cdc, store, @@ -726,7 +734,10 @@ func (k Keeper) removeOrderByRecord( return err } } - k.removeOrderData(ctx, record.OrderSequence) + + if err = k.removeOrderData(ctx, record.OrderSequence); err != nil { + return err + } if err := k.removeOrderIDToSequence(ctx, record.AccountNumber, record.OrderID); err != nil { return err @@ -927,8 +938,8 @@ func (k Keeper) getPaginatedOrders( if err != nil { return nil, nil, err } - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CreateOrderIDToSequenceKeyPrefix(accNumber)) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.CreateOrderIDToSequenceKeyPrefix(accNumber)) orderBookIDToOrderBookData := make(map[uint32]types.OrderBookData) orders, pageRes, err := query.GenericFilteredPaginate( k.cdc, @@ -997,7 +1008,8 @@ func (k Keeper) getPaginatedOrderBooksWithID( ctx sdk.Context, pagination *query.PageRequest, ) ([]types.OrderBookDataWithID, *query.PageResponse, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.OrderBookDataKeyPrefix) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.OrderBookDataKeyPrefix) orders, pageRes, err := query.GenericFilteredPaginate( k.cdc, store, @@ -1038,7 +1050,8 @@ func (k Keeper) getPaginatedOrderBookOrders( return nil, nil, err } - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CreateOrderBookSideKey(orderBookID, side)) + moduleStore := k.storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.CreateOrderBookSideKey(orderBookID, side)) accNumberToAddCache := make(map[uint64]sdk.AccAddress) orders, pageRes, err := query.GenericFilteredPaginate( @@ -1105,17 +1118,15 @@ func (k Keeper) removeOrderBookRecord( if err != nil { return err } - ctx.KVStore(k.storeKey).Delete(key) - - return nil + return k.storeService.OpenKVStore(ctx).Delete(key) } func (k Keeper) saveOrderData(ctx sdk.Context, orderSequence uint64, data types.OrderData) error { return k.setDataToStore(ctx, types.CreateOrderKey(orderSequence), &data) } -func (k Keeper) removeOrderData(ctx sdk.Context, orderSequence uint64) { - ctx.KVStore(k.storeKey).Delete(types.CreateOrderKey(orderSequence)) +func (k Keeper) removeOrderData(ctx sdk.Context, orderSequence uint64) error { + return k.storeService.OpenKVStore(ctx).Delete(types.CreateOrderKey(orderSequence)) } func (k Keeper) getOrderData(ctx sdk.Context, orderSequence uint64) (types.OrderData, error) { @@ -1132,8 +1143,7 @@ func (k Keeper) saveOrderIDToSequence(ctx sdk.Context, accNumber uint64, orderID } func (k Keeper) removeOrderIDToSequence(ctx sdk.Context, accNumber uint64, orderID string) error { - ctx.KVStore(k.storeKey).Delete(types.CreateOrderIDToSequenceKey(accNumber, orderID)) - return nil + return k.storeService.OpenKVStore(ctx).Delete(types.CreateOrderIDToSequenceKey(accNumber, orderID)) } func (k Keeper) getOrderSequenceByID(ctx sdk.Context, accNumber uint64, orderID string) (uint64, error) { @@ -1214,7 +1224,10 @@ func (k Keeper) saveAccountDenomOrderSequence( return err } // save empty slice - ctx.KVStore(k.storeKey).Set(key, make([]byte, 0)) + + if err = k.storeService.OpenKVStore(ctx).Set(key, make([]byte, 0)); err != nil { + return err + } } return nil @@ -1229,7 +1242,10 @@ func (k Keeper) removeAccountDenomOrderSequence( return err } // remove all - ctx.KVStore(k.storeKey).Delete(key) + err = k.storeService.OpenKVStore(ctx).Delete(key) + if err != nil { + return err + } } return nil diff --git a/x/dex/keeper/keeper_ft_test.go b/x/dex/keeper/keeper_ft_test.go index d00ebee47..8ab7fec40 100644 --- a/x/dex/keeper/keeper_ft_test.go +++ b/x/dex/keeper/keeper_ft_test.go @@ -320,7 +320,9 @@ func TestKeeper_PlaceOrderWithStaking(t *testing.T) { require.NoError(t, testApp.DEXKeeper.PlaceOrder(sdkCtx, order)) balance = testApp.BankKeeper.GetBalance(sdkCtx, acc, denomToStake) - orderReserve := testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + orderReserve := params.OrderReserve require.Equal(t, orderLockedBalance.Add(orderReserve).String(), balance.String()) lockedBalance = testApp.AssetFTKeeper.GetDEXLockedBalance(sdkCtx, acc, denomToStake) diff --git a/x/dex/keeper/keeper_matching.go b/x/dex/keeper/keeper_matching.go index 443b069d2..59f08e953 100644 --- a/x/dex/keeper/keeper_matching.go +++ b/x/dex/keeper/keeper_matching.go @@ -154,7 +154,10 @@ func (k Keeper) getInitialRemainingAmount( } case types.ORDER_TYPE_MARKET: if order.Side == types.SIDE_BUY { - remainingBalance = k.assetFTKeeper.GetSpendableBalance(ctx, creatorAddr, order.QuoteDenom) + remainingBalance, err = k.assetFTKeeper.GetSpendableBalance(ctx, creatorAddr, order.QuoteDenom) + if err != nil { + return sdkmath.Int{}, err + } } else { remainingBalance = sdk.NewCoin(order.BaseDenom, order.Quantity) } diff --git a/x/dex/keeper/keeper_matching_fuzz_test.go b/x/dex/keeper/keeper_matching_fuzz_test.go index 3d6b28ee6..4f5aa268f 100644 --- a/x/dex/keeper/keeper_matching_fuzz_test.go +++ b/x/dex/keeper/keeper_matching_fuzz_test.go @@ -75,7 +75,8 @@ func NewFuzzApp( sdkCtx, _, _ := testApp.BeginNextBlock() - params := testApp.DEXKeeper.GetParams(sdkCtx) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) params.PriceTickExponent = int32(-10) // use low but not too much require.NoError(t, testApp.DEXKeeper.SetParams(sdkCtx, params)) @@ -160,7 +161,7 @@ func NewFuzzApp( types.SIDE_SELL, } - _, err := testApp.EndBlocker(sdkCtx) + _, err = testApp.EndBlocker(sdkCtx) require.NoError(t, err) return FuzzApp{ @@ -375,8 +376,12 @@ func (fa *FuzzApp) FundAccountAndApplyFTFeatures( if order.Type == types.ORDER_TYPE_LIMIT && order.TimeInForce == types.TIME_IN_FORCE_GTC && randBoolWithPercent(orderRnd, fa.cfg.FundOrderReservePercent) { - reserve := fa.testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve - spendableBalance := fa.testApp.AssetFTKeeper.GetSpendableBalance(sdkCtx, creator, reserve.Denom) + params, err := fa.testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + reserve := params.OrderReserve + + spendableBalance, err := fa.testApp.AssetFTKeeper.GetSpendableBalance(sdkCtx, creator, reserve.Denom) + require.NoError(t, err) if spendableBalance.IsLT(reserve) { t.Logf("Funding order reserve, account: %s coin: %s", creator.String(), reserve.String()) fa.testApp.MintAndSendCoin(t, sdkCtx, creator, sdk.NewCoins(reserve)) @@ -389,7 +394,8 @@ func (fa *FuzzApp) AdjustAppState(t *testing.T, sdkCtx sdk.Context, rnd *rand.Ra if randBoolWithPercent(rnd, fa.cfg.UnifiedRefAmountChangePercent) { // change globally if randBool(rnd) { - params := fa.testApp.DEXKeeper.GetParams(sdkCtx) + params, err := fa.testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) params.DefaultUnifiedRefAmount = randPositiveSDKDec(rnd) t.Logf("Updating new default unified ref amount: %s", params.DefaultUnifiedRefAmount.String()) @@ -448,10 +454,13 @@ func (fa *FuzzApp) PlaceOrder(t *testing.T, sdkCtx sdk.Context, order types.Orde return } // check failed because of reserve - reserve := fa.testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve - reserveDenomSpendableBalance := fa.testApp.AssetFTKeeper.GetSpendableBalance( + params, err := fa.testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + reserve := params.OrderReserve + reserveDenomSpendableBalance, err := fa.testApp.AssetFTKeeper.GetSpendableBalance( sdkCtx, creator, reserve.Denom, ) + require.NoError(t, err) if reserveDenomSpendableBalance.Amount.LT(reserve.Amount) { t.Logf("Placement is failed due to insufficient reserve, reserve: %s, reserveDenomSpendableBalance: %s", reserve.String(), reserveDenomSpendableBalance.String()) @@ -459,9 +468,10 @@ func (fa *FuzzApp) PlaceOrder(t *testing.T, sdkCtx sdk.Context, order types.Orde } // check spendable balance - spendableBalance := fa.testApp.AssetFTKeeper.GetSpendableBalance( + spendableBalance, err := fa.testApp.AssetFTKeeper.GetSpendableBalance( sdkCtx, creator, order.GetSpendDenom(), ) + require.NoError(t, err) orderLockedBalance, err := order.ComputeLimitOrderLockedBalance() require.NoError(t, err) require.True( @@ -519,7 +529,8 @@ func (fa *FuzzApp) PlaceOrder(t *testing.T, sdkCtx sdk.Context, order types.Orde } } - availableBalancesBefore := getAvailableBalances(sdkCtx, fa.testApp, sdk.MustAccAddressFromBech32(order.Creator)) + availableBalancesBefore, err := getAvailableBalances(sdkCtx, fa.testApp, sdk.MustAccAddressFromBech32(order.Creator)) + require.NoError(t, err) // use empty event manager for each order placement to check events properly sdkCtx = sdkCtx.WithEventManager(sdk.NewEventManager()) @@ -561,7 +572,9 @@ func (fa *FuzzApp) CancelOrdersByDenom(t *testing.T, sdkCtx sdk.Context, account return } - require.LessOrEqual(t, count, fa.testApp.DEXKeeper.GetParams(sdkCtx).MaxOrdersPerDenom) + params, err := fa.testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + require.LessOrEqual(t, count, params.MaxOrdersPerDenom) require.NoError(t, fa.testApp.DEXKeeper.CancelOrdersByDenom( sdkCtx, diff --git a/x/dex/keeper/keeper_matching_test.go b/x/dex/keeper/keeper_matching_test.go index 8c75faff1..5ad3706a7 100644 --- a/x/dex/keeper/keeper_matching_test.go +++ b/x/dex/keeper/keeper_matching_test.go @@ -6336,12 +6336,13 @@ func TestKeeper_MatchOrders(t *testing.T) { for i, order := range initialOrders { ordersDenoms[order.BaseDenom] = struct{}{} ordersDenoms[order.QuoteDenom] = struct{}{} - availableBalancesBefore := getAvailableBalances(sdkCtx, testApp, sdk.MustAccAddressFromBech32(order.Creator)) + availableBalancesBefore, err := getAvailableBalances(sdkCtx, testApp, sdk.MustAccAddressFromBech32(order.Creator)) + require.NoError(t, err) // use new event manager for each order sdkCtx = sdkCtx.WithEventManager(sdk.NewEventManager()) gasBefore := sdkCtx.GasMeter().GasConsumed() - err := testApp.DEXKeeper.PlaceOrder(sdkCtx, order) + err = testApp.DEXKeeper.PlaceOrder(sdkCtx, order) if err != nil && tt.wantErrorContains != "" { require.True(t, sdkerrors.IsOf( err, @@ -6429,8 +6430,10 @@ func TestKeeper_MatchOrders(t *testing.T) { coins = sdk.NewCoins() } coins = coins.Add(sdk.NewCoin(order.GetSpendDenom(), order.RemainingBalance)) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) // add reserve for each order - coins = coins.Add(testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve) + coins = coins.Add(params.OrderReserve) orderLockedBalances[order.Creator] = coins } orderLockedBalances = removeEmptyBalances(orderLockedBalances) @@ -6476,6 +6479,9 @@ func genTestSet(t *testing.T, sdkCtx sdk.Context, testApp *simapp.App) TestSet { }) require.NoError(t, err) + param, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + testSet := TestSet{ acc1: acc1, acc2: acc2, @@ -6485,7 +6491,7 @@ func genTestSet(t *testing.T, sdkCtx sdk.Context, testApp *simapp.App) TestSet { ftDenomWhitelisting1: ftDenomWhitelisting1, ftDenomWhitelisting2: ftDenomWhitelisting2, - orderReserve: testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve, + orderReserve: param.OrderReserve, } return testSet @@ -6507,7 +6513,9 @@ func fillReserveAndOrderSequence( testApp *simapp.App, orders []types.Order, ) []types.Order { - orderReserve := testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + orderReserve := params.OrderReserve for i, order := range orders { storedOrder, err := testApp.DEXKeeper.GetOrderByAddressAndID( sdkCtx, sdk.MustAccAddressFromBech32(order.Creator), order.ID, @@ -6666,7 +6674,8 @@ func assetOrderSentReceivedAmounts( if !ok { availableAmtBefore = sdkmath.ZeroInt() } - availableBalancesAfter := getAvailableBalances(sdkCtx, testApp, creator) + availableBalancesAfter, err := getAvailableBalances(sdkCtx, testApp, creator) + require.NoError(t, err) availableBalanceAmtAfter, ok := availableBalancesAfter[order.GetSpendDenom()] if !ok { availableBalanceAmtAfter = sdkmath.ZeroInt() @@ -6741,17 +6750,21 @@ func assertFilledQuantity(t *testing.T, order types.Order, sent, receiveAmt sdkm require.True(t, order.Quantity.GTE(filledQuantity)) } -func getAvailableBalances(sdkCtx sdk.Context, testApp *simapp.App, acc sdk.AccAddress) map[string]sdkmath.Int { +func getAvailableBalances(sdkCtx sdk.Context, testApp *simapp.App, acc sdk.AccAddress) (map[string]sdkmath.Int, error) { balances := testApp.BankKeeper.GetAllBalances(sdkCtx, acc) spendableBalances := make(map[string]sdkmath.Int) for _, balance := range balances { - frozenAmt := testApp.AssetFTKeeper.GetFrozenBalance(sdkCtx, acc, balance.Denom).Amount + frozenBalance, err := testApp.AssetFTKeeper.GetFrozenBalance(sdkCtx, acc, balance.Denom) + if err != nil { + return nil, err + } + frozenAmt := frozenBalance.Amount dexLockedAmt := testApp.AssetFTKeeper.GetDEXLockedBalance(sdkCtx, acc, balance.Denom).Amount // can be negative spendableBalances[balance.Denom] = balance.Amount.Sub(frozenAmt).Sub(dexLockedAmt) } - return spendableBalances + return spendableBalances, nil } func cancelAllOrdersAndAssertState( diff --git a/x/dex/keeper/keeper_ob_iterator.go b/x/dex/keeper/keeper_ob_iterator.go index 62ce5cfe1..af5ff9550 100644 --- a/x/dex/keeper/keeper_ob_iterator.go +++ b/x/dex/keeper/keeper_ob_iterator.go @@ -1,10 +1,12 @@ package keeper import ( + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/CoreumFoundation/coreum/v5/x/dex/types" @@ -25,12 +27,13 @@ type OrderBookIterator struct { func NewOrderBookIterator( ctx sdk.Context, cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, orderBookID uint32, side types.Side, readFromTail bool, ) *OrderBookIterator { - store := prefix.NewStore(ctx.KVStore(storeKey), types.CreateOrderBookSideKey(orderBookID, side)) + moduleStore := storeService.OpenKVStore(ctx) + store := prefix.NewStore(runtime.KVStoreAdapter(moduleStore), types.CreateOrderBookSideKey(orderBookID, side)) var iterator storetypes.Iterator if readFromTail { iterator = store.ReverseIterator(nil, nil) @@ -176,5 +179,5 @@ func (k Keeper) NewOrderBookSideIterator(ctx sdk.Context, orderBookID uint32, si readFromTail = true } - return NewOrderBookIterator(ctx, k.cdc, k.storeKey, orderBookID, side, readFromTail) + return NewOrderBookIterator(ctx, k.cdc, k.storeService, orderBookID, side, readFromTail) } diff --git a/x/dex/keeper/keeper_ob_iterator_fuzz_test.go b/x/dex/keeper/keeper_ob_iterator_fuzz_test.go index 2b195bc17..0172f6b90 100644 --- a/x/dex/keeper/keeper_ob_iterator_fuzz_test.go +++ b/x/dex/keeper/keeper_ob_iterator_fuzz_test.go @@ -25,11 +25,12 @@ func FuzzSaveSellOrderAndReadWithSorting(f *testing.F) { // don't limit the price tick sdkCtx, _, _ := testApp.BeginNextBlock() - params := testApp.DEXKeeper.GetParams(sdkCtx) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(f, err) params.PriceTickExponent = int32(types.MinExp) require.NoError(f, testApp.DEXKeeper.SetParams(sdkCtx, params)) - _, err := testApp.EndBlocker(sdkCtx) + _, err = testApp.EndBlocker(sdkCtx) require.NoError(f, err) f.Fuzz(func(t *testing.T, num uint64, exp int8) { @@ -56,11 +57,12 @@ func FuzzSaveBuyOrderAndReadWithSorting(f *testing.F) { // don't limit the price tick sdkCtx, _, _ := testApp.BeginNextBlock() - params := testApp.DEXKeeper.GetParams(sdkCtx) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(f, err) params.PriceTickExponent = int32(types.MinExp) require.NoError(f, testApp.DEXKeeper.SetParams(sdkCtx, params)) - _, err := testApp.EndBlocker(sdkCtx) + _, err = testApp.EndBlocker(sdkCtx) require.NoError(f, err) f.Fuzz(func(t *testing.T, num uint64, exp int8) { diff --git a/x/dex/keeper/keeper_ob_iterator_test.go b/x/dex/keeper/keeper_ob_iterator_test.go index 27b0e500f..e3f2b60eb 100644 --- a/x/dex/keeper/keeper_ob_iterator_test.go +++ b/x/dex/keeper/keeper_ob_iterator_test.go @@ -231,7 +231,8 @@ func TestKeeper_SaveOrderAndReadWithOrderBookIterator(t *testing.T) { require.NoError(t, err) // don't limit the price tick - params := testApp.DEXKeeper.GetParams(sdkCtx) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) params.PriceTickExponent = int32(types.MinExp) require.NoError(t, testApp.DEXKeeper.SetParams(sdkCtx, params)) diff --git a/x/dex/keeper/keeper_store.go b/x/dex/keeper/keeper_store.go index a638de573..2aa99b8a3 100644 --- a/x/dex/keeper/keeper_store.go +++ b/x/dex/keeper/keeper_store.go @@ -87,8 +87,7 @@ func (k Keeper) setDataToStore( if err != nil { return sdkerrors.Wrapf(types.ErrInvalidState, "failed to marshal %T, err: %s", err, val) } - ctx.KVStore(k.storeKey).Set(key, bz) - return nil + return k.storeService.OpenKVStore(ctx).Set(key, bz) } func (k Keeper) getDataFromStore( @@ -96,7 +95,10 @@ func (k Keeper) getDataFromStore( key []byte, val proto.Message, ) error { - bz := ctx.KVStore(k.storeKey).Get(key) + bz, err := k.storeService.OpenKVStore(ctx).Get(key) + if err != nil { + return err + } if bz == nil { return sdkerrors.Wrapf(types.ErrRecordNotFound, "store type %T", val) } diff --git a/x/dex/keeper/keeper_test.go b/x/dex/keeper/keeper_test.go index 27e8cc1df..2bb8d55a5 100644 --- a/x/dex/keeper/keeper_test.go +++ b/x/dex/keeper/keeper_test.go @@ -88,7 +88,8 @@ func TestKeeper_UpdateParams(t *testing.T) { sdkCtx := testApp.BaseApp.NewContext(false) dexKeeper := testApp.DEXKeeper - gotParams := dexKeeper.GetParams(sdkCtx) + gotParams, err := dexKeeper.GetParams(sdkCtx) + require.NoError(t, err) require.Equal(t, types.DefaultParams(), gotParams) newPrams := gotParams @@ -102,7 +103,8 @@ func TestKeeper_UpdateParams(t *testing.T) { govAddr := authtypes.NewModuleAddress(govtypes.ModuleName).String() require.NoError(t, dexKeeper.UpdateParams(sdkCtx, govAddr, newPrams)) - gotParams = dexKeeper.GetParams(sdkCtx) + gotParams, err = dexKeeper.GetParams(sdkCtx) + require.NoError(t, err) require.Equal(t, newPrams, gotParams) } @@ -226,7 +228,9 @@ func TestKeeper_PlaceAndGetOrderByID(t *testing.T) { sellOrder.Sequence = 1 sellOrder.RemainingQuantity = sdkmath.NewInt(10) sellOrder.RemainingBalance = sdkmath.NewInt(10) - orderReserve := testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + orderReserve := params.OrderReserve sellOrder.Reserve = orderReserve require.Equal(t, sellOrder, gotOrder) @@ -547,15 +551,15 @@ func TestKeeper_PlaceOrderWithPriceTick(t *testing.T) { sdkCtx := testApp.BaseApp.NewContext(false) if tt.baseDenomRefAmount != nil { - testApp.AssetFTKeeper.SetDEXSettings(sdkCtx, denom1, assetfttypes.DEXSettings{ + require.NoError(t, testApp.AssetFTKeeper.SetDEXSettings(sdkCtx, denom1, assetfttypes.DEXSettings{ UnifiedRefAmount: tt.baseDenomRefAmount, - }) + })) } if tt.quoteDenomRefAmount != nil { - testApp.AssetFTKeeper.SetDEXSettings(sdkCtx, denom2, assetfttypes.DEXSettings{ + require.NoError(t, testApp.AssetFTKeeper.SetDEXSettings(sdkCtx, denom2, assetfttypes.DEXSettings{ UnifiedRefAmount: tt.quoteDenomRefAmount, - }) + })) } acc, _ := testApp.GenAccount(sdkCtx) @@ -851,7 +855,8 @@ func TestKeeper_PlaceAndCancelOrderWithMaxAllowedAccountDenomOrdersCount(t *test testApp := simapp.New() sdkCtx := testApp.BaseApp.NewContext(false) - params := testApp.DEXKeeper.GetParams(sdkCtx) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) params.MaxOrdersPerDenom = 2 require.NoError(t, testApp.DEXKeeper.SetParams(sdkCtx, params)) @@ -1003,7 +1008,8 @@ func TestKeeper_PlaceAndCancelOrdersByDenom(t *testing.T) { testApp := simapp.New() sdkCtx := testApp.BaseApp.NewContext(false) - params := testApp.DEXKeeper.GetParams(sdkCtx) + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) require.NoError(t, testApp.DEXKeeper.SetParams(sdkCtx, params)) acc1, _ := testApp.GenAccount(sdkCtx) @@ -1258,7 +1264,9 @@ func fundOrderReserve( sdkCtx sdk.Context, acc sdk.AccAddress, ) { - orderReserve := testApp.DEXKeeper.GetParams(sdkCtx).OrderReserve + params, err := testApp.DEXKeeper.GetParams(sdkCtx) + require.NoError(t, err) + orderReserve := params.OrderReserve if !orderReserve.IsPositive() { return } diff --git a/x/dex/types/expected_keepers.go b/x/dex/types/expected_keepers.go index 59b7a04d9..d0472b531 100644 --- a/x/dex/types/expected_keepers.go +++ b/x/dex/types/expected_keepers.go @@ -1,7 +1,7 @@ package types import ( - context "context" + "context" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -27,7 +27,7 @@ type AccountQueryServer interface { type AssetFTKeeper interface { DEXExecuteActions(ctx sdk.Context, actions dextypes.DEXActions) error DEXDecreaseLimits(ctx sdk.Context, addr sdk.AccAddress, lockedCoin sdk.Coins, expectedToReceiveCoin sdk.Coin) error - GetSpendableBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + GetSpendableBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) (sdk.Coin, error) GetDEXSettings(ctx sdk.Context, denom string) (dextypes.DEXSettings, error) ValidateDEXCancelOrdersByDenomIsAllowed(ctx sdk.Context, addr sdk.AccAddress, denom string) error } diff --git a/x/feemodel/ante/ante.go b/x/feemodel/ante/ante.go index 98d3946ed..daac3217b 100644 --- a/x/feemodel/ante/ante.go +++ b/x/feemodel/ante/ante.go @@ -11,7 +11,7 @@ import ( // Keeper interface exposes methods required by ante handler decorator of fee model. type Keeper interface { - TrackGas(ctx sdk.Context, gas int64) + TrackGas(ctx sdk.Context, gas int64) error GetMinGasPrice(ctx sdk.Context) sdk.DecCoin } @@ -47,7 +47,9 @@ func (fd FeeDecorator) AnteHandle( return ctx, err } - fd.collectFeeModelInput(ctx, feeTx) + if err := fd.collectFeeModelInput(ctx, feeTx); err != nil { + return ctx, err + } return next(ctx, tx, simulate) } @@ -77,6 +79,6 @@ func (fd FeeDecorator) actOnFeeModelOutput(ctx sdk.Context, feeTx sdk.FeeTx) err return nil } -func (fd FeeDecorator) collectFeeModelInput(ctx sdk.Context, feeTx sdk.FeeTx) { - fd.keeper.TrackGas(ctx, int64(feeTx.GetGas())) +func (fd FeeDecorator) collectFeeModelInput(ctx sdk.Context, feeTx sdk.FeeTx) error { + return fd.keeper.TrackGas(ctx, int64(feeTx.GetGas())) } diff --git a/x/feemodel/keeper/grpc.go b/x/feemodel/keeper/grpc.go index ae7fbd673..d4410137d 100644 --- a/x/feemodel/keeper/grpc.go +++ b/x/feemodel/keeper/grpc.go @@ -12,7 +12,7 @@ import ( // QueryKeeper defines subscope of keeper methods required by query service. type QueryKeeper interface { - GetParams(ctx sdk.Context) types.Params + GetParams(ctx sdk.Context) (types.Params, error) GetMinGasPrice(ctx sdk.Context) sdk.DecCoin CalculateEdgeGasPriceAfterBlocks(ctx sdk.Context, after uint32) (sdk.DecCoin, sdk.DecCoin, error) } @@ -69,7 +69,9 @@ func (qs QueryService) Params(ctx context.Context, req *types.QueryParamsRequest return nil, status.Error(codes.InvalidArgument, "empty request") } - return &types.QueryParamsResponse{ - Params: qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)), - }, nil + params, err := qs.keeper.GetParams(sdk.UnwrapSDKContext(ctx)) + if err != nil { + return nil, err + } + return &types.QueryParamsResponse{Params: params}, nil } diff --git a/x/feemodel/keeper/keeper.go b/x/feemodel/keeper/keeper.go index 602c2ed7b..8ab37d0db 100644 --- a/x/feemodel/keeper/keeper.go +++ b/x/feemodel/keeper/keeper.go @@ -1,9 +1,9 @@ package keeper import ( + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -14,33 +14,36 @@ import ( // Keeper is a fee model keeper. type Keeper struct { - storeKey storetypes.StoreKey - transientStoreKey storetypes.StoreKey - cdc codec.BinaryCodec - authority string + storeService sdkstore.KVStoreService + transientStoreService sdkstore.TransientStoreService + cdc codec.BinaryCodec + authority string } // NewKeeper returns a new keeper object providing storage options required by fee model. func NewKeeper( - storeKey storetypes.StoreKey, - transientStoreKey storetypes.StoreKey, + storeService sdkstore.KVStoreService, + transientStoreService sdkstore.TransientStoreService, cdc codec.BinaryCodec, authority string, ) Keeper { return Keeper{ - storeKey: storeKey, - transientStoreKey: transientStoreKey, - cdc: cdc, - authority: authority, + storeService: storeService, + transientStoreService: transientStoreService, + cdc: cdc, + authority: authority, } } // TrackedGas returns gas limits declared by transactions executed so far in current block. func (k Keeper) TrackedGas(ctx sdk.Context) int64 { - tStore := ctx.TransientStore(k.transientStoreKey) + tStore := k.transientStoreService.OpenTransientStore(ctx) gasUsed := sdkmath.NewInt(0) - bz := tStore.Get(gasTrackingKey) + bz, err := tStore.Get(gasTrackingKey) + if err != nil { + panic(err) + } if bz != nil { if err := gasUsed.Unmarshal(bz); err != nil { @@ -52,33 +55,33 @@ func (k Keeper) TrackedGas(ctx sdk.Context) int64 { } // TrackGas increments gas tracked for current block. -func (k Keeper) TrackGas(ctx sdk.Context, gas int64) { - tStore := ctx.TransientStore(k.transientStoreKey) +func (k Keeper) TrackGas(ctx sdk.Context, gas int64) error { + tStore := k.transientStoreService.OpenTransientStore(ctx) bz, err := sdkmath.NewInt(k.TrackedGas(ctx) + gas).Marshal() if err != nil { panic(err) } - tStore.Set(gasTrackingKey, bz) + return tStore.Set(gasTrackingKey, bz) } // SetParams sets the parameters of the module. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { return err } - store.Set(paramsKey, bz) - return nil + return k.storeService.OpenKVStore(ctx).Set(paramsKey, bz) } // GetParams gets the parameters of the module. -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get(paramsKey) +func (k Keeper) GetParams(ctx sdk.Context) (types.Params, error) { + bz, err := k.storeService.OpenKVStore(ctx).Get(paramsKey) + if err != nil { + return types.Params{}, err + } var params types.Params k.cdc.MustUnmarshal(bz, ¶ms) - return params + return params, nil } // UpdateParams is a governance operation that sets parameters of the module. @@ -93,8 +96,10 @@ func (k Keeper) UpdateParams(ctx sdk.Context, authority string, params types.Par // GetShortEMAGas retrieves average gas used by previous blocks, used as a representation of // smoothed gas used by latest block. func (k Keeper) GetShortEMAGas(ctx sdk.Context) int64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(shortEMAGasKey) + bz, err := k.storeService.OpenKVStore(ctx).Get(shortEMAGasKey) + if err != nil { + panic(err) + } if bz == nil { return 0 @@ -109,22 +114,22 @@ func (k Keeper) GetShortEMAGas(ctx sdk.Context) int64 { // SetShortEMAGas sets average gas used by previous blocks, used as a representation of smoothed gas // used by latest block. -func (k Keeper) SetShortEMAGas(ctx sdk.Context, emaGas int64) { - store := ctx.KVStore(k.storeKey) - +func (k Keeper) SetShortEMAGas(ctx sdk.Context, emaGas int64) error { bz, err := sdkmath.NewInt(emaGas).Marshal() if err != nil { panic(err) } - store.Set(shortEMAGasKey, bz) + return k.storeService.OpenKVStore(ctx).Set(shortEMAGasKey, bz) } // GetLongEMAGas retrieves long average gas used by previous blocks, used for determining average block // load where maximum discount is applied. func (k Keeper) GetLongEMAGas(ctx sdk.Context) int64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(longEMAGasKey) + bz, err := k.storeService.OpenKVStore(ctx).Get(longEMAGasKey) + if err != nil { + panic(err) + } if bz == nil { return 0 @@ -139,21 +144,21 @@ func (k Keeper) GetLongEMAGas(ctx sdk.Context) int64 { // SetLongEMAGas sets long average gas used by previous blocks, used for determining average block load where // maximum discount is applied. -func (k Keeper) SetLongEMAGas(ctx sdk.Context, emaGas int64) { - store := ctx.KVStore(k.storeKey) - +func (k Keeper) SetLongEMAGas(ctx sdk.Context, emaGas int64) error { bz, err := sdkmath.NewInt(emaGas).Marshal() if err != nil { panic(err) } - store.Set(longEMAGasKey, bz) + return k.storeService.OpenKVStore(ctx).Set(longEMAGasKey, bz) } // GetMinGasPrice returns current minimum gas price required by the network. func (k Keeper) GetMinGasPrice(ctx sdk.Context) sdk.DecCoin { - store := ctx.KVStore(k.storeKey) - bz := store.Get(gasPriceKey) + bz, err := k.storeService.OpenKVStore(ctx).Get(gasPriceKey) + if err != nil { + panic(err) + } if bz == nil { // This is really a panic condition because it means that genesis initialization was not done correctly panic("min gas price not set") @@ -166,18 +171,21 @@ func (k Keeper) GetMinGasPrice(ctx sdk.Context) sdk.DecCoin { } // SetMinGasPrice sets minimum gas price required by the network on current block. -func (k Keeper) SetMinGasPrice(ctx sdk.Context, minGasPrice sdk.DecCoin) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) SetMinGasPrice(ctx sdk.Context, minGasPrice sdk.DecCoin) error { bz, err := minGasPrice.Marshal() if err != nil { panic(err) } - store.Set(gasPriceKey, bz) + return k.storeService.OpenKVStore(ctx).Set(gasPriceKey, bz) } // CalculateEdgeGasPriceAfterBlocks returns the smallest and highest possible values for min gas price in future blocks. func (k Keeper) CalculateEdgeGasPriceAfterBlocks(ctx sdk.Context, after uint32) (sdk.DecCoin, sdk.DecCoin, error) { - shortEMABlockLength := k.GetParams(ctx).Model.ShortEmaBlockLength + params, err := k.GetParams(ctx) + if err != nil { + return sdk.DecCoin{}, sdk.DecCoin{}, err + } + shortEMABlockLength := params.Model.ShortEmaBlockLength if after > shortEMABlockLength { return sdk.DecCoin{}, sdk.DecCoin{}, sdkerrors.Wrapf( cosmoserrors.ErrInvalidRequest, @@ -191,7 +199,11 @@ func (k Keeper) CalculateEdgeGasPriceAfterBlocks(ctx sdk.Context, after uint32) after = shortEMABlockLength } - params := k.GetParams(ctx) + params, err = k.GetParams(ctx) + if err != nil { + return sdk.DecCoin{}, sdk.DecCoin{}, err + } + shortEMA := k.GetShortEMAGas(ctx) longEMA := k.GetLongEMAGas(ctx) diff --git a/x/feemodel/keeper/keeper_test.go b/x/feemodel/keeper/keeper_test.go index 1b7f952c6..6d6fe2b92 100644 --- a/x/feemodel/keeper/keeper_test.go +++ b/x/feemodel/keeper/keeper_test.go @@ -10,6 +10,7 @@ import ( storetypes "cosmossdk.io/store/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -32,7 +33,11 @@ func setup() (sdk.Context, keeper.Keeper) { must.OK(cms.LoadLatestVersion()) ctx := sdk.NewContext(cms, tmproto.Header{}, false, log.NewNopLogger()) encodingConfig := config.NewEncodingConfig(feemodel.AppModuleBasic{}) - return ctx, keeper.NewKeeper(key, tKey, encodingConfig.Codec, "") + return ctx, keeper.NewKeeper( + runtime.NewKVStoreService(key), + runtime.NewTransientStoreService(tKey), + encodingConfig.Codec, "", + ) } func TestTrackGas(t *testing.T) { @@ -40,10 +45,10 @@ func TestTrackGas(t *testing.T) { assert.EqualValues(t, 0, keeper.TrackedGas(ctx)) - keeper.TrackGas(ctx, 10) + require.NoError(t, keeper.TrackGas(ctx, 10)) assert.EqualValues(t, 10, keeper.TrackedGas(ctx)) - keeper.TrackGas(ctx, 5) + require.NoError(t, keeper.TrackGas(ctx, 5)) assert.EqualValues(t, 15, keeper.TrackedGas(ctx)) } @@ -52,7 +57,7 @@ func TestShortEMAGas(t *testing.T) { assert.EqualValues(t, 0, keeper.GetShortEMAGas(ctx)) - keeper.SetShortEMAGas(ctx, 10) + require.NoError(t, keeper.SetShortEMAGas(ctx, 10)) assert.EqualValues(t, 10, keeper.GetShortEMAGas(ctx)) } @@ -61,19 +66,19 @@ func TestLongEMAGas(t *testing.T) { assert.EqualValues(t, 0, keeper.GetLongEMAGas(ctx)) - keeper.SetLongEMAGas(ctx, 10) + require.NoError(t, keeper.SetLongEMAGas(ctx, 10)) assert.EqualValues(t, 10, keeper.GetLongEMAGas(ctx)) } func TestMinGasPrice(t *testing.T) { ctx, keeper := setup() - keeper.SetMinGasPrice(ctx, sdk.NewDecCoin("coin", sdkmath.NewInt(10))) + require.NoError(t, keeper.SetMinGasPrice(ctx, sdk.NewDecCoin("coin", sdkmath.NewInt(10)))) minGasPrice := keeper.GetMinGasPrice(ctx) assert.Equal(t, "10.000000000000000000", minGasPrice.Amount.String()) assert.Equal(t, "coin", minGasPrice.Denom) - keeper.SetMinGasPrice(ctx, sdk.NewDecCoin("coin", sdkmath.NewInt(20))) + require.NoError(t, keeper.SetMinGasPrice(ctx, sdk.NewDecCoin("coin", sdkmath.NewInt(20)))) minGasPrice = keeper.GetMinGasPrice(ctx) assert.EqualValues(t, "20.000000000000000000", minGasPrice.Amount.String()) assert.Equal(t, "coin", minGasPrice.Denom) @@ -84,7 +89,8 @@ func TestParams(t *testing.T) { defParams := types.DefaultParams() require.NoError(t, keeper.SetParams(ctx, defParams)) - params := keeper.GetParams(ctx) + params, err := keeper.GetParams(ctx) + require.NoError(t, err) assert.Equal(t, defParams.Model.InitialGasPrice.String(), params.Model.InitialGasPrice.String()) assert.Equal(t, defParams.Model.MaxGasPriceMultiplier.String(), params.Model.MaxGasPriceMultiplier.String()) @@ -286,9 +292,12 @@ func TestEstimateGasPriceInFuture(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - keeper.SetMinGasPrice(ctx, sdk.NewDecCoinFromDec("coin", sdkmath.LegacyMustNewDecFromStr("0.0625"))) - keeper.SetShortEMAGas(ctx, tc.shortEMA) - keeper.SetLongEMAGas(ctx, tc.longEMA) + require.NoError(t, keeper.SetMinGasPrice( + ctx, + sdk.NewDecCoinFromDec("coin", sdkmath.LegacyMustNewDecFromStr("0.0625")), + )) + require.NoError(t, keeper.SetShortEMAGas(ctx, tc.shortEMA)) + require.NoError(t, keeper.SetLongEMAGas(ctx, tc.longEMA)) low, high, err := keeper.CalculateEdgeGasPriceAfterBlocks(ctx, tc.afterBlocks) require.NoError(t, err) tc.assertions(t, low, high) diff --git a/x/feemodel/module.go b/x/feemodel/module.go index bd121dfe8..c24591792 100644 --- a/x/feemodel/module.go +++ b/x/feemodel/module.go @@ -39,13 +39,13 @@ var ( type Keeper interface { TrackedGas(ctx sdk.Context) int64 SetParams(ctx sdk.Context, params types.Params) error - GetParams(ctx sdk.Context) types.Params + GetParams(ctx sdk.Context) (types.Params, error) GetShortEMAGas(ctx sdk.Context) int64 - SetShortEMAGas(ctx sdk.Context, emaGas int64) + SetShortEMAGas(ctx sdk.Context, emaGas int64) error GetLongEMAGas(ctx sdk.Context) int64 - SetLongEMAGas(ctx sdk.Context, emaGas int64) + SetLongEMAGas(ctx sdk.Context, emaGas int64) error GetMinGasPrice(ctx sdk.Context) sdk.DecCoin - SetMinGasPrice(ctx sdk.Context, minGasPrice sdk.DecCoin) + SetMinGasPrice(ctx sdk.Context, minGasPrice sdk.DecCoin) error CalculateEdgeGasPriceAfterBlocks(ctx sdk.Context, after uint32) (sdk.DecCoin, sdk.DecCoin, error) UpdateParams(ctx sdk.Context, authority string, params types.Params) error } @@ -144,14 +144,20 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json. if err := am.keeper.SetParams(ctx, genesis.Params); err != nil { panic(err) } - am.keeper.SetMinGasPrice(ctx, genesis.MinGasPrice) + if err := am.keeper.SetMinGasPrice(ctx, genesis.MinGasPrice); err != nil { + panic(err) + } } // ExportGenesis returns the exported genesis state as raw bytes for the fee // module. func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + params, err := am.keeper.GetParams(ctx) + if err != nil { + panic(err) + } return cdc.MustMarshalJSON(&types.GenesisState{ - Params: am.keeper.GetParams(ctx), + Params: params, MinGasPrice: am.keeper.GetMinGasPrice(ctx), }) } @@ -170,7 +176,10 @@ func (AppModule) ConsensusVersion() uint64 { return 2 } func (am AppModule) EndBlock(c context.Context) error { ctx := sdk.UnwrapSDKContext(c) currentGasUsage := am.keeper.TrackedGas(ctx) - params := am.keeper.GetParams(ctx) + params, err := am.keeper.GetParams(ctx) + if err != nil { + return err + } model := types.NewModel(params.Model) previousMinGasPrice := am.keeper.GetMinGasPrice(ctx) @@ -181,9 +190,18 @@ func (am AppModule) EndBlock(c context.Context) error { newMinGasPrice := model.CalculateNextGasPrice(newShortEMA, newLongEMA) - am.keeper.SetShortEMAGas(ctx, newShortEMA) - am.keeper.SetLongEMAGas(ctx, newLongEMA) - am.keeper.SetMinGasPrice(ctx, sdk.NewDecCoinFromDec(previousMinGasPrice.Denom, newMinGasPrice)) + if err := am.keeper.SetShortEMAGas(ctx, newShortEMA); err != nil { + return err + } + if err := am.keeper.SetLongEMAGas(ctx, newLongEMA); err != nil { + return err + } + if err := am.keeper.SetMinGasPrice( + ctx, + sdk.NewDecCoinFromDec(previousMinGasPrice.Denom, newMinGasPrice), + ); err != nil { + return err + } metrics.SetGauge([]string{"min_gas_price"}, float32(newMinGasPrice.MustFloat64())) return nil diff --git a/x/feemodel/module_test.go b/x/feemodel/module_test.go index 6b381439a..10ca4d8b2 100644 --- a/x/feemodel/module_test.go +++ b/x/feemodel/module_test.go @@ -33,28 +33,33 @@ func (k *keeperMock) SetParams(ctx sdk.Context, params types.Params) error { return nil } -func (k *keeperMock) GetParams(ctx sdk.Context) types.Params { - return k.state.Params +func (k *keeperMock) GetParams(ctx sdk.Context) (types.Params, error) { + return k.state.Params, nil } func (k *keeperMock) GetShortEMAGas(ctx sdk.Context) int64 { return 0 } -func (k *keeperMock) SetShortEMAGas(ctx sdk.Context, emaGas int64) {} +func (k *keeperMock) SetShortEMAGas(ctx sdk.Context, emaGas int64) error { + return nil +} func (k *keeperMock) GetLongEMAGas(ctx sdk.Context) int64 { return 0 } -func (k *keeperMock) SetLongEMAGas(ctx sdk.Context, emaGas int64) {} +func (k *keeperMock) SetLongEMAGas(ctx sdk.Context, emaGas int64) error { + return nil +} func (k *keeperMock) GetMinGasPrice(ctx sdk.Context) sdk.DecCoin { return k.state.MinGasPrice } -func (k *keeperMock) SetMinGasPrice(ctx sdk.Context, minGasPrice sdk.DecCoin) { +func (k *keeperMock) SetMinGasPrice(ctx sdk.Context, minGasPrice sdk.DecCoin) error { k.state.MinGasPrice = minGasPrice + return nil } func (k *keeperMock) CalculateEdgeGasPriceAfterBlocks(ctx sdk.Context, after uint32) (sdk.DecCoin, sdk.DecCoin, error) { @@ -103,7 +108,8 @@ func TestInitGenesis(t *testing.T) { module.InitGenesis(sdk.Context{}, cdc, cdc.MustMarshalJSON(&genesisState)) - params := keeper.GetParams(sdk.Context{}) + params, err := keeper.GetParams(sdk.Context{}) + require.NoError(t, err) minGasPrice := keeper.GetMinGasPrice(sdk.Context{}) assert.Equal(t, genesisState.Params.Model.InitialGasPrice.String(), params.Model.InitialGasPrice.String()) assert.Equal(t, genesisState.Params.Model.MaxGasPriceMultiplier.String(), params.Model.MaxGasPriceMultiplier.String()) diff --git a/x/wbank/keeper/keeper.go b/x/wbank/keeper/keeper.go index e3634f53f..d7335a637 100644 --- a/x/wbank/keeper/keeper.go +++ b/x/wbank/keeper/keeper.go @@ -3,7 +3,7 @@ package keeper import ( "context" - "cosmossdk.io/core/store" + sdkstore "cosmossdk.io/core/store" sdkerrors "cosmossdk.io/errors" "cosmossdk.io/log" sdkmath "cosmossdk.io/math" @@ -30,7 +30,7 @@ type BaseKeeperWrapper struct { // NewKeeper returns a new BaseKeeperWrapper instance. func NewKeeper( cdc codec.BinaryCodec, - storeService store.KVStoreService, + storeService sdkstore.KVStoreService, ak banktypes.AccountKeeper, wasmKeeper cwasmtypes.WasmKeeper, blockedAddrs map[string]bool, @@ -197,7 +197,10 @@ func (k BaseKeeperWrapper) SpendableBalances( balances := balancesRes.Balances for i := range balances { bankLockedCoin := sdk.NewCoin(balances[i].Denom, bankLockedCoins.AmountOf(balances[i].Denom)) - balances[i] = k.getSpendableCoin(sdk.UnwrapSDKContext(ctx), addr, balances[i], bankLockedCoin) + balances[i], err = k.getSpendableCoin(sdk.UnwrapSDKContext(ctx), addr, balances[i], bankLockedCoin) + if err != nil { + return nil, err + } } return &banktypes.QuerySpendableBalancesResponse{ @@ -230,9 +233,13 @@ func (k BaseKeeperWrapper) SpendableBalanceByDenom( bankLockedCoins := k.BaseKeeper.LockedCoins(ctx, addr) bankLockedCoin := sdk.NewCoin(req.Denom, bankLockedCoins.AmountOf(req.Denom)) + spendableCoin, err := k.getSpendableCoin(sdk.UnwrapSDKContext(ctx), addr, *balanceRes.Balance, bankLockedCoin) + if err != nil { + return nil, err + } return &banktypes.QuerySpendableBalanceByDenomResponse{ - Balance: lo.ToPtr(k.getSpendableCoin(sdk.UnwrapSDKContext(ctx), addr, *balanceRes.Balance, bankLockedCoin)), + Balance: lo.ToPtr(spendableCoin), }, nil } @@ -240,20 +247,24 @@ func (k BaseKeeperWrapper) getSpendableCoin( ctx sdk.Context, addr sdk.AccAddress, balance, bankLocked sdk.Coin, -) sdk.Coin { +) (sdk.Coin, error) { denom := balance.Denom notLockedAmt := balance.Amount. Sub(bankLocked.Amount). Sub(k.ftProvider.GetDEXLockedBalance(ctx, addr, denom).Amount) - notFrozenAmt := balance.Amount.Sub(k.ftProvider.GetFrozenBalance(ctx, addr, denom).Amount) + frozenBalance, err := k.ftProvider.GetFrozenBalance(ctx, addr, denom) + if err != nil { + return sdk.Coin{}, err + } + notFrozenAmt := balance.Amount.Sub(frozenBalance.Amount) spendableAmount := sdkmath.MinInt(notLockedAmt, notFrozenAmt) if !spendableAmount.IsPositive() { - return sdk.NewCoin(denom, sdkmath.ZeroInt()) + return sdk.NewCoin(denom, sdkmath.ZeroInt()), nil } - return sdk.NewCoin(denom, spendableAmount) + return sdk.NewCoin(denom, spendableAmount), nil } func (k BaseKeeperWrapper) isSmartContract(ctx sdk.Context, addr sdk.AccAddress) bool { diff --git a/x/wbank/types/expected_keepers.go b/x/wbank/types/expected_keepers.go index 5718bbcad..8bdf34708 100644 --- a/x/wbank/types/expected_keepers.go +++ b/x/wbank/types/expected_keepers.go @@ -9,6 +9,6 @@ import ( type FungibleTokenProvider interface { BeforeSendCoins(ctx sdk.Context, fromAddress, toAddress sdk.AccAddress, coins sdk.Coins) error BeforeInputOutputCoins(ctx sdk.Context, input banktypes.Input, outputs []banktypes.Output) error - GetFrozenBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + GetFrozenBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) (sdk.Coin, error) GetDEXLockedBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin } diff --git a/x/wstaking/keeper/msg_server.go b/x/wstaking/keeper/msg_server.go index 26563fc9c..29825f494 100644 --- a/x/wstaking/keeper/msg_server.go +++ b/x/wstaking/keeper/msg_server.go @@ -32,7 +32,11 @@ func (s MsgServer) CreateValidator( ) (*stakingtypes.MsgCreateValidatorResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - expectedMinSelfDelegation := s.customParamsKeeper.GetStakingParams(ctx).MinSelfDelegation + params, err := s.customParamsKeeper.GetStakingParams(ctx) + if err != nil { + return nil, err + } + expectedMinSelfDelegation := params.MinSelfDelegation if expectedMinSelfDelegation.GT(msg.MinSelfDelegation) { return nil, sdkerrors.Wrapf( stakingtypes.ErrSelfDelegationBelowMinimum, diff --git a/x/wstaking/types/expected_keepers.go b/x/wstaking/types/expected_keepers.go index 3043466b2..ab8970765 100644 --- a/x/wstaking/types/expected_keepers.go +++ b/x/wstaking/types/expected_keepers.go @@ -8,5 +8,5 @@ import ( // CustomParamsKeeper defines the custom params keeper interface required for the module. type CustomParamsKeeper interface { - GetStakingParams(ctx sdk.Context) customparamstypes.StakingParams + GetStakingParams(ctx sdk.Context) (customparamstypes.StakingParams, error) }