diff --git a/modules/apps/27-interchain-accounts/controller/ibc_middleware.go b/modules/apps/27-interchain-accounts/controller/ibc_middleware.go index e90ebbb723e..4c1c112615a 100644 --- a/modules/apps/27-interchain-accounts/controller/ibc_middleware.go +++ b/modules/apps/27-interchain-accounts/controller/ibc_middleware.go @@ -174,7 +174,7 @@ func (im IBCMiddleware) OnChanCloseConfirm( } // OnRecvPacket implements the IBCMiddleware interface -func (IBCMiddleware) OnRecvPacket( +func (im IBCMiddleware) OnRecvPacket( ctx context.Context, _ string, packet channeltypes.Packet, @@ -182,7 +182,7 @@ func (IBCMiddleware) OnRecvPacket( ) ibcexported.Acknowledgement { err := errorsmod.Wrapf(icatypes.ErrInvalidChannelFlow, "cannot receive packet on controller chain") ack := channeltypes.NewErrorAcknowledgement(err) - keeper.EmitAcknowledgementEvent(ctx, packet, ack, err) + keeper.EmitAcknowledgementEvent(ctx, packet, ack, err, im.keeper) return ack } diff --git a/modules/apps/27-interchain-accounts/controller/keeper/account.go b/modules/apps/27-interchain-accounts/controller/keeper/account.go index b0d77bf4640..b93ca05e791 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/account.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/account.go @@ -84,8 +84,8 @@ func (k Keeper) registerInterchainAccount(ctx context.Context, connectionID, por return "", err } - events := sdkCtx.EventManager().Events() - k.Logger(ctx).Debug("emitting interchain account registration events", logging.SdkEventsToLogArguments(events)) + k.EventService.EventManager(ctx).Events() + k.Logger.Debug("emitting interchain account registration events", logging.SdkEventsToLogArguments(events)) // NOTE: The sdk msg handler creates a new EventManager, so events must be correctly propagated back to the current context sdkCtx.EventManager().EmitEvents(events) diff --git a/modules/apps/27-interchain-accounts/controller/keeper/events.go b/modules/apps/27-interchain-accounts/controller/keeper/events.go index 468a1028a5c..d583827b3cd 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/events.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/events.go @@ -2,8 +2,9 @@ package keeper import ( "context" - "strconv" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" sdk "github.com/cosmos/cosmos-sdk/types" icatypes "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/types" @@ -13,22 +14,20 @@ import ( // EmitAcknowledgementEvent emits an event signalling a successful or failed acknowledgement and including the error // details if any. -func EmitAcknowledgementEvent(ctx context.Context, packet channeltypes.Packet, ack exported.Acknowledgement, err error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - attributes := []sdk.Attribute{ - sdk.NewAttribute(sdk.AttributeKeyModule, icatypes.ModuleName), - sdk.NewAttribute(icatypes.AttributeKeyControllerChannelID, packet.GetDestChannel()), - sdk.NewAttribute(icatypes.AttributeKeyAckSuccess, strconv.FormatBool(ack.Success())), +func EmitAcknowledgementEvent(ctx context.Context, packet channeltypes.Packet, ack exported.Acknowledgement, err error, env appmodule.Environment) { + + attributes := []event.Attribute{ + {sdk.AttributeKeyModule, icatypes.ModuleName}, + {icatypes.AttributeKeyControllerChannelID, packet.GetDestChannel()}, + {icatypes.AttributeKeyControllerChannelID, packet.GetDestChannel()}, } if err != nil { - attributes = append(attributes, sdk.NewAttribute(icatypes.AttributeKeyAckError, err.Error())) + attributes = append(attributes, event.Attribute{icatypes.AttributeKeyAckError, err.Error()}) } - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - icatypes.EventTypePacket, - attributes..., - ), + env.EventService.EventManager(ctx).EmitKV( + icatypes.EventTypePacket, + attributes..., ) } diff --git a/modules/apps/27-interchain-accounts/controller/keeper/grpc_query.go b/modules/apps/27-interchain-accounts/controller/keeper/grpc_query.go index 4d8e14c6d76..e23cfa30584 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/grpc_query.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/grpc_query.go @@ -6,8 +6,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/controller/types" icatypes "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/types" ) @@ -15,13 +13,11 @@ import ( var _ types.QueryServer = (*Keeper)(nil) // InterchainAccount implements the Query/InterchainAccount gRPC method -func (k Keeper) InterchainAccount(goCtx context.Context, req *types.QueryInterchainAccountRequest) (*types.QueryInterchainAccountResponse, error) { +func (k Keeper) InterchainAccount(ctx context.Context, req *types.QueryInterchainAccountRequest) (*types.QueryInterchainAccountResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx) - portID, err := icatypes.NewControllerPortID(req.Owner) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "failed to generate portID from owner address: %s", err) @@ -38,8 +34,7 @@ func (k Keeper) InterchainAccount(goCtx context.Context, req *types.QueryInterch } // Params implements the Query/Params gRPC method -func (k Keeper) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) +func (k Keeper) Params(ctx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { params := k.GetParams(ctx) return &types.QueryParamsResponse{ diff --git a/modules/apps/27-interchain-accounts/controller/keeper/keeper.go b/modules/apps/27-interchain-accounts/controller/keeper/keeper.go index af5ddae50d0..28453af6c14 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/keeper.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/keeper.go @@ -4,17 +4,14 @@ import ( "bytes" "context" "errors" - "fmt" "strings" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/controller/types" @@ -30,7 +27,7 @@ import ( // Keeper defines the IBC interchain accounts controller keeper type Keeper struct { - storeService corestore.KVStoreService + appmodule.Environment cdc codec.Codec legacySubspace icatypes.ParamSubspace ics4Wrapper porttypes.ICS4Wrapper @@ -48,7 +45,7 @@ type Keeper struct { // NewKeeper creates a new interchain accounts controller Keeper instance func NewKeeper( - cdc codec.Codec, storeService corestore.KVStoreService, legacySubspace icatypes.ParamSubspace, + cdc codec.Codec, env appmodule.Environment, legacySubspace icatypes.ParamSubspace, ics4Wrapper porttypes.ICS4Wrapper, channelKeeper icatypes.ChannelKeeper, portKeeper icatypes.PortKeeper, scopedKeeper exported.ScopedKeeper, msgRouter icatypes.MessageRouter, authority string, ) Keeper { @@ -57,7 +54,7 @@ func NewKeeper( } return Keeper{ - storeService: storeService, + Environment: env, cdc: cdc, legacySubspace: legacySubspace, ics4Wrapper: ics4Wrapper, @@ -81,12 +78,6 @@ func (k Keeper) GetICS4Wrapper() porttypes.ICS4Wrapper { return k.ics4Wrapper } -// Logger returns the application logger, scoped to the associated module -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return sdkCtx.Logger().With("module", fmt.Sprintf("x/%s-%s", exported.ModuleName, icatypes.ModuleName)) -} - // GetConnectionID returns the connection id for the given port and channelIDs. func (k Keeper) GetConnectionID(ctx context.Context, portID, channelID string) (string, error) { channel, found := k.channelKeeper.GetChannel(ctx, portID, channelID) @@ -98,9 +89,9 @@ func (k Keeper) GetConnectionID(ctx context.Context, portID, channelID string) ( // GetAllPorts returns all ports to which the interchain accounts controller module is bound. Used in ExportGenesis func (k Keeper) GetAllPorts(ctx context.Context) []string { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(icatypes.PortKeyPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var ports []string for ; iterator.Valid(); iterator.Next() { @@ -114,7 +105,7 @@ func (k Keeper) GetAllPorts(ctx context.Context) []string { // setPort sets the provided portID in state func (k Keeper) setPort(ctx context.Context, portID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyPort(portID), []byte{0x01}); err != nil { panic(err) } @@ -143,7 +134,7 @@ func (k Keeper) GetAppVersion(ctx context.Context, portID, channelID string) (st // GetActiveChannelID retrieves the active channelID from the store, keyed by the provided connectionID and portID func (k Keeper) GetActiveChannelID(ctx context.Context, connectionID, portID string) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := icatypes.KeyActiveChannel(portID, connectionID) bz, err := store.Get(key) @@ -186,9 +177,9 @@ func (k Keeper) IsActiveChannelClosed(ctx context.Context, connectionID, portID // GetAllActiveChannels returns a list of all active interchain accounts controller channels and their associated connection and port identifiers func (k Keeper) GetAllActiveChannels(ctx context.Context) []genesistypes.ActiveChannel { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(icatypes.ActiveChannelKeyPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var activeChannels []genesistypes.ActiveChannel for ; iterator.Valid(); iterator.Next() { @@ -213,7 +204,7 @@ func (k Keeper) GetAllActiveChannels(ctx context.Context) []genesistypes.ActiveC // SetActiveChannelID stores the active channelID, keyed by the provided connectionID and portID func (k Keeper) SetActiveChannelID(ctx context.Context, connectionID, portID, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyActiveChannel(portID, connectionID), []byte(channelID)); err != nil { panic(err) } @@ -227,7 +218,7 @@ func (k Keeper) IsActiveChannel(ctx context.Context, connectionID, portID string // GetInterchainAccountAddress retrieves the InterchainAccount address from the store associated with the provided connectionID and portID func (k Keeper) GetInterchainAccountAddress(ctx context.Context, connectionID, portID string) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := icatypes.KeyOwnerAccount(portID, connectionID) bz, err := store.Get(key) @@ -243,7 +234,7 @@ func (k Keeper) GetInterchainAccountAddress(ctx context.Context, connectionID, p // GetAllInterchainAccounts returns a list of all registered interchain account addresses and their associated connection and controller port identifiers func (k Keeper) GetAllInterchainAccounts(ctx context.Context) []genesistypes.RegisteredInterchainAccount { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(icatypes.OwnerKeyPrefix)) var interchainAccounts []genesistypes.RegisteredInterchainAccount @@ -264,7 +255,7 @@ func (k Keeper) GetAllInterchainAccounts(ctx context.Context) []genesistypes.Reg // SetInterchainAccountAddress stores the InterchainAccount address, keyed by the associated connectionID and portID func (k Keeper) SetInterchainAccountAddress(ctx context.Context, connectionID, portID, address string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyOwnerAccount(portID, connectionID), []byte(address)); err != nil { panic(err) } @@ -272,7 +263,7 @@ func (k Keeper) SetInterchainAccountAddress(ctx context.Context, connectionID, p // IsMiddlewareEnabled returns true if the underlying application callbacks are enabled for given port and connection identifier pair, otherwise false func (k Keeper) IsMiddlewareEnabled(ctx context.Context, portID, connectionID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(icatypes.KeyIsMiddlewareEnabled(portID, connectionID)) if err != nil { panic(err) @@ -282,7 +273,7 @@ func (k Keeper) IsMiddlewareEnabled(ctx context.Context, portID, connectionID st // IsMiddlewareDisabled returns true if the underlying application callbacks are disabled for the given port and connection identifier pair, otherwise false func (k Keeper) IsMiddlewareDisabled(ctx context.Context, portID, connectionID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(icatypes.KeyIsMiddlewareEnabled(portID, connectionID)) if err != nil { panic(err) @@ -292,7 +283,7 @@ func (k Keeper) IsMiddlewareDisabled(ctx context.Context, portID, connectionID s // SetMiddlewareEnabled stores a flag to indicate that the underlying application callbacks should be enabled for the given port and connection identifier pair func (k Keeper) SetMiddlewareEnabled(ctx context.Context, portID, connectionID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyIsMiddlewareEnabled(portID, connectionID), icatypes.MiddlewareEnabled); err != nil { panic(err) } @@ -300,7 +291,7 @@ func (k Keeper) SetMiddlewareEnabled(ctx context.Context, portID, connectionID s // SetMiddlewareDisabled stores a flag to indicate that the underlying application callbacks should be disabled for the given port and connection identifier pair func (k Keeper) SetMiddlewareDisabled(ctx context.Context, portID, connectionID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyIsMiddlewareEnabled(portID, connectionID), icatypes.MiddlewareDisabled); err != nil { panic(err) } @@ -308,7 +299,7 @@ func (k Keeper) SetMiddlewareDisabled(ctx context.Context, portID, connectionID // DeleteMiddlewareEnabled deletes the middleware enabled flag stored in state func (k Keeper) DeleteMiddlewareEnabled(ctx context.Context, portID, connectionID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(icatypes.KeyIsMiddlewareEnabled(portID, connectionID)); err != nil { panic(err) } @@ -331,7 +322,7 @@ func (k Keeper) getAppMetadata(ctx context.Context, portID, channelID string) (i // GetParams returns the current ica/controller submodule parameters. func (k Keeper) GetParams(ctx context.Context) types.Params { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.ParamsKey)) if err != nil { panic(err) @@ -347,7 +338,7 @@ func (k Keeper) GetParams(ctx context.Context) types.Params { // SetParams sets the ica/controller submodule parameters. func (k Keeper) SetParams(ctx context.Context, params types.Params) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) if err := store.Set([]byte(types.ParamsKey), bz); err != nil { panic(err) diff --git a/modules/apps/27-interchain-accounts/controller/keeper/migrations.go b/modules/apps/27-interchain-accounts/controller/keeper/migrations.go index bd43a02c420..8a4b28ec449 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/migrations.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/migrations.go @@ -29,7 +29,7 @@ func (m Migrator) MigrateParams(ctx context.Context) error { m.keeper.legacySubspace.GetParamSetIfExists(sdkCtx, ¶ms) } m.keeper.SetParams(ctx, params) - m.keeper.Logger(ctx).Info("successfully migrated ica/controller submodule to self-manage params") + m.keeper.Logger.Info("successfully migrated ica/controller submodule to self-manage params") } return nil } diff --git a/modules/apps/27-interchain-accounts/controller/keeper/msg_server.go b/modules/apps/27-interchain-accounts/controller/keeper/msg_server.go index ea78c2d0fde..5135d597198 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/msg_server.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/msg_server.go @@ -5,8 +5,6 @@ import ( errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/controller/types" icatypes "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/types" channeltypes "github.com/cosmos/ibc-go/v9/modules/core/04-channel/types" @@ -26,8 +24,7 @@ func NewMsgServerImpl(keeper *Keeper) types.MsgServer { } // RegisterInterchainAccount defines a rpc handler for MsgRegisterInterchainAccount -func (s msgServer) RegisterInterchainAccount(goCtx context.Context, msg *types.MsgRegisterInterchainAccount) (*types.MsgRegisterInterchainAccountResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) +func (s msgServer) RegisterInterchainAccount(ctx context.Context, msg *types.MsgRegisterInterchainAccount) (*types.MsgRegisterInterchainAccountResponse, error) { portID, err := icatypes.NewControllerPortID(msg.Owner) if err != nil { @@ -48,11 +45,11 @@ func (s msgServer) RegisterInterchainAccount(goCtx context.Context, msg *types.M channelID, err := s.registerInterchainAccount(ctx, msg.ConnectionId, portID, msg.Version, order) if err != nil { - s.Logger(ctx).Error("error registering interchain account", "error", err.Error()) + s.Logger.Error("error registering interchain account", "error", err.Error()) return nil, err } - s.Logger(ctx).Info("successfully registered interchain account", "channel-id", channelID) + s.Logger.Info("successfully registered interchain account", "channel-id", channelID) return &types.MsgRegisterInterchainAccountResponse{ ChannelId: channelID, @@ -61,8 +58,7 @@ func (s msgServer) RegisterInterchainAccount(goCtx context.Context, msg *types.M } // SendTx defines a rpc handler for MsgSendTx -func (s msgServer) SendTx(goCtx context.Context, msg *types.MsgSendTx) (*types.MsgSendTxResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) +func (s msgServer) SendTx(ctx context.Context, msg *types.MsgSendTx) (*types.MsgSendTxResponse, error) { portID, err := icatypes.NewControllerPortID(msg.Owner) if err != nil { @@ -71,7 +67,7 @@ func (s msgServer) SendTx(goCtx context.Context, msg *types.MsgSendTx) (*types.M // the absolute timeout value is calculated using the controller chain block time + the relative timeout value // this assumes time synchrony to a certain degree between the controller and counterparty host chain - absoluteTimeout := uint64(ctx.BlockTime().UnixNano()) + msg.RelativeTimeout + absoluteTimeout := uint64(s.HeaderService.HeaderInfo(ctx).Time.UnixNano()) + msg.RelativeTimeout seq, err := s.sendTx(ctx, msg.ConnectionId, portID, msg.PacketData, absoluteTimeout) if err != nil { return nil, err @@ -81,12 +77,11 @@ func (s msgServer) SendTx(goCtx context.Context, msg *types.MsgSendTx) (*types.M } // UpdateParams defines an rpc handler method for MsgUpdateParams. Updates the ica/controller submodule's parameters. -func (k Keeper) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { +func (k Keeper) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { if k.GetAuthority() != msg.Signer { return nil, errorsmod.Wrapf(ibcerrors.ErrUnauthorized, "expected %s, got %s", k.GetAuthority(), msg.Signer) } - ctx := sdk.UnwrapSDKContext(goCtx) k.SetParams(ctx, msg.Params) return &types.MsgUpdateParamsResponse{}, nil diff --git a/modules/apps/27-interchain-accounts/controller/keeper/relay.go b/modules/apps/27-interchain-accounts/controller/keeper/relay.go index d33f82c5da4..477fbdb4610 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/relay.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/relay.go @@ -5,8 +5,6 @@ import ( errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/controller/types" icatypes "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/types" @@ -38,8 +36,7 @@ func (k Keeper) sendTx(ctx context.Context, connectionID, portID string, icaPack return 0, errorsmod.Wrapf(icatypes.ErrActiveChannelNotFound, "failed to retrieve active channel on connection %s for port %s", connectionID, portID) } - sdkCtx := sdk.UnwrapSDKContext(ctx) - if uint64(sdkCtx.BlockTime().UnixNano()) >= timeoutTimestamp { + if uint64(k.HeaderService.HeaderInfo(ctx).Time.UnixNano()) >= timeoutTimestamp { return 0, icatypes.ErrInvalidTimeoutTimestamp } diff --git a/modules/apps/27-interchain-accounts/host/ibc_module.go b/modules/apps/27-interchain-accounts/host/ibc_module.go index e23b0514e59..69fab506c1d 100644 --- a/modules/apps/27-interchain-accounts/host/ibc_module.go +++ b/modules/apps/27-interchain-accounts/host/ibc_module.go @@ -116,8 +116,8 @@ func (im IBCModule) OnRecvPacket( _ sdk.AccAddress, ) ibcexported.Acknowledgement { if !im.keeper.GetParams(ctx).HostEnabled { - im.keeper.Logger(ctx).Info("host submodule is disabled") - keeper.EmitHostDisabledEvent(ctx, packet) + im.keeper.Logger.Info("host submodule is disabled") + keeper.EmitHostDisabledEvent(ctx, im.keeper.Environment, packet) return channeltypes.NewErrorAcknowledgement(types.ErrHostSubModuleDisabled) } @@ -125,13 +125,13 @@ func (im IBCModule) OnRecvPacket( ack := channeltypes.NewResultAcknowledgement(txResponse) if err != nil { ack = channeltypes.NewErrorAcknowledgement(err) - im.keeper.Logger(ctx).Error(fmt.Sprintf("%s sequence %d", err.Error(), packet.Sequence)) + im.keeper.Logger.Error(fmt.Sprintf("%s sequence %d", err.Error(), packet.Sequence)) } else { - im.keeper.Logger(ctx).Info("successfully handled packet", "sequence", packet.Sequence) + im.keeper.Logger.Info("successfully handled packet", "sequence", packet.Sequence) } // Emit an event indicating a successful or failed acknowledgement. - keeper.EmitAcknowledgementEvent(ctx, packet, ack, err) + keeper.EmitAcknowledgementEvent(ctx, im.keeper.Environment, packet, ack, err) // NOTE: acknowledgement will be written synchronously during IBC handler execution. return ack diff --git a/modules/apps/27-interchain-accounts/host/keeper/events.go b/modules/apps/27-interchain-accounts/host/keeper/events.go index fb497ec2ca3..8d3e0259a44 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/events.go +++ b/modules/apps/27-interchain-accounts/host/keeper/events.go @@ -4,6 +4,8 @@ import ( "context" "strconv" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/host/types" @@ -14,35 +16,30 @@ import ( // EmitAcknowledgementEvent emits an event signalling a successful or failed acknowledgement and including the error // details if any. -func EmitAcknowledgementEvent(ctx context.Context, packet channeltypes.Packet, ack exported.Acknowledgement, err error) { - attributes := []sdk.Attribute{ - sdk.NewAttribute(sdk.AttributeKeyModule, icatypes.ModuleName), - sdk.NewAttribute(icatypes.AttributeKeyHostChannelID, packet.GetDestChannel()), - sdk.NewAttribute(icatypes.AttributeKeyAckSuccess, strconv.FormatBool(ack.Success())), +func EmitAcknowledgementEvent(ctx context.Context, env appmodule.Environment, packet channeltypes.Packet, ack exported.Acknowledgement, err error) { + attributes := []event.Attribute{ + {Key: sdk.AttributeKeyModule, Value: icatypes.ModuleName}, + {Key: icatypes.AttributeKeyHostChannelID, Value: packet.GetDestChannel()}, + {Key: icatypes.AttributeKeyAckSuccess, Value: strconv.FormatBool(ack.Success())}, } if err != nil { - attributes = append(attributes, sdk.NewAttribute(icatypes.AttributeKeyAckError, err.Error())) + attributes = append(attributes, event.Attribute{Key: icatypes.AttributeKeyAckError, Value: err.Error()}) } - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - icatypes.EventTypePacket, - attributes..., - ), + + env.EventService.EventManager(ctx).EmitKV( + icatypes.EventTypePacket, + attributes..., ) } // EmitHostDisabledEvent emits an event signalling that the host submodule is disabled. -func EmitHostDisabledEvent(ctx context.Context, packet channeltypes.Packet) { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - icatypes.EventTypePacket, - sdk.NewAttribute(sdk.AttributeKeyModule, icatypes.ModuleName), - sdk.NewAttribute(icatypes.AttributeKeyHostChannelID, packet.GetDestChannel()), - sdk.NewAttribute(icatypes.AttributeKeyAckError, types.ErrHostSubModuleDisabled.Error()), - sdk.NewAttribute(icatypes.AttributeKeyAckSuccess, "false"), - ), +func EmitHostDisabledEvent(ctx context.Context, env appmodule.Environment, packet channeltypes.Packet) { + env.EventService.EventManager(ctx).EmitKV( + icatypes.EventTypePacket, + event.Attribute{Key: sdk.AttributeKeyModule, Value: icatypes.ModuleName}, + event.Attribute{Key: icatypes.AttributeKeyHostChannelID, Value: packet.GetDestChannel()}, + event.Attribute{Key: icatypes.AttributeKeyAckError, Value: types.ErrHostSubModuleDisabled.Error()}, + event.Attribute{Key: icatypes.AttributeKeyAckSuccess, Value: "false"}, ) } diff --git a/modules/apps/27-interchain-accounts/host/keeper/grpc_query.go b/modules/apps/27-interchain-accounts/host/keeper/grpc_query.go index c6616c455bd..138e0106db0 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/grpc_query.go +++ b/modules/apps/27-interchain-accounts/host/keeper/grpc_query.go @@ -3,16 +3,13 @@ package keeper import ( "context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/host/types" ) var _ types.QueryServer = (*Keeper)(nil) // Params implements the Query/Params gRPC method -func (k Keeper) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) +func (k Keeper) Params(ctx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { params := k.GetParams(ctx) return &types.QueryParamsResponse{ diff --git a/modules/apps/27-interchain-accounts/host/keeper/handshake.go b/modules/apps/27-interchain-accounts/host/keeper/handshake.go index 19d126218b3..59a8356ffb4 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/handshake.go +++ b/modules/apps/27-interchain-accounts/host/keeper/handshake.go @@ -40,7 +40,7 @@ func (k Keeper) OnChanOpenTry( return "", errorsmod.Wrapf(err, "failed to retrieve connection %s", connectionHops[0]) } - k.Logger(ctx).Debug("counterparty version is invalid, proposing default metadata") + k.Logger.Debug("counterparty version is invalid, proposing default metadata") metadata = icatypes.NewDefaultMetadata(connection.Counterparty.ConnectionId, connectionHops[0]) } @@ -72,7 +72,7 @@ func (k Keeper) OnChanOpenTry( interchainAccAddr, found := k.GetInterchainAccountAddress(ctx, metadata.HostConnectionId, counterparty.PortId) if found { // reopening an interchain account - k.Logger(ctx).Info("reopening existing interchain account", "address", interchainAccAddr) + k.Logger.Info("reopening existing interchain account", "address", interchainAccAddr) accAddress = sdk.MustAccAddressFromBech32(interchainAccAddr) if _, ok := k.accountKeeper.GetAccount(ctx, accAddress).(*icatypes.InterchainAccount); !ok { return "", errorsmod.Wrapf(icatypes.ErrInvalidAccountReopening, "existing account address %s, does not have interchain account type", accAddress) @@ -83,7 +83,7 @@ func (k Keeper) OnChanOpenTry( if err != nil { return "", err } - k.Logger(ctx).Info("successfully created new interchain account", "host-connection-id", metadata.HostConnectionId, "port-id", counterparty.PortId, "address", accAddress) + k.Logger.Info("successfully created new interchain account", "host-connection-id", metadata.HostConnectionId, "port-id", counterparty.PortId, "address", accAddress) } metadata.Address = accAddress.String() diff --git a/modules/apps/27-interchain-accounts/host/keeper/keeper.go b/modules/apps/27-interchain-accounts/host/keeper/keeper.go index 057e308a234..91c34ff0071 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/keeper.go +++ b/modules/apps/27-interchain-accounts/host/keeper/keeper.go @@ -13,14 +13,12 @@ import ( msgv1 "cosmossdk.io/api/cosmos/msg/v1" queryv1 "cosmossdk.io/api/cosmos/query/v1" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" genesistypes "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/genesis/types" "github.com/cosmos/ibc-go/v9/modules/apps/27-interchain-accounts/host/types" @@ -34,7 +32,7 @@ import ( // Keeper defines the IBC interchain accounts host keeper type Keeper struct { - storeService corestore.KVStoreService + appmodule.Environment cdc codec.Codec legacySubspace icatypes.ParamSubspace @@ -58,7 +56,7 @@ type Keeper struct { // NewKeeper creates a new interchain accounts host Keeper instance func NewKeeper( - cdc codec.Codec, storeService corestore.KVStoreService, legacySubspace icatypes.ParamSubspace, + cdc codec.Codec, env appmodule.Environment, legacySubspace icatypes.ParamSubspace, ics4Wrapper porttypes.ICS4Wrapper, channelKeeper icatypes.ChannelKeeper, portKeeper icatypes.PortKeeper, accountKeeper icatypes.AccountKeeper, scopedKeeper exported.ScopedKeeper, msgRouter icatypes.MessageRouter, queryRouter icatypes.QueryRouter, authority string, @@ -73,7 +71,7 @@ func NewKeeper( } return Keeper{ - storeService: storeService, + Environment: env, cdc: cdc, legacySubspace: legacySubspace, ics4Wrapper: ics4Wrapper, @@ -100,12 +98,6 @@ func (k Keeper) GetICS4Wrapper() porttypes.ICS4Wrapper { return k.ics4Wrapper } -// Logger returns the application logger, scoped to the associated module -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: remove after context.Context is removed from core IBC - return sdkCtx.Logger().With("module", fmt.Sprintf("x/%s-%s", exported.ModuleName, icatypes.ModuleName)) -} - // getConnectionID returns the connection id for the given port and channelIDs. func (k Keeper) getConnectionID(ctx context.Context, portID, channelID string) (string, error) { channel, found := k.channelKeeper.GetChannel(ctx, portID, channelID) @@ -117,7 +109,7 @@ func (k Keeper) getConnectionID(ctx context.Context, portID, channelID string) ( // setPort sets the provided portID in state. func (k Keeper) setPort(ctx context.Context, portID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyPort(portID), []byte{0x01}); err != nil { panic(err) } @@ -140,7 +132,7 @@ func (k Keeper) getAppMetadata(ctx context.Context, portID, channelID string) (i // GetActiveChannelID retrieves the active channelID from the store keyed by the provided connectionID and portID func (k Keeper) GetActiveChannelID(ctx context.Context, connectionID, portID string) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := icatypes.KeyActiveChannel(portID, connectionID) bz, err := store.Get(key) @@ -172,9 +164,9 @@ func (k Keeper) GetOpenActiveChannel(ctx context.Context, connectionID, portID s // GetAllActiveChannels returns a list of all active interchain accounts host channels and their associated connection and port identifiers func (k Keeper) GetAllActiveChannels(ctx context.Context) []genesistypes.ActiveChannel { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(icatypes.ActiveChannelKeyPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var activeChannels []genesistypes.ActiveChannel for ; iterator.Valid(); iterator.Next() { @@ -194,7 +186,7 @@ func (k Keeper) GetAllActiveChannels(ctx context.Context) []genesistypes.ActiveC // SetActiveChannelID stores the active channelID, keyed by the provided connectionID and portID func (k Keeper) SetActiveChannelID(ctx context.Context, connectionID, portID, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyActiveChannel(portID, connectionID), []byte(channelID)); err != nil { panic(err) } @@ -208,7 +200,7 @@ func (k Keeper) IsActiveChannel(ctx context.Context, connectionID, portID string // GetInterchainAccountAddress retrieves the InterchainAccount address from the store associated with the provided connectionID and portID func (k Keeper) GetInterchainAccountAddress(ctx context.Context, connectionID, portID string) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := icatypes.KeyOwnerAccount(portID, connectionID) bz, err := store.Get(key) @@ -224,7 +216,7 @@ func (k Keeper) GetInterchainAccountAddress(ctx context.Context, connectionID, p // GetAllInterchainAccounts returns a list of all registered interchain account addresses and their associated connection and controller port identifiers func (k Keeper) GetAllInterchainAccounts(ctx context.Context) []genesistypes.RegisteredInterchainAccount { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(icatypes.OwnerKeyPrefix)) var interchainAccounts []genesistypes.RegisteredInterchainAccount @@ -245,7 +237,7 @@ func (k Keeper) GetAllInterchainAccounts(ctx context.Context) []genesistypes.Reg // SetInterchainAccountAddress stores the InterchainAccount address, keyed by the associated connectionID and portID func (k Keeper) SetInterchainAccountAddress(ctx context.Context, connectionID, portID, address string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(icatypes.KeyOwnerAccount(portID, connectionID), []byte(address)); err != nil { panic(err) } @@ -258,7 +250,7 @@ func (k Keeper) GetAuthority() string { // GetParams returns the total set of the host submodule parameters. func (k Keeper) GetParams(ctx context.Context) types.Params { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.ParamsKey)) if err != nil { panic(err) @@ -274,7 +266,7 @@ func (k Keeper) GetParams(ctx context.Context) types.Params { // SetParams sets the total set of the host submodule parameters. func (k Keeper) SetParams(ctx context.Context, params types.Params) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) if err := store.Set([]byte(types.ParamsKey), bz); err != nil { panic(err) diff --git a/modules/apps/27-interchain-accounts/host/keeper/migrations.go b/modules/apps/27-interchain-accounts/host/keeper/migrations.go index ea0fb9374f5..dbf453e1ef6 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/migrations.go +++ b/modules/apps/27-interchain-accounts/host/keeper/migrations.go @@ -32,7 +32,7 @@ func (m Migrator) MigrateParams(ctx context.Context) error { return err } m.keeper.SetParams(ctx, params) - m.keeper.Logger(ctx).Info("successfully migrated ica/host submodule to self-manage params") + m.keeper.Logger.Info("successfully migrated ica/host submodule to self-manage params") } return nil } diff --git a/modules/apps/27-interchain-accounts/host/keeper/msg_server.go b/modules/apps/27-interchain-accounts/host/keeper/msg_server.go index 90c0159ffe7..5eee722a9ef 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/msg_server.go +++ b/modules/apps/27-interchain-accounts/host/keeper/msg_server.go @@ -2,6 +2,7 @@ package keeper import ( "context" + "fmt" "slices" errorsmod "cosmossdk.io/errors" @@ -29,7 +30,6 @@ func NewMsgServerImpl(keeper *Keeper) types.MsgServer { // ModuleQuerySafe routes the queries to the keeper's query router if they are module_query_safe. // This handler doesn't use the signer. func (m msgServer) ModuleQuerySafe(goCtx context.Context, msg *types.MsgModuleQuerySafe) (*types.MsgModuleQuerySafeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) responses := make([][]byte, len(msg.Requests)) for i, query := range msg.Requests { @@ -43,31 +43,38 @@ func (m msgServer) ModuleQuerySafe(goCtx context.Context, msg *types.MsgModuleQu return nil, errorsmod.Wrapf(ibcerrors.ErrInvalidRequest, "no route to query: %s", query.Path) } - res, err := route(ctx, &abci.QueryRequest{ + ctx := sdk.UnwrapSDKContext(goCtx) + res, err := m.QueryRouterService.Invoke(ctx, &abci.QueryRequest{ Path: query.Path, Data: query.Data, }) if err != nil { - m.Logger(ctx).Debug("query failed", "path", query.Path, "error", err) + m.Logger.Debug("query failed", "path", query.Path, "error", err) return nil, err } - if res == nil || res.Value == nil { + + resp, ok := res.(*abci.QueryResponse) + if !ok { + return nil, fmt.Errorf("unexpected response type: %T", resp) + } + + if resp == nil || resp.Value == nil { return nil, errorsmod.Wrapf(ibcerrors.ErrInvalidRequest, "no response for query: %s", query.Path) } - responses[i] = res.Value + responses[i] = resp.Value } + height := m.HeaderService.HeaderInfo(goCtx).Height - return &types.MsgModuleQuerySafeResponse{Responses: responses, Height: uint64(ctx.BlockHeight())}, nil + return &types.MsgModuleQuerySafeResponse{Responses: responses, Height: uint64(height)}, nil } // UpdateParams updates the host submodule's params. -func (m msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { +func (m msgServer) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { if m.GetAuthority() != msg.Signer { return nil, errorsmod.Wrapf(ibcerrors.ErrUnauthorized, "expected %s, got %s", m.GetAuthority(), msg.Signer) } - ctx := sdk.UnwrapSDKContext(goCtx) m.SetParams(ctx, msg.Params) return &types.MsgUpdateParamsResponse{}, nil diff --git a/modules/apps/27-interchain-accounts/host/keeper/relay.go b/modules/apps/27-interchain-accounts/host/keeper/relay.go index 42e685738c8..9b7c34e6038 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/relay.go +++ b/modules/apps/27-interchain-accounts/host/keeper/relay.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/gogoproto/proto" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -68,24 +69,24 @@ func (k Keeper) executeTx(ctx context.Context, sourcePort, destPort, destChannel // CacheContext returns a new context with the multi-store branched into a cached storage object // writeCache is called only if all msgs succeed, performing state transitions atomically - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - cacheCtx, writeCache := sdkCtx.CacheContext() - for i, msg := range msgs { - if m, ok := msg.(sdk.HasValidateBasic); ok { - if err := m.ValidateBasic(); err != nil { - return nil, err - } - } + k.BranchService.Execute(ctx, func(ctx context.Context) error { - protoAny, err := k.executeMsg(cacheCtx, msg) - if err != nil { - return nil, err - } + for i, msg := range msgs { + if m, ok := msg.(sdk.HasValidateBasic); ok { + if err := m.ValidateBasic(); err != nil { + return err + } + } - txMsgData.MsgResponses[i] = protoAny - } + protoAny, err := k.executeMsg(ctx, k.Environment, msg) + if err != nil { + return err + } - writeCache() + txMsgData.MsgResponses[i] = protoAny + } + return nil + }) txResponse, err := proto.Marshal(txMsgData) if err != nil { @@ -131,19 +132,19 @@ func (k Keeper) authenticateTx(ctx context.Context, msgs []sdk.Msg, connectionID // Attempts to get the message handler from the router and if found will then execute the message. // If the message execution is successful, the proto marshaled message response will be returned. -func (k Keeper) executeMsg(ctx sdk.Context, msg sdk.Msg) (*codectypes.Any, error) { // TODO: https://github.com/cosmos/ibc-go/issues/7223 - handler := k.msgRouter.Handler(msg) +func (k Keeper) executeMsg(ctx context.Context, env appmodule.Environment, msg sdk.Msg) (*codectypes.Any, error) { // TODO: https://github.com/cosmos/ibc-go/issues/7223 + handler := env.MsgRouterService.CanInvoke(ctx, msg) if handler == nil { return nil, icatypes.ErrInvalidRoute } - res, err := handler(ctx, msg) + res, err := env.MsgRouterService.Invoke(ctx, msg) if err != nil { return nil, err } // NOTE: The sdk msg handler creates a new EventManager, so events must be correctly propagated back to the current context - ctx.EventManager().EmitEvents(res.GetEvents()) + env.EventService.EventManager(ctx).EmitKV(res.GetEvents()) //TODO // Each individual sdk.Result has exactly one Msg response. We aggregate here. msgResponse := res.MsgResponses[0] diff --git a/modules/apps/27-interchain-accounts/types/account.go b/modules/apps/27-interchain-accounts/types/account.go index d1542f52ace..8c10a80c34d 100644 --- a/modules/apps/27-interchain-accounts/types/account.go +++ b/modules/apps/27-interchain-accounts/types/account.go @@ -8,6 +8,7 @@ import ( yaml "gopkg.in/yaml.v2" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" crypto "github.com/cosmos/cosmos-sdk/crypto/types" @@ -44,14 +45,13 @@ type interchainAccountPretty struct { // GenerateAddress returns an sdk.AccAddress derived using a host module account address, host connection ID, the controller portID, // the current block app hash, and the current block data hash. The sdk.AccAddress returned is a sub-address of the host module account. -func GenerateAddress(ctx context.Context, connectionID, portID string) sdk.AccAddress { +func GenerateAddress(ctx context.Context, env appmodule.Environment, connectionID, portID string) sdk.AccAddress { hostModuleAcc := sdkaddress.Module(ModuleName, []byte(hostAccountsKey)) - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - header := sdkCtx.BlockHeader() + hi := env.HeaderService.HeaderInfo(ctx) buf := []byte(connectionID + portID) - buf = append(buf, header.AppHash...) - buf = append(buf, header.DataHash...) + buf = append(buf, hi.AppHash...) + buf = append(buf, hi.Hash...) return sdkaddress.Derive(hostModuleAcc, buf) } diff --git a/modules/apps/29-fee/keeper/escrow.go b/modules/apps/29-fee/keeper/escrow.go index 36571450fb0..51d7c467b86 100644 --- a/modules/apps/29-fee/keeper/escrow.go +++ b/modules/apps/29-fee/keeper/escrow.go @@ -41,7 +41,7 @@ func (k Keeper) escrowPacketFee(ctx context.Context, packetID channeltypes.Packe packetFees := types.NewPacketFees(fees) k.SetFeesInEscrow(ctx, packetID, packetFees) - emitIncentivizedPacketEvent(ctx, packetID, packetFees) + emitIncentivizedPacketEvent(ctx, k.Environment, packetID, packetFees) return nil } @@ -50,35 +50,32 @@ func (k Keeper) escrowPacketFee(ctx context.Context, packetID channeltypes.Packe func (k Keeper) DistributePacketFeesOnAcknowledgement(ctx context.Context, forwardRelayer string, reverseRelayer sdk.AccAddress, packetFees []types.PacketFee, packetID channeltypes.PacketId) { // cache context before trying to distribute fees // if the escrow account has insufficient balance then we want to avoid partially distributing fees - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - cacheCtx, writeFn := sdkCtx.CacheContext() - // forward relayer address will be empty if conversion fails forwardAddr, _ := sdk.AccAddressFromBech32(forwardRelayer) - for _, packetFee := range packetFees { - if !k.EscrowAccountHasBalance(cacheCtx, packetFee.Fee.Total()) { - // if the escrow account does not have sufficient funds then there must exist a severe bug - // the fee module should be locked until manual intervention fixes the issue - // a locked fee module will simply skip fee logic, all channels will temporarily function as - // fee disabled channels - // NOTE: we use the uncached context to lock the fee module so that the state changes from - // locking the fee module are persisted - k.lockFeeModule(ctx) - return - } - - // check if refundAcc address works - refundAddr, err := sdk.AccAddressFromBech32(packetFee.RefundAddress) - if err != nil { - panic(fmt.Errorf("could not parse refundAcc %s to sdk.AccAddress", packetFee.RefundAddress)) - } + k.BranchService.Execute(ctx, func(cacheCtx context.Context) error { + for _, packetFee := range packetFees { + if !k.EscrowAccountHasBalance(cacheCtx, packetFee.Fee.Total()) { + // if the escrow account does not have sufficient funds then there must exist a severe bug + // the fee module should be locked until manual intervention fixes the issue + // a locked fee module will simply skip fee logic, all channels will temporarily function as + // fee disabled channels + // NOTE: we use the uncached context to lock the fee module so that the state changes from + // locking the fee module are persisted + k.lockFeeModule(ctx) + return nil + } - k.distributePacketFeeOnAcknowledgement(cacheCtx, refundAddr, forwardAddr, reverseRelayer, packetFee) - } + // check if refundAcc address works + refundAddr, err := sdk.AccAddressFromBech32(packetFee.RefundAddress) + if err != nil { + return fmt.Errorf("could not parse refundAcc %s to sdk.AccAddress", packetFee.RefundAddress) + } - // write the cache - writeFn() + k.distributePacketFeeOnAcknowledgement(cacheCtx, refundAddr, forwardAddr, reverseRelayer, packetFee) + } + return nil + }) // removes the fees from the store as fees are now paid k.DeleteFeesInEscrow(ctx, packetID) @@ -108,32 +105,31 @@ func (k Keeper) distributePacketFeeOnAcknowledgement(ctx context.Context, refund func (k Keeper) DistributePacketFeesOnTimeout(ctx context.Context, timeoutRelayer sdk.AccAddress, packetFees []types.PacketFee, packetID channeltypes.PacketId) { // cache context before trying to distribute fees // if the escrow account has insufficient balance then we want to avoid partially distributing fees - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - cacheCtx, writeFn := sdkCtx.CacheContext() - - for _, packetFee := range packetFees { - if !k.EscrowAccountHasBalance(cacheCtx, packetFee.Fee.Total()) { - // if the escrow account does not have sufficient funds then there must exist a severe bug - // the fee module should be locked until manual intervention fixes the issue - // a locked fee module will simply skip fee logic, all channels will temporarily function as - // fee disabled channels - // NOTE: we use the uncached context to lock the fee module so that the state changes from - // locking the fee module are persisted - k.lockFeeModule(ctx) - return - } + k.BranchService.Execute(ctx, func(ctx context.Context) error { - // check if refundAcc address works - refundAddr, err := sdk.AccAddressFromBech32(packetFee.RefundAddress) - if err != nil { - panic(fmt.Errorf("could not parse refundAcc %s to sdk.AccAddress", packetFee.RefundAddress)) - } + for _, packetFee := range packetFees { + if !k.EscrowAccountHasBalance(ctx, packetFee.Fee.Total()) { + // if the escrow account does not have sufficient funds then there must exist a severe bug + // the fee module should be locked until manual intervention fixes the issue + // a locked fee module will simply skip fee logic, all channels will temporarily function as + // fee disabled channels + // NOTE: we use the uncached context to lock the fee module so that the state changes from + // locking the fee module are persisted + k.lockFeeModule(ctx) + return nil + } - k.distributePacketFeeOnTimeout(cacheCtx, refundAddr, timeoutRelayer, packetFee) - } + // check if refundAcc address works + refundAddr, err := sdk.AccAddressFromBech32(packetFee.RefundAddress) + if err != nil { + return fmt.Errorf("could not parse refundAcc %s to sdk.AccAddress", packetFee.RefundAddress) + } + + k.distributePacketFeeOnTimeout(ctx, refundAddr, timeoutRelayer, packetFee) + } - // write the cache - writeFn() + return nil + }) // removing the fee from the store as the fee is now paid k.DeleteFeesInEscrow(ctx, packetID) @@ -153,32 +149,32 @@ func (k Keeper) distributePacketFeeOnTimeout(ctx context.Context, refundAddr, ti // If the distribution fails for any reason (such as the receiving address being blocked), // the state changes will be discarded. func (k Keeper) distributeFee(ctx context.Context, receiver, refundAccAddress sdk.AccAddress, fee sdk.Coins) { - // cache context before trying to distribute fees - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/7223 - cacheCtx, writeFn := sdkCtx.CacheContext() - - err := k.bankKeeper.SendCoinsFromModuleToAccount(cacheCtx, types.ModuleName, receiver, fee) - if err != nil { - if bytes.Equal(receiver, refundAccAddress) { - k.Logger(ctx).Error("error distributing fee", "receiver address", receiver, "fee", fee) - return // if sending to the refund address already failed, then return (no-op) - } - // if an error is returned from x/bank and the receiver is not the refundAccAddress - // then attempt to refund the fee to the original sender - err := k.bankKeeper.SendCoinsFromModuleToAccount(cacheCtx, types.ModuleName, refundAccAddress, fee) + k.BranchService.Execute(ctx, func(ctx context.Context) error { + err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, receiver, fee) if err != nil { - k.Logger(ctx).Error("error refunding fee to the original sender", "refund address", refundAccAddress, "fee", fee) - return // if sending to the refund address fails, no-op + if bytes.Equal(receiver, refundAccAddress) { + k.Logger.Error("error distributing fee", "receiver address", receiver, "fee", fee) + return nil + } + + // if an error is returned from x/bank and the receiver is not the refundAccAddress + // then attempt to refund the fee to the original sender + err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, refundAccAddress, fee) + if err != nil { + k.Logger.Error("error refunding fee to the original sender", "refund address", refundAccAddress, "fee", fee) + return nil + } + + emitDistributeFeeEvent(ctx, k.Environment, refundAccAddress.String(), fee) + } else { + emitDistributeFeeEvent(ctx, k.Environment, receiver.String(), fee) } - emitDistributeFeeEvent(ctx, refundAccAddress.String(), fee) - } else { - emitDistributeFeeEvent(ctx, receiver.String(), fee) - } + return nil + + }) - // write the cache - writeFn() } // RefundFeesOnChannelClosure will refund all fees associated with the given port and channel identifiers. @@ -190,50 +186,48 @@ func (k Keeper) RefundFeesOnChannelClosure(ctx context.Context, portID, channelI // cache context before trying to distribute fees // if the escrow account has insufficient balance then we want to avoid partially distributing fees - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - cacheCtx, writeFn := sdkCtx.CacheContext() - - for _, identifiedPacketFee := range identifiedPacketFees { - var unRefundedFees []types.PacketFee - for _, packetFee := range identifiedPacketFee.PacketFees { - - if !k.EscrowAccountHasBalance(cacheCtx, packetFee.Fee.Total()) { - // if the escrow account does not have sufficient funds then there must exist a severe bug - // the fee module should be locked until manual intervention fixes the issue - // a locked fee module will simply skip fee logic, all channels will temporarily function as - // fee disabled channels - // NOTE: we use the uncached context to lock the fee module so that the state changes from - // locking the fee module are persisted - k.lockFeeModule(ctx) - - // return a nil error so state changes are committed but distribution stops - return nil + k.BranchService.Execute(ctx, func(ctx context.Context) error { + + for _, identifiedPacketFee := range identifiedPacketFees { + var unRefundedFees []types.PacketFee + for _, packetFee := range identifiedPacketFee.PacketFees { + + if !k.EscrowAccountHasBalance(ctx, packetFee.Fee.Total()) { + // if the escrow account does not have sufficient funds then there must exist a severe bug + // the fee module should be locked until manual intervention fixes the issue + // a locked fee module will simply skip fee logic, all channels will temporarily function as + // fee disabled channels + // NOTE: we use the uncached context to lock the fee module so that the state changes from + // locking the fee module are persisted + k.lockFeeModule(ctx) + + // return a nil error so state changes are committed but distribution stops + return nil + } + + refundAddr, err := sdk.AccAddressFromBech32(packetFee.RefundAddress) + if err != nil { + unRefundedFees = append(unRefundedFees, packetFee) + continue + } + + // refund all fees to refund address + if err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, refundAddr, packetFee.Fee.Total()); err != nil { + unRefundedFees = append(unRefundedFees, packetFee) + continue + } } - refundAddr, err := sdk.AccAddressFromBech32(packetFee.RefundAddress) - if err != nil { - unRefundedFees = append(unRefundedFees, packetFee) - continue - } - - // refund all fees to refund address - if err = k.bankKeeper.SendCoinsFromModuleToAccount(cacheCtx, types.ModuleName, refundAddr, packetFee.Fee.Total()); err != nil { - unRefundedFees = append(unRefundedFees, packetFee) - continue + if len(unRefundedFees) > 0 { + // update packet fees to keep only the unrefunded fees + packetFees := types.NewPacketFees(unRefundedFees) + k.SetFeesInEscrow(ctx, identifiedPacketFee.PacketId, packetFees) + } else { + k.DeleteFeesInEscrow(ctx, identifiedPacketFee.PacketId) } } - - if len(unRefundedFees) > 0 { - // update packet fees to keep only the unrefunded fees - packetFees := types.NewPacketFees(unRefundedFees) - k.SetFeesInEscrow(cacheCtx, identifiedPacketFee.PacketId, packetFees) - } else { - k.DeleteFeesInEscrow(cacheCtx, identifiedPacketFee.PacketId) - } - } - - // write the cache - writeFn() + return nil + }) return nil } diff --git a/modules/apps/29-fee/keeper/events.go b/modules/apps/29-fee/keeper/events.go index 683339a55ff..c54146addf0 100644 --- a/modules/apps/29-fee/keeper/events.go +++ b/modules/apps/29-fee/keeper/events.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/ibc-go/v9/modules/apps/29-fee/types" @@ -12,7 +14,7 @@ import ( // emitIncentivizedPacketEvent emits an event containing information on the total amount of fees incentivizing // a specific packet. It should be emitted on every fee escrowed for the given packetID. -func emitIncentivizedPacketEvent(ctx context.Context, packetID channeltypes.PacketId, packetFees types.PacketFees) { +func emitIncentivizedPacketEvent(ctx context.Context, env appmodule.Environment, packetID channeltypes.PacketId, packetFees types.PacketFees) { var ( totalRecvFees sdk.Coins totalAckFees sdk.Coins @@ -27,70 +29,61 @@ func emitIncentivizedPacketEvent(ctx context.Context, packetID channeltypes.Pack totalTimeoutFees = totalTimeoutFees.Add(fee.Fee.TimeoutFee...) } } - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/7223 - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeIncentivizedPacket, - sdk.NewAttribute(channeltypes.AttributeKeyPortID, packetID.PortId), - sdk.NewAttribute(channeltypes.AttributeKeyChannelID, packetID.ChannelId), - sdk.NewAttribute(channeltypes.AttributeKeySequence, fmt.Sprint(packetID.Sequence)), - sdk.NewAttribute(types.AttributeKeyRecvFee, totalRecvFees.String()), - sdk.NewAttribute(types.AttributeKeyAckFee, totalAckFees.String()), - sdk.NewAttribute(types.AttributeKeyTimeoutFee, totalTimeoutFees.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - ), - }) + + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeIncentivizedPacket, + event.Attribute{Key: channeltypes.AttributeKeyPortID, Value: packetID.PortId}, + event.Attribute{Key: channeltypes.AttributeKeyChannelID, Value: packetID.ChannelId}, + event.Attribute{Key: channeltypes.AttributeKeySequence, Value: fmt.Sprint(packetID.Sequence)}, + event.Attribute{Key: types.AttributeKeyRecvFee, Value: totalRecvFees.String()}, + event.Attribute{Key: types.AttributeKeyAckFee, Value: totalAckFees.String()}, + event.Attribute{Key: types.AttributeKeyTimeoutFee, Value: totalTimeoutFees.String()}, + ) + + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.ModuleName}, + ) + } // emitRegisterPayeeEvent emits an event containing information of a registered payee for a relayer on a particular channel -func emitRegisterPayeeEvent(ctx context.Context, relayer, payee, channelID string) { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/7223 - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeRegisterPayee, - sdk.NewAttribute(types.AttributeKeyRelayer, relayer), - sdk.NewAttribute(types.AttributeKeyPayee, payee), - sdk.NewAttribute(types.AttributeKeyChannelID, channelID), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - ), - }) +func emitRegisterPayeeEvent(ctx context.Context, env appmodule.Environment, relayer, payee, channelID string) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeRegisterPayee, + event.Attribute{Key: types.AttributeKeyRelayer, Value: relayer}, + event.Attribute{Key: types.AttributeKeyPayee, Value: payee}, + event.Attribute{Key: types.AttributeKeyChannelID, Value: channelID}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.ModuleName}, + ) } // emitRegisterCounterpartyPayeeEvent emits an event containing information of a registered counterparty payee for a relayer on a particular channel -func emitRegisterCounterpartyPayeeEvent(ctx context.Context, relayer, counterpartyPayee, channelID string) { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/7223 - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeRegisterCounterpartyPayee, - sdk.NewAttribute(types.AttributeKeyRelayer, relayer), - sdk.NewAttribute(types.AttributeKeyCounterpartyPayee, counterpartyPayee), - sdk.NewAttribute(types.AttributeKeyChannelID, channelID), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - ), - }) +func emitRegisterCounterpartyPayeeEvent(ctx context.Context, env appmodule.Environment, relayer, counterpartyPayee, channelID string) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeRegisterCounterpartyPayee, + event.Attribute{Key: types.AttributeKeyRelayer, Value: relayer}, + event.Attribute{Key: types.AttributeKeyCounterpartyPayee, Value: counterpartyPayee}, + event.Attribute{Key: types.AttributeKeyChannelID, Value: channelID}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.ModuleName}, + ) } // emitDistributeFeeEvent emits an event containing a distribution fee and receiver address -func emitDistributeFeeEvent(ctx context.Context, receiver string, fee sdk.Coins) { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/7223 - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeDistributeFee, - sdk.NewAttribute(types.AttributeKeyReceiver, receiver), - sdk.NewAttribute(types.AttributeKeyFee, fee.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - ), - }) +func emitDistributeFeeEvent(ctx context.Context, env appmodule.Environment, receiver string, fee sdk.Coins) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeDistributeFee, + event.Attribute{Key: types.AttributeKeyReceiver, Value: receiver}, + event.Attribute{Key: types.AttributeKeyFee, Value: fee.String()}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.ModuleName}, + ) } diff --git a/modules/apps/29-fee/keeper/genesis.go b/modules/apps/29-fee/keeper/genesis.go index c407238f772..e77b807a1db 100644 --- a/modules/apps/29-fee/keeper/genesis.go +++ b/modules/apps/29-fee/keeper/genesis.go @@ -7,7 +7,7 @@ import ( ) // InitGenesis initializes the fee middleware application state from a provided genesis state -func (k Keeper) InitGenesis(ctx context.Context, state types.GenesisState) { +func (k Keeper) InitGenesis(ctx context.Context, state types.GenesisState) error { for _, identifiedFees := range state.IdentifiedFees { k.SetFeesInEscrow(ctx, identifiedFees.PacketId, types.NewPacketFees(identifiedFees.PacketFees)) } @@ -27,6 +27,8 @@ func (k Keeper) InitGenesis(ctx context.Context, state types.GenesisState) { for _, enabledChan := range state.FeeEnabledChannels { k.SetFeeEnabled(ctx, enabledChan.PortId, enabledChan.ChannelId) } + + return nil } // ExportGenesis returns the fee middleware application exported genesis diff --git a/modules/apps/29-fee/keeper/grpc_query.go b/modules/apps/29-fee/keeper/grpc_query.go index cd6a0e05f33..62f586e7253 100644 --- a/modules/apps/29-fee/keeper/grpc_query.go +++ b/modules/apps/29-fee/keeper/grpc_query.go @@ -28,7 +28,7 @@ func (k Keeper) IncentivizedPackets(ctx context.Context, req *types.QueryIncenti var identifiedPackets []types.IdentifiedPacketFees - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), []byte(types.FeesInEscrowPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), []byte(types.FeesInEscrowPrefix)) pagination, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { packetID, err := types.ParseKeyFeesInEscrow(types.FeesInEscrowPrefix + string(key)) if err != nil { @@ -55,7 +55,7 @@ func (k Keeper) IncentivizedPacket(goCtx context.Context, req *types.QueryIncent return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx).WithBlockHeight(int64(req.QueryHeight)) + ctx := sdk.UnwrapSDKContext(goCtx).WithBlockHeight(int64(req.QueryHeight)) //TODO: remove, possibly unsafe feesInEscrow, exists := k.GetFeesInEscrow(ctx, req.PacketId) if !exists { @@ -70,7 +70,7 @@ func (k Keeper) IncentivizedPacket(goCtx context.Context, req *types.QueryIncent } // IncentivizedPacketsForChannel implements the Query/IncentivizedPacketsForChannel gRPC method -func (k Keeper) IncentivizedPacketsForChannel(goCtx context.Context, req *types.QueryIncentivizedPacketsForChannelRequest) (*types.QueryIncentivizedPacketsForChannelResponse, error) { +func (k Keeper) IncentivizedPacketsForChannel(ctx context.Context, req *types.QueryIncentivizedPacketsForChannelRequest) (*types.QueryIncentivizedPacketsForChannelResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -79,8 +79,6 @@ func (k Keeper) IncentivizedPacketsForChannel(goCtx context.Context, req *types. return nil, err } - ctx := sdk.UnwrapSDKContext(goCtx).WithBlockHeight(int64(req.QueryHeight)) - if !k.channelKeeper.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -90,7 +88,7 @@ func (k Keeper) IncentivizedPacketsForChannel(goCtx context.Context, req *types. var packets []*types.IdentifiedPacketFees keyPrefix := types.KeyFeesInEscrowChannelPrefix(req.PortId, req.ChannelId) - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), keyPrefix) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), keyPrefix) pagination, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { packetID, err := types.ParseKeyFeesInEscrow(string(keyPrefix) + string(key)) if err != nil { @@ -115,13 +113,11 @@ func (k Keeper) IncentivizedPacketsForChannel(goCtx context.Context, req *types. } // TotalRecvFees implements the Query/TotalRecvFees gRPC method -func (k Keeper) TotalRecvFees(goCtx context.Context, req *types.QueryTotalRecvFeesRequest) (*types.QueryTotalRecvFeesResponse, error) { +func (k Keeper) TotalRecvFees(ctx context.Context, req *types.QueryTotalRecvFeesRequest) (*types.QueryTotalRecvFeesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx) - feesInEscrow, found := k.GetFeesInEscrow(ctx, req.PacketId) if !found { return nil, status.Errorf( @@ -141,13 +137,11 @@ func (k Keeper) TotalRecvFees(goCtx context.Context, req *types.QueryTotalRecvFe } // TotalAckFees implements the Query/TotalAckFees gRPC method -func (k Keeper) TotalAckFees(goCtx context.Context, req *types.QueryTotalAckFeesRequest) (*types.QueryTotalAckFeesResponse, error) { +func (k Keeper) TotalAckFees(ctx context.Context, req *types.QueryTotalAckFeesRequest) (*types.QueryTotalAckFeesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx) - feesInEscrow, found := k.GetFeesInEscrow(ctx, req.PacketId) if !found { return nil, status.Errorf( @@ -167,13 +161,11 @@ func (k Keeper) TotalAckFees(goCtx context.Context, req *types.QueryTotalAckFees } // TotalTimeoutFees implements the Query/TotalTimeoutFees gRPC method -func (k Keeper) TotalTimeoutFees(goCtx context.Context, req *types.QueryTotalTimeoutFeesRequest) (*types.QueryTotalTimeoutFeesResponse, error) { +func (k Keeper) TotalTimeoutFees(ctx context.Context, req *types.QueryTotalTimeoutFeesRequest) (*types.QueryTotalTimeoutFeesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx) - feesInEscrow, found := k.GetFeesInEscrow(ctx, req.PacketId) if !found { return nil, status.Errorf( @@ -193,13 +185,11 @@ func (k Keeper) TotalTimeoutFees(goCtx context.Context, req *types.QueryTotalTim } // Payee implements the Query/Payee gRPC method and returns the registered payee address to which packet fees are paid out -func (k Keeper) Payee(goCtx context.Context, req *types.QueryPayeeRequest) (*types.QueryPayeeResponse, error) { +func (k Keeper) Payee(ctx context.Context, req *types.QueryPayeeRequest) (*types.QueryPayeeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx) - payeeAddr, found := k.GetPayeeAddress(ctx, req.Relayer, req.ChannelId) if !found { return nil, status.Errorf(codes.NotFound, "payee address not found for address: %s on channel: %s", req.Relayer, req.ChannelId) @@ -211,13 +201,11 @@ func (k Keeper) Payee(goCtx context.Context, req *types.QueryPayeeRequest) (*typ } // CounterpartyPayee implements the Query/CounterpartyPayee gRPC method and returns the registered counterparty payee address for forward relaying -func (k Keeper) CounterpartyPayee(goCtx context.Context, req *types.QueryCounterpartyPayeeRequest) (*types.QueryCounterpartyPayeeResponse, error) { +func (k Keeper) CounterpartyPayee(ctx context.Context, req *types.QueryCounterpartyPayeeRequest) (*types.QueryCounterpartyPayeeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx) - counterpartyPayeeAddr, found := k.GetCounterpartyPayeeAddress(ctx, req.Relayer, req.ChannelId) if !found { return nil, status.Errorf(codes.NotFound, "counterparty payee address not found for address: %s on channel: %s", req.Relayer, req.ChannelId) @@ -235,7 +223,7 @@ func (k Keeper) FeeEnabledChannels(ctx context.Context, req *types.QueryFeeEnabl } var feeEnabledChannels []types.FeeEnabledChannel - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), []byte(types.FeeEnabledKeyPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), []byte(types.FeeEnabledKeyPrefix)) pagination, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { portID, channelID, err := types.ParseKeyFeeEnabled(types.FeeEnabledKeyPrefix + string(key)) if err != nil { @@ -263,7 +251,7 @@ func (k Keeper) FeeEnabledChannels(ctx context.Context, req *types.QueryFeeEnabl // FeeEnabledChannel implements the Query/FeeEnabledChannel gRPC method and returns true if the provided // port and channel identifiers belong to a fee enabled channel -func (k Keeper) FeeEnabledChannel(goCtx context.Context, req *types.QueryFeeEnabledChannelRequest) (*types.QueryFeeEnabledChannelResponse, error) { +func (k Keeper) FeeEnabledChannel(ctx context.Context, req *types.QueryFeeEnabledChannelRequest) (*types.QueryFeeEnabledChannelResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -272,8 +260,6 @@ func (k Keeper) FeeEnabledChannel(goCtx context.Context, req *types.QueryFeeEnab return nil, err } - ctx := sdk.UnwrapSDKContext(goCtx) - if !k.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, diff --git a/modules/apps/29-fee/keeper/keeper.go b/modules/apps/29-fee/keeper/keeper.go index 874c97ea42c..5d17273be88 100644 --- a/modules/apps/29-fee/keeper/keeper.go +++ b/modules/apps/29-fee/keeper/keeper.go @@ -3,8 +3,7 @@ package keeper import ( "context" - corestore "cosmossdk.io/core/store" - "cosmossdk.io/log" + "cosmossdk.io/core/appmodule" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" @@ -15,7 +14,6 @@ import ( "github.com/cosmos/ibc-go/v9/modules/apps/29-fee/types" channeltypes "github.com/cosmos/ibc-go/v9/modules/core/04-channel/types" porttypes "github.com/cosmos/ibc-go/v9/modules/core/05-port/types" - ibcexported "github.com/cosmos/ibc-go/v9/modules/core/exported" coretypes "github.com/cosmos/ibc-go/v9/modules/core/types" ) @@ -28,8 +26,8 @@ var ( // Keeper defines the IBC fungible transfer keeper type Keeper struct { - storeService corestore.KVStoreService - cdc codec.BinaryCodec + appmodule.Environment + cdc codec.BinaryCodec authKeeper types.AccountKeeper ics4Wrapper porttypes.ICS4Wrapper @@ -40,13 +38,13 @@ type Keeper struct { // NewKeeper creates a new 29-fee Keeper instance func NewKeeper( - cdc codec.BinaryCodec, storeService corestore.KVStoreService, + cdc codec.BinaryCodec, env appmodule.Environment, ics4Wrapper porttypes.ICS4Wrapper, channelKeeper types.ChannelKeeper, portKeeper types.PortKeeper, authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, ) Keeper { return Keeper{ cdc: cdc, - storeService: storeService, + Environment: env, ics4Wrapper: ics4Wrapper, channelKeeper: channelKeeper, portKeeper: portKeeper, @@ -67,12 +65,6 @@ func (k Keeper) GetICS4Wrapper() porttypes.ICS4Wrapper { return k.ics4Wrapper } -// Logger returns a module-specific logger. -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return sdkCtx.Logger().With("module", "x/"+ibcexported.ModuleName+"-"+types.ModuleName) -} - // BindPort defines a wrapper function for the port Keeper's function in // order to expose it to module's InitGenesis function func (k Keeper) BindPort(ctx context.Context, portID string) *capabilitytypes.Capability { @@ -119,7 +111,7 @@ func (k Keeper) EscrowAccountHasBalance(ctx context.Context, coins sdk.Coins) bo // identified by channel and port identifiers. // Please see ADR 004 for more information. func (k Keeper) lockFeeModule(ctx context.Context) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(types.KeyLocked(), []byte{1}); err != nil { panic(err) } @@ -128,7 +120,7 @@ func (k Keeper) lockFeeModule(ctx context.Context) { // IsLocked indicates if the fee module is locked // Please see ADR 004 for more information. func (k Keeper) IsLocked(ctx context.Context) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(types.KeyLocked()) if err != nil { panic(err) @@ -139,7 +131,7 @@ func (k Keeper) IsLocked(ctx context.Context) bool { // SetFeeEnabled sets a flag to determine if fee handling logic should run for the given channel // identified by channel and port identifiers. func (k Keeper) SetFeeEnabled(ctx context.Context, portID, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(types.KeyFeeEnabled(portID, channelID), []byte{1}); err != nil { panic(err) } @@ -147,7 +139,7 @@ func (k Keeper) SetFeeEnabled(ctx context.Context, portID, channelID string) { // DeleteFeeEnabled deletes the fee enabled flag for a given portID and channelID func (k Keeper) DeleteFeeEnabled(ctx context.Context, portID, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(types.KeyFeeEnabled(portID, channelID)); err != nil { panic(err) } @@ -156,7 +148,7 @@ func (k Keeper) DeleteFeeEnabled(ctx context.Context, portID, channelID string) // IsFeeEnabled returns whether fee handling logic should be run for the given port. It will check the // fee enabled flag for the given port and channel identifiers func (k Keeper) IsFeeEnabled(ctx context.Context, portID, channelID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(types.KeyFeeEnabled(portID, channelID)) if err != nil { panic(err) @@ -166,9 +158,9 @@ func (k Keeper) IsFeeEnabled(ctx context.Context, portID, channelID string) bool // GetAllFeeEnabledChannels returns a list of all ics29 enabled channels containing portID & channelID that are stored in state func (k Keeper) GetAllFeeEnabledChannels(ctx context.Context) []types.FeeEnabledChannel { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.FeeEnabledKeyPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var enabledChArr []types.FeeEnabledChannel for ; iterator.Valid(); iterator.Next() { @@ -189,7 +181,7 @@ func (k Keeper) GetAllFeeEnabledChannels(ctx context.Context) []types.FeeEnabled // GetPayeeAddress retrieves the fee payee address stored in state given the provided channel identifier and relayer address func (k Keeper) GetPayeeAddress(ctx context.Context, relayerAddr, channelID string) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyPayee(relayerAddr, channelID) bz, err := store.Get(key) @@ -206,7 +198,7 @@ func (k Keeper) GetPayeeAddress(ctx context.Context, relayerAddr, channelID stri // SetPayeeAddress stores the fee payee address in state keyed by the provided channel identifier and relayer address func (k Keeper) SetPayeeAddress(ctx context.Context, relayerAddr, payeeAddr, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(types.KeyPayee(relayerAddr, channelID), []byte(payeeAddr)); err != nil { panic(err) } @@ -214,9 +206,9 @@ func (k Keeper) SetPayeeAddress(ctx context.Context, relayerAddr, payeeAddr, cha // GetAllPayees returns all registered payees addresses func (k Keeper) GetAllPayees(ctx context.Context) []types.RegisteredPayee { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.PayeeKeyPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var registeredPayees []types.RegisteredPayee for ; iterator.Valid(); iterator.Next() { @@ -240,7 +232,7 @@ func (k Keeper) GetAllPayees(ctx context.Context) []types.RegisteredPayee { // SetCounterpartyPayeeAddress maps the destination chain counterparty payee address to the source relayer address // The receiving chain must store the mapping from: address -> counterpartyPayeeAddress for the given channel func (k Keeper) SetCounterpartyPayeeAddress(ctx context.Context, address, counterpartyAddress, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(types.KeyCounterpartyPayee(address, channelID), []byte(counterpartyAddress)); err != nil { panic(err) } @@ -248,7 +240,7 @@ func (k Keeper) SetCounterpartyPayeeAddress(ctx context.Context, address, counte // GetCounterpartyPayeeAddress gets the counterparty payee address given a destination relayer address func (k Keeper) GetCounterpartyPayeeAddress(ctx context.Context, address, channelID string) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyCounterpartyPayee(address, channelID) addr, err := store.Get(key) @@ -264,9 +256,9 @@ func (k Keeper) GetCounterpartyPayeeAddress(ctx context.Context, address, channe // GetAllCounterpartyPayees returns all registered counterparty payee addresses func (k Keeper) GetAllCounterpartyPayees(ctx context.Context) []types.RegisteredCounterpartyPayee { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.CounterpartyPayeeKeyPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var registeredCounterpartyPayees []types.RegisteredCounterpartyPayee for ; iterator.Valid(); iterator.Next() { @@ -289,7 +281,7 @@ func (k Keeper) GetAllCounterpartyPayees(ctx context.Context) []types.Registered // SetRelayerAddressForAsyncAck sets the forward relayer address during OnRecvPacket in case of async acknowledgement func (k Keeper) SetRelayerAddressForAsyncAck(ctx context.Context, packetID channeltypes.PacketId, address string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(types.KeyRelayerAddressForAsyncAck(packetID), []byte(address)); err != nil { panic(err) } @@ -297,7 +289,7 @@ func (k Keeper) SetRelayerAddressForAsyncAck(ctx context.Context, packetID chann // GetRelayerAddressForAsyncAck gets forward relayer address for a particular packet func (k Keeper) GetRelayerAddressForAsyncAck(ctx context.Context, packetID channeltypes.PacketId) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyRelayerAddressForAsyncAck(packetID) addr, err := store.Get(key) @@ -314,9 +306,9 @@ func (k Keeper) GetRelayerAddressForAsyncAck(ctx context.Context, packetID chann // GetAllForwardRelayerAddresses returns all forward relayer addresses stored for async acknowledgements func (k Keeper) GetAllForwardRelayerAddresses(ctx context.Context) []types.ForwardRelayerAddress { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.ForwardRelayerPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var forwardRelayerAddr []types.ForwardRelayerAddress for ; iterator.Valid(); iterator.Next() { @@ -338,7 +330,7 @@ func (k Keeper) GetAllForwardRelayerAddresses(ctx context.Context) []types.Forwa // DeleteForwardRelayerAddress deletes the forwardRelayerAddr associated with the packetID func (k Keeper) DeleteForwardRelayerAddress(ctx context.Context, packetID channeltypes.PacketId) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyRelayerAddressForAsyncAck(packetID) if err := store.Delete(key); err != nil { panic(err) @@ -347,7 +339,7 @@ func (k Keeper) DeleteForwardRelayerAddress(ctx context.Context, packetID channe // GetFeesInEscrow returns all escrowed packet fees for a given packetID func (k Keeper) GetFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId) (types.PacketFees, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyFeesInEscrow(packetID) bz, err := store.Get(key) if err != nil { @@ -362,7 +354,7 @@ func (k Keeper) GetFeesInEscrow(ctx context.Context, packetID channeltypes.Packe // HasFeesInEscrow returns true if packet fees exist for the provided packetID func (k Keeper) HasFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyFeesInEscrow(packetID) has, err := store.Has(key) if err != nil { @@ -373,7 +365,7 @@ func (k Keeper) HasFeesInEscrow(ctx context.Context, packetID channeltypes.Packe // SetFeesInEscrow sets the given packet fees in escrow keyed by the packetID func (k Keeper) SetFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId, fees types.PacketFees) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.MustMarshalFees(fees) if err := store.Set(types.KeyFeesInEscrow(packetID), bz); err != nil { panic(err) @@ -382,7 +374,7 @@ func (k Keeper) SetFeesInEscrow(ctx context.Context, packetID channeltypes.Packe // DeleteFeesInEscrow deletes the fee associated with the given packetID func (k Keeper) DeleteFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.KeyFeesInEscrow(packetID) if err := store.Delete(key); err != nil { panic(err) @@ -393,10 +385,10 @@ func (k Keeper) DeleteFeesInEscrow(ctx context.Context, packetID channeltypes.Pa func (k Keeper) GetIdentifiedPacketFeesForChannel(ctx context.Context, portID, channelID string) []types.IdentifiedPacketFees { var identifiedPacketFees []types.IdentifiedPacketFees - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.KeyFeesInEscrowChannelPrefix(portID, channelID)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { packetID, err := types.ParseKeyFeesInEscrow(string(iterator.Key())) if err != nil { @@ -414,9 +406,9 @@ func (k Keeper) GetIdentifiedPacketFeesForChannel(ctx context.Context, portID, c // GetAllIdentifiedPacketFees returns a list of all IdentifiedPacketFees that are stored in state func (k Keeper) GetAllIdentifiedPacketFees(ctx context.Context) []types.IdentifiedPacketFees { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.FeesInEscrowPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var identifiedFees []types.IdentifiedPacketFees for ; iterator.Valid(); iterator.Next() { diff --git a/modules/apps/29-fee/keeper/migrations.go b/modules/apps/29-fee/keeper/migrations.go index 971a692e48c..6bb05548796 100644 --- a/modules/apps/29-fee/keeper/migrations.go +++ b/modules/apps/29-fee/keeper/migrations.go @@ -25,7 +25,7 @@ func NewMigrator(keeper Keeper) Migrator { // Migrate1to2 migrates ibc-fee module from ConsensusVersion 1 to 2 // by refunding leftover fees to the refund address. func (m Migrator) Migrate1to2(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(m.keeper.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.FeesInEscrowPrefix)) defer coretypes.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) diff --git a/modules/apps/29-fee/keeper/msg_server.go b/modules/apps/29-fee/keeper/msg_server.go index e79996a0389..671334a013a 100644 --- a/modules/apps/29-fee/keeper/msg_server.go +++ b/modules/apps/29-fee/keeper/msg_server.go @@ -19,8 +19,7 @@ var _ types.MsgServer = (*Keeper)(nil) // payee to which reverse and timeout relayer packet fees will be paid out. The payee should be registered on // the source chain from which packets originate as this is where fee distribution takes place. This function may be // called more than once by a relayer, in which case, the latest payee is always used. -func (k Keeper) RegisterPayee(goCtx context.Context, msg *types.MsgRegisterPayee) (*types.MsgRegisterPayeeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) +func (k Keeper) RegisterPayee(ctx context.Context, msg *types.MsgRegisterPayee) (*types.MsgRegisterPayeeResponse, error) { payee, err := sdk.AccAddressFromBech32(msg.Payee) if err != nil { @@ -42,9 +41,9 @@ func (k Keeper) RegisterPayee(goCtx context.Context, msg *types.MsgRegisterPayee k.SetPayeeAddress(ctx, msg.Relayer, msg.Payee, msg.ChannelId) - k.Logger(ctx).Info("registering payee address for relayer", "relayer", msg.Relayer, "payee", msg.Payee, "channel", msg.ChannelId) + k.Logger.Info("registering payee address for relayer", "relayer", msg.Relayer, "payee", msg.Payee, "channel", msg.ChannelId) - emitRegisterPayeeEvent(ctx, msg.Relayer, msg.Payee, msg.ChannelId) + emitRegisterPayeeEvent(ctx, k.Environment, msg.Relayer, msg.Payee, msg.ChannelId) return &types.MsgRegisterPayeeResponse{}, nil } @@ -54,8 +53,7 @@ func (k Keeper) RegisterPayee(goCtx context.Context, msg *types.MsgRegisterPayee // payee address before relaying. This ensures they will be properly compensated for forward relaying since // the destination chain must include the registered counterparty payee address in the acknowledgement. This function // may be called more than once by a relayer, in which case, the latest counterparty payee address is always used. -func (k Keeper) RegisterCounterpartyPayee(goCtx context.Context, msg *types.MsgRegisterCounterpartyPayee) (*types.MsgRegisterCounterpartyPayeeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) +func (k Keeper) RegisterCounterpartyPayee(ctx context.Context, msg *types.MsgRegisterCounterpartyPayee) (*types.MsgRegisterCounterpartyPayeeResponse, error) { // only register counterparty payee if the channel exists and is fee enabled if _, found := k.channelKeeper.GetChannel(ctx, msg.PortId, msg.ChannelId); !found { @@ -68,17 +66,16 @@ func (k Keeper) RegisterCounterpartyPayee(goCtx context.Context, msg *types.MsgR k.SetCounterpartyPayeeAddress(ctx, msg.Relayer, msg.CounterpartyPayee, msg.ChannelId) - k.Logger(ctx).Info("registering counterparty payee for relayer", "relayer", msg.Relayer, "counterparty payee", msg.CounterpartyPayee, "channel", msg.ChannelId) + k.Logger.Info("registering counterparty payee for relayer", "relayer", msg.Relayer, "counterparty payee", msg.CounterpartyPayee, "channel", msg.ChannelId) - emitRegisterCounterpartyPayeeEvent(ctx, msg.Relayer, msg.CounterpartyPayee, msg.ChannelId) + emitRegisterCounterpartyPayeeEvent(ctx, k.Environment, msg.Relayer, msg.CounterpartyPayee, msg.ChannelId) return &types.MsgRegisterCounterpartyPayeeResponse{}, nil } // PayPacketFee defines a rpc handler method for MsgPayPacketFee // PayPacketFee is an open callback that may be called by any module/user that wishes to escrow funds in order to relay the packet with the next sequence -func (k Keeper) PayPacketFee(goCtx context.Context, msg *types.MsgPayPacketFee) (*types.MsgPayPacketFeeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) +func (k Keeper) PayPacketFee(ctx context.Context, msg *types.MsgPayPacketFee) (*types.MsgPayPacketFeeResponse, error) { if !k.IsFeeEnabled(ctx, msg.SourcePortId, msg.SourceChannelId) { // users may not escrow fees on this channel. Must send packets without a fee message @@ -122,9 +119,7 @@ func (k Keeper) PayPacketFee(goCtx context.Context, msg *types.MsgPayPacketFee) // PayPacketFeeAsync is an open callback that may be called by any module/user that wishes to escrow funds in order to // incentivize the relaying of a known packet. Only packets which have been sent and have not gone through the // packet life cycle may be incentivized. -func (k Keeper) PayPacketFeeAsync(goCtx context.Context, msg *types.MsgPayPacketFeeAsync) (*types.MsgPayPacketFeeAsyncResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - +func (k Keeper) PayPacketFeeAsync(ctx context.Context, msg *types.MsgPayPacketFeeAsync) (*types.MsgPayPacketFeeAsyncResponse, error) { if !k.IsFeeEnabled(ctx, msg.PacketId.PortId, msg.PacketId.ChannelId) { // users may not escrow fees on this channel. Must send packets without a fee message return nil, types.ErrFeeNotEnabled diff --git a/modules/apps/29-fee/module.go b/modules/apps/29-fee/module.go index 05d2f1cd0c2..f25bfe92e17 100644 --- a/modules/apps/29-fee/module.go +++ b/modules/apps/29-fee/module.go @@ -9,11 +9,11 @@ import ( "github.com/spf13/cobra" "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/registry" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -23,18 +23,19 @@ import ( ) var ( - _ module.AppModule = (*AppModule)(nil) - _ module.AppModuleBasic = (*AppModuleBasic)(nil) - _ module.AppModuleSimulation = (*AppModule)(nil) - _ module.HasGenesis = (*AppModule)(nil) - _ module.HasName = (*AppModule)(nil) - _ module.HasConsensusVersion = (*AppModule)(nil) - _ module.HasServices = (*AppModule)(nil) - _ appmodule.AppModule = (*AppModule)(nil) + _ module.AppModule = (*AppModule)(nil) + _ module.AppModuleBasic = (*AppModuleBasic)(nil) + _ module.AppModuleSimulation = (*AppModule)(nil) + _ module.HasGenesis = (*AppModule)(nil) + _ appmodule.HasConsensusVersion = (*AppModule)(nil) + _ module.HasServices = (*AppModule)(nil) + _ appmodule.AppModule = (*AppModule)(nil) ) // AppModuleBasic is the 29-fee AppModuleBasic -type AppModuleBasic struct{} +type AppModuleBasic struct { + cdc codec.Codec +} // Name implements AppModuleBasic interface func (AppModuleBasic) Name() string { @@ -48,7 +49,7 @@ func (AppModule) IsOnePerModuleType() {} func (AppModule) IsAppModule() {} // RegisterLegacyAminoCodec implements AppModuleBasic interface -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc registry.AminoRegistrar) { types.RegisterLegacyAminoCodec(cdc) } @@ -59,14 +60,14 @@ func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) // DefaultGenesis returns default genesis state as raw bytes for the ibc // 29-fee module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModuleBasic) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the 29-fee module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var gs types.GenesisState - if err := cdc.UnmarshalJSON(bz, &gs); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &gs); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -117,17 +118,19 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the ibc-29-fee module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return am.keeper.InitGenesis(ctx, genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the ibc-29-fee // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements AppModule/ConsensusVersion. diff --git a/modules/apps/29-fee/types/codec.go b/modules/apps/29-fee/types/codec.go index 4ac59323f1e..f3943c338bc 100644 --- a/modules/apps/29-fee/types/codec.go +++ b/modules/apps/29-fee/types/codec.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/core/registry" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -10,7 +11,7 @@ import ( // RegisterLegacyAminoCodec registers the necessary x/ibc 29-fee interfaces and concrete types // on the provided LegacyAmino codec. These types are used for Amino JSON serialization. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func RegisterLegacyAminoCodec(cdc registry.AminoRegistrar) { legacy.RegisterAminoMsg(cdc, &MsgPayPacketFee{}, "cosmos-sdk/MsgPayPacketFee") legacy.RegisterAminoMsg(cdc, &MsgPayPacketFeeAsync{}, "cosmos-sdk/MsgPayPacketFeeAsync") legacy.RegisterAminoMsg(cdc, &MsgRegisterPayee{}, "cosmos-sdk/MsgRegisterPayee") diff --git a/modules/apps/29-fee/types/msgs_test.go b/modules/apps/29-fee/types/msgs_test.go index be39ea3ac2b..e097208fbfc 100644 --- a/modules/apps/29-fee/types/msgs_test.go +++ b/modules/apps/29-fee/types/msgs_test.go @@ -98,7 +98,7 @@ func TestRegisterPayeeGetSigners(t *testing.T) { msg := types.NewMsgRegisterPayee(ibctesting.MockPort, ibctesting.FirstChannelID, accAddress.String(), defaultAccAddress) encodingCfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, modulefee.AppModule{}) - signers, _, err := encodingCfg.Codec.GetMsgV1Signers(msg) + signers, _, err := encodingCfg.Codec.GetMsgSigners(msg) require.NoError(t, err) require.Equal(t, accAddress.Bytes(), signers[0]) } @@ -186,7 +186,7 @@ func TestRegisterCountepartyAddressGetSigners(t *testing.T) { msg := types.NewMsgRegisterCounterpartyPayee(ibctesting.MockPort, ibctesting.FirstChannelID, accAddress.String(), defaultAccAddress) encodingCfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, modulefee.AppModule{}) - signers, _, err := encodingCfg.Codec.GetMsgV1Signers(msg) + signers, _, err := encodingCfg.Codec.GetMsgSigners(msg) require.NoError(t, err) require.Equal(t, accAddress.Bytes(), signers[0]) } @@ -265,7 +265,7 @@ func TestPayPacketFeeGetSigners(t *testing.T) { msg := types.NewMsgPayPacketFee(fee, ibctesting.MockFeePort, ibctesting.FirstChannelID, refundAddr.String(), nil) encodingCfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, modulefee.AppModule{}) - signers, _, err := encodingCfg.Codec.GetMsgV1Signers(msg) + signers, _, err := encodingCfg.Codec.GetMsgSigners(msg) require.NoError(t, err) require.Equal(t, refundAddr.Bytes(), signers[0]) } @@ -404,7 +404,7 @@ func TestPayPacketFeeAsyncGetSigners(t *testing.T) { msg := types.NewMsgPayPacketFeeAsync(packetID, packetFee) encodingCfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, modulefee.AppModule{}) - signers, _, err := encodingCfg.Codec.GetMsgV1Signers(msg) + signers, _, err := encodingCfg.Codec.GetMsgSigners(msg) require.NoError(t, err) require.Equal(t, refundAddr.Bytes(), signers[0]) } diff --git a/modules/apps/transfer/ibc_module.go b/modules/apps/transfer/ibc_module.go index c6445645c23..ba13442a196 100644 --- a/modules/apps/transfer/ibc_module.go +++ b/modules/apps/transfer/ibc_module.go @@ -111,7 +111,7 @@ func (im IBCModule) OnChanOpenTry( } if !slices.Contains(types.SupportedVersions, counterpartyVersion) { - im.keeper.Logger(ctx).Debug("invalid counterparty version, proposing latest app version", "counterpartyVersion", counterpartyVersion, "version", types.V2) + im.keeper.Logger.Debug("invalid counterparty version, proposing latest app version", "counterpartyVersion", counterpartyVersion, "version", types.V2) return types.V2, nil } @@ -187,17 +187,17 @@ func (im IBCModule) OnRecvPacket( data, ackErr = types.UnmarshalPacketData(packet.GetData(), channelVersion) if ackErr != nil { ack = channeltypes.NewErrorAcknowledgement(ackErr) - im.keeper.Logger(ctx).Error(fmt.Sprintf("%s sequence %d", ackErr.Error(), packet.Sequence)) + im.keeper.Logger.Error(fmt.Sprintf("%s sequence %d", ackErr.Error(), packet.Sequence)) return ack } if ackErr = im.keeper.OnRecvPacket(ctx, packet, data); ackErr != nil { ack = channeltypes.NewErrorAcknowledgement(ackErr) - im.keeper.Logger(ctx).Error(fmt.Sprintf("%s sequence %d", ackErr.Error(), packet.Sequence)) + im.keeper.Logger.Error(fmt.Sprintf("%s sequence %d", ackErr.Error(), packet.Sequence)) return ack } - im.keeper.Logger(ctx).Info("successfully handled ICS-20 packet", "sequence", packet.Sequence) + im.keeper.Logger.Info("successfully handled ICS-20 packet", "sequence", packet.Sequence) if data.HasForwarding() { // NOTE: acknowledgement will be written asynchronously @@ -276,7 +276,7 @@ func (im IBCModule) OnChanUpgradeTry(ctx context.Context, portID, channelID stri } if !slices.Contains(types.SupportedVersions, counterpartyVersion) { - im.keeper.Logger(ctx).Debug("invalid counterparty version, proposing latest app version", "counterpartyVersion", counterpartyVersion, "version", types.V2) + im.keeper.Logger.Debug("invalid counterparty version, proposing latest app version", "counterpartyVersion", counterpartyVersion, "version", types.V2) return types.V2, nil } diff --git a/modules/apps/transfer/keeper/genesis.go b/modules/apps/transfer/keeper/genesis.go index d9653ce3c6c..20fe87e4c04 100644 --- a/modules/apps/transfer/keeper/genesis.go +++ b/modules/apps/transfer/keeper/genesis.go @@ -1,13 +1,13 @@ package keeper import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "context" "github.com/cosmos/ibc-go/v9/modules/apps/transfer/types" ) // InitGenesis initializes the ibc-transfer state and binds to PortID. -func (k Keeper) InitGenesis(ctx sdk.Context, state types.GenesisState) { +func (k Keeper) InitGenesis(ctx context.Context, state types.GenesisState) error { k.SetPort(ctx, state.PortId) for _, denom := range state.Denoms { @@ -28,15 +28,16 @@ func (k Keeper) InitGenesis(ctx sdk.Context, state types.GenesisState) { forwardKey := forwardPacketState.ForwardKey k.setForwardedPacket(ctx, forwardKey.PortId, forwardKey.ChannelId, forwardKey.Sequence, forwardPacketState.Packet) } + return nil } // ExportGenesis exports ibc-transfer module's portID and denom trace info into its genesis state. -func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { +func (k Keeper) ExportGenesis(ctx context.Context) (*types.GenesisState, error) { return &types.GenesisState{ PortId: k.GetPort(ctx), Denoms: k.GetAllDenoms(ctx), Params: k.GetParams(ctx), TotalEscrowed: k.GetAllTotalEscrowed(ctx), ForwardedPackets: k.getAllForwardedPackets(ctx), - } + }, nil } diff --git a/modules/apps/transfer/keeper/genesis_test.go b/modules/apps/transfer/keeper/genesis_test.go index 2a44b65610d..b388232538a 100644 --- a/modules/apps/transfer/keeper/genesis_test.go +++ b/modules/apps/transfer/keeper/genesis_test.go @@ -57,7 +57,8 @@ func (suite *KeeperTestSuite) TestGenesis() { } } - genesis := suite.chainA.GetSimApp().TransferKeeper.ExportGenesis(suite.chainA.GetContext()) + genesis, err := suite.chainA.GetSimApp().TransferKeeper.ExportGenesis(suite.chainA.GetContext()) + suite.Require().NoError(err) suite.Require().Equal(types.PortID, genesis.PortId) suite.Require().Equal(denoms.Sort(), genesis.Denoms) diff --git a/modules/apps/transfer/keeper/grpc_query.go b/modules/apps/transfer/keeper/grpc_query.go index 90f53542985..eb8d11ca818 100644 --- a/modules/apps/transfer/keeper/grpc_query.go +++ b/modules/apps/transfer/keeper/grpc_query.go @@ -56,11 +56,11 @@ func (k Keeper) Denoms(ctx context.Context, req *types.QueryDenomsRequest) (*typ } var denoms types.Denoms - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.DenomKey) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), types.DenomKey) pageRes, err := query.Paginate(store, req.Pagination, func(_, value []byte) error { var denom types.Denom - if err := k.cdc.Unmarshal(value, &denom); err != nil { + if err := k.Cdc.Unmarshal(value, &denom); err != nil { return err } diff --git a/modules/apps/transfer/keeper/keeper.go b/modules/apps/transfer/keeper/keeper.go index 589d1d6d5f6..444daac5ac8 100644 --- a/modules/apps/transfer/keeper/keeper.go +++ b/modules/apps/transfer/keeper/keeper.go @@ -6,8 +6,7 @@ import ( "fmt" "strings" - corestore "cosmossdk.io/core/store" - "cosmossdk.io/log" + "cosmossdk.io/core/appmodule" "cosmossdk.io/math" sdkmath "cosmossdk.io/math" "cosmossdk.io/store/prefix" @@ -30,8 +29,9 @@ import ( // Keeper defines the IBC fungible transfer keeper type Keeper struct { - storeService corestore.KVStoreService - cdc codec.BinaryCodec + appmodule.Environment + + Cdc codec.BinaryCodec legacySubspace types.ParamSubspace ics4Wrapper porttypes.ICS4Wrapper @@ -49,7 +49,7 @@ type Keeper struct { // NewKeeper creates a new IBC transfer Keeper instance func NewKeeper( cdc codec.BinaryCodec, - storeService corestore.KVStoreService, + env appmodule.Environment, legacySubspace types.ParamSubspace, ics4Wrapper porttypes.ICS4Wrapper, channelKeeper types.ChannelKeeper, @@ -69,8 +69,8 @@ func NewKeeper( } return Keeper{ - cdc: cdc, - storeService: storeService, + Cdc: cdc, + Environment: env, legacySubspace: legacySubspace, ics4Wrapper: ics4Wrapper, channelKeeper: channelKeeper, @@ -99,15 +99,9 @@ func (k Keeper) GetAuthority() string { return k.authority } -// Logger returns a module-specific logger. -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"-"+types.ModuleName) -} - // GetPort returns the portID for the transfer module. Used in ExportGenesis func (k Keeper) GetPort(ctx context.Context) string { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(types.PortKey) if err != nil { panic(err) @@ -117,7 +111,7 @@ func (k Keeper) GetPort(ctx context.Context) string { // SetPort sets the portID for the transfer module. Used in InitGenesis func (k Keeper) SetPort(ctx context.Context, portID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(types.PortKey, []byte(portID)); err != nil { panic(err) } @@ -125,7 +119,7 @@ func (k Keeper) SetPort(ctx context.Context, portID string) { // GetParams returns the current transfer module parameters. func (k Keeper) GetParams(ctx context.Context) types.Params { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.ParamsKey)) if err != nil { panic(err) @@ -135,14 +129,14 @@ func (k Keeper) GetParams(ctx context.Context) types.Params { } var params types.Params - k.cdc.MustUnmarshal(bz, ¶ms) + k.Cdc.MustUnmarshal(bz, ¶ms) return params } // SetParams sets the transfer module parameters. func (k Keeper) SetParams(ctx context.Context, params types.Params) { - store := k.storeService.OpenKVStore(ctx) - bz := k.cdc.MustMarshal(¶ms) + store := k.KVStoreService.OpenKVStore(ctx) + bz := k.Cdc.MustMarshal(¶ms) if err := store.Set([]byte(types.ParamsKey), bz); err != nil { panic(err) } @@ -150,29 +144,29 @@ func (k Keeper) SetParams(ctx context.Context, params types.Params) { // GetDenom retrieves the denom from store given the hash of the denom. func (k Keeper) GetDenom(ctx context.Context, denomHash cmtbytes.HexBytes) (types.Denom, bool) { - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.DenomKey) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), types.DenomKey) bz := store.Get(denomHash) if len(bz) == 0 { return types.Denom{}, false } var denom types.Denom - k.cdc.MustUnmarshal(bz, &denom) + k.Cdc.MustUnmarshal(bz, &denom) return denom, true } // HasDenom checks if a the key with the given denomination hash exists on the store. func (k Keeper) HasDenom(ctx context.Context, denomHash cmtbytes.HexBytes) bool { - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.DenomKey) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), types.DenomKey) return store.Has(denomHash) } // SetDenom sets a new {denom hash -> denom } pair to the store. // This allows for reverse lookup of the denom given the hash. func (k Keeper) SetDenom(ctx context.Context, denom types.Denom) { - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.DenomKey) - bz := k.cdc.MustMarshal(&denom) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), types.DenomKey) + bz := k.Cdc.MustMarshal(&denom) store.Set(denom.Hash(), bz) } @@ -189,13 +183,13 @@ func (k Keeper) GetAllDenoms(ctx context.Context) types.Denoms { // IterateDenoms iterates over the denominations in the store and performs a callback function. func (k Keeper) IterateDenoms(ctx context.Context, cb func(denom types.Denom) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.DenomKey) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var denom types.Denom - k.cdc.MustUnmarshal(iterator.Value(), &denom) + k.Cdc.MustUnmarshal(iterator.Value(), &denom) if cb(denom) { break @@ -231,7 +225,7 @@ func (k Keeper) setDenomMetadata(ctx context.Context, denom types.Denom) { // NOTE: if there is no value stored in state for the provided denom then a new Coin is returned for the denom with an initial value of zero. // This accommodates callers to simply call `Add()` on the returned Coin as an empty Coin literal (e.g. sdk.Coin{}) will trigger a panic due to the absence of a denom. func (k Keeper) GetTotalEscrowForDenom(ctx context.Context, denom string) sdk.Coin { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(types.TotalEscrowForDenomKey(denom)) if err != nil { panic(err) @@ -256,7 +250,7 @@ func (k Keeper) SetTotalEscrowForDenom(ctx context.Context, coin sdk.Coin) { panic(fmt.Errorf("amount cannot be negative: %s", coin.Amount)) } - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := types.TotalEscrowForDenomKey(coin.Denom) if coin.Amount.IsZero() { @@ -290,10 +284,10 @@ func (k Keeper) GetAllTotalEscrowed(ctx context.Context) sdk.Coins { // and performs a callback function. Denominations for which an invalid value // (i.e. not integer) is stored, will be skipped. func (k Keeper) IterateTokensInEscrow(ctx context.Context, storeprefix []byte, cb func(denomEscrow sdk.Coin) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, storeprefix) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { denom := strings.TrimPrefix(string(iterator.Key()), fmt.Sprintf("%s/", types.KeyTotalEscrowPrefix)) if strings.TrimSpace(denom) == "" { @@ -314,8 +308,8 @@ func (k Keeper) IterateTokensInEscrow(ctx context.Context, storeprefix []byte, c // setForwardedPacket sets the forwarded packet in the store. func (k Keeper) setForwardedPacket(ctx context.Context, portID, channelID string, sequence uint64, packet channeltypes.Packet) { - store := k.storeService.OpenKVStore(ctx) - bz := k.cdc.MustMarshal(&packet) + store := k.KVStoreService.OpenKVStore(ctx) + bz := k.Cdc.MustMarshal(&packet) if err := store.Set(types.PacketForwardKey(portID, channelID, sequence), bz); err != nil { panic(err) } @@ -323,7 +317,7 @@ func (k Keeper) setForwardedPacket(ctx context.Context, portID, channelID string // getForwardedPacket gets the forwarded packet from the store. func (k Keeper) getForwardedPacket(ctx context.Context, portID, channelID string, sequence uint64) (channeltypes.Packet, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(types.PacketForwardKey(portID, channelID, sequence)) if err != nil { panic(err) @@ -333,14 +327,14 @@ func (k Keeper) getForwardedPacket(ctx context.Context, portID, channelID string } var storedPacket channeltypes.Packet - k.cdc.MustUnmarshal(bz, &storedPacket) + k.Cdc.MustUnmarshal(bz, &storedPacket) return storedPacket, true } // deleteForwardedPacket deletes the forwarded packet from the store. func (k Keeper) deleteForwardedPacket(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) packetKey := types.PacketForwardKey(portID, channelID, sequence) if err := store.Delete(packetKey); err != nil { @@ -361,13 +355,13 @@ func (k Keeper) getAllForwardedPackets(ctx context.Context) []types.ForwardedPac // iterateForwardedPackets iterates over the forward packets in the store and performs a callback function. func (k Keeper) iterateForwardedPackets(ctx context.Context, cb func(packet types.ForwardedPacket) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.ForwardedPacketKey) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var forwardPacket types.ForwardedPacket - k.cdc.MustUnmarshal(iterator.Value(), &forwardPacket.Packet) + k.Cdc.MustUnmarshal(iterator.Value(), &forwardPacket.Packet) // Iterator key consists of types.ForwardedPacketKey/portID/channelID/sequence parts := strings.Split(string(iterator.Key()), "/") diff --git a/modules/apps/transfer/keeper/keeper_test.go b/modules/apps/transfer/keeper/keeper_test.go index 1ace8029507..0e7589d3596 100644 --- a/modules/apps/transfer/keeper/keeper_test.go +++ b/modules/apps/transfer/keeper/keeper_test.go @@ -6,12 +6,12 @@ import ( testifysuite "github.com/stretchr/testify/suite" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" minttypes "cosmossdk.io/x/mint/types" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" @@ -192,7 +192,6 @@ func (suite *KeeperTestSuite) TestSetGetTotalEscrowForDenom() { func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { var ( store storetypes.KVStore - cdc codec.Codec expDenomEscrows sdk.Coins ) @@ -208,7 +207,8 @@ func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { amount := sdkmath.NewInt(100) expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) - bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + bz, err := math.Int(amount).Marshal() + suite.Require().NoError(err) store.Set(types.TotalEscrowForDenomKey(denom), bz) }, true, @@ -220,14 +220,16 @@ func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { amount := sdkmath.NewInt(100) expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) - bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + bz, err := math.Int(amount).Marshal() + suite.Require().NoError(err) store.Set(types.TotalEscrowForDenomKey(denom), bz) denom = "bar/foo" amount = sdkmath.NewInt(50) expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) - bz = cdc.MustMarshal(&sdk.IntProto{Int: amount}) + bz, err = math.Int(amount).Marshal() + suite.Require().NoError(err) store.Set(types.TotalEscrowForDenomKey(denom), bz) }, true, @@ -239,7 +241,8 @@ func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { amount := sdkmath.NewInt(100) expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) - bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + bz, err := math.Int(amount).Marshal() + suite.Require().NoError(err) store.Set(types.TotalEscrowForDenomKey(denom), bz) }, true, @@ -250,7 +253,8 @@ func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { denom := "" amount := sdkmath.ZeroInt() - bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + bz, err := math.Int(amount).Marshal() + suite.Require().NoError(err) store.Set(types.TotalEscrowForDenomKey(denom), bz) }, false, @@ -261,7 +265,8 @@ func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { denom := "uatom" amount := sdkmath.ZeroInt() - bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + bz, err := math.Int(amount).Marshal() + suite.Require().NoError(err) store.Set([]byte(fmt.Sprintf("wrong-prefix/%s", denom)), bz) }, false, diff --git a/modules/apps/transfer/keeper/migrations.go b/modules/apps/transfer/keeper/migrations.go index 94896fe5123..367b1103d30 100644 --- a/modules/apps/transfer/keeper/migrations.go +++ b/modules/apps/transfer/keeper/migrations.go @@ -35,7 +35,7 @@ func (m Migrator) MigrateParams(ctx sdk.Context) error { m.keeper.legacySubspace.GetParamSet(ctx, ¶ms) m.keeper.SetParams(ctx, params) - m.keeper.Logger(ctx).Info("successfully migrated transfer app self-manage params") + m.keeper.Logger.Info("successfully migrated transfer app self-manage params") return nil } @@ -50,7 +50,7 @@ func (m Migrator) MigrateDenomMetadata(ctx sdk.Context) error { return false }) - m.keeper.Logger(ctx).Info("successfully added metadata to IBC voucher denominations") + m.keeper.Logger.Info("successfully added metadata to IBC voucher denominations") return nil } @@ -71,7 +71,7 @@ func (m Migrator) MigrateTotalEscrowForDenom(ctx sdk.Context) error { m.keeper.SetTotalEscrowForDenom(ctx, totalEscrow) } - m.keeper.Logger(ctx).Info("successfully set total escrow", "number of denominations", totalEscrowed.Len()) + m.keeper.Logger.Info("successfully set total escrow", "number of denominations", totalEscrowed.Len()) return nil } @@ -117,28 +117,28 @@ func (m Migrator) MigrateDenomTraceToDenom(ctx sdk.Context) error { // setDenomTrace sets a new {trace hash -> denom trace} pair to the store. func (k Keeper) setDenomTrace(ctx context.Context, denomTrace internaltypes.DenomTrace) { - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.DenomTraceKey) - bz := k.cdc.MustMarshal(&denomTrace) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), types.DenomTraceKey) + bz := k.Cdc.MustMarshal(&denomTrace) store.Set(denomTrace.Hash(), bz) } // deleteDenomTrace deletes the denom trace func (k Keeper) deleteDenomTrace(ctx context.Context, denomTrace internaltypes.DenomTrace) { - store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.DenomTraceKey) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), types.DenomTraceKey) store.Delete(denomTrace.Hash()) } // iterateDenomTraces iterates over the denomination traces in the store // and performs a callback function. func (k Keeper) iterateDenomTraces(ctx context.Context, cb func(denomTrace internaltypes.DenomTrace) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.DenomTraceKey) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var denomTrace internaltypes.DenomTrace - k.cdc.MustUnmarshal(iterator.Value(), &denomTrace) + k.Cdc.MustUnmarshal(iterator.Value(), &denomTrace) if cb(denomTrace) { break diff --git a/modules/apps/transfer/keeper/msg_server.go b/modules/apps/transfer/keeper/msg_server.go index b0cb57398b7..148fde36841 100644 --- a/modules/apps/transfer/keeper/msg_server.go +++ b/modules/apps/transfer/keeper/msg_server.go @@ -15,8 +15,7 @@ import ( var _ types.MsgServer = (*Keeper)(nil) // Transfer defines an rpc handler method for MsgTransfer. -func (k Keeper) Transfer(goCtx context.Context, msg *types.MsgTransfer) (*types.MsgTransferResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) +func (k Keeper) Transfer(ctx context.Context, msg *types.MsgTransfer) (*types.MsgTransferResponse, error) { if !k.GetParams(ctx).SendEnabled { return nil, types.ErrSendDisabled @@ -51,7 +50,7 @@ func (k Keeper) Transfer(goCtx context.Context, msg *types.MsgTransfer) (*types. return nil, err } - k.Logger(ctx).Info("IBC fungible token transfer", "tokens", coins, "sender", msg.Sender, "receiver", msg.Receiver) + k.Logger.Info("IBC fungible token transfer", "tokens", coins, "sender", msg.Sender, "receiver", msg.Receiver) return &types.MsgTransferResponse{Sequence: sequence}, nil } @@ -71,7 +70,7 @@ func (k Keeper) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) // unwindHops unwinds the hops present in the tokens denomination and returns the message modified to reflect // the unwound path to take. It assumes that only a single token is present (as this is verified in ValidateBasic) // in the tokens list and ensures that the token is not native to the chain. -func (k Keeper) unwindHops(ctx sdk.Context, msg *types.MsgTransfer) (*types.MsgTransfer, error) { +func (k Keeper) unwindHops(ctx context.Context, msg *types.MsgTransfer) (*types.MsgTransfer, error) { unwindHops, err := k.getUnwindHops(ctx, msg.GetCoins()) if err != nil { return nil, err @@ -92,7 +91,7 @@ func (k Keeper) unwindHops(ctx sdk.Context, msg *types.MsgTransfer) (*types.MsgT // getUnwindHops returns the hops to be used during unwinding. If coins consists of more than // one coin, all coins must have the exact same trace, else an error is returned. getUnwindHops // also validates that the coins are not native to the chain. -func (k Keeper) getUnwindHops(ctx sdk.Context, coins sdk.Coins) ([]types.Hop, error) { +func (k Keeper) getUnwindHops(ctx context.Context, coins sdk.Coins) ([]types.Hop, error) { // Sanity: validation for MsgTransfer ensures coins are not empty. if len(coins) == 0 { return nil, errorsmod.Wrap(types.ErrInvalidForwarding, "coins cannot be empty") diff --git a/modules/apps/transfer/keeper/relay.go b/modules/apps/transfer/keeper/relay.go index 71ef740132c..6b1c37384bc 100644 --- a/modules/apps/transfer/keeper/relay.go +++ b/modules/apps/transfer/keeper/relay.go @@ -52,7 +52,7 @@ import ( // 5. C -> B : sender chain is sink zone. Denom upon receiving: 'B/denom' // 6. B -> A : sender chain is sink zone. Denom upon receiving: 'denom' func (k Keeper) sendTransfer( - ctx sdk.Context, + ctx context.Context, sourcePort, sourceChannel string, coins sdk.Coins, @@ -419,7 +419,7 @@ func (k Keeper) unescrowCoin(ctx context.Context, escrowAddress, receiver sdk.Ac } // tokenFromCoin constructs an IBC token given an SDK coin. -func (k Keeper) tokenFromCoin(ctx sdk.Context, coin sdk.Coin) (types.Token, error) { +func (k Keeper) tokenFromCoin(ctx context.Context, coin sdk.Coin) (types.Token, error) { // if the coin does not have an IBC denom, return as is if !strings.HasPrefix(coin.Denom, "ibc/") { return types.Token{ diff --git a/modules/apps/transfer/module.go b/modules/apps/transfer/module.go index 095c7d49685..42becbf9396 100644 --- a/modules/apps/transfer/module.go +++ b/modules/apps/transfer/module.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/registry" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -25,22 +26,23 @@ import ( ) var ( - _ module.AppModule = (*AppModule)(nil) - _ module.AppModuleBasic = (*AppModuleBasic)(nil) - _ module.AppModuleSimulation = (*AppModule)(nil) - _ module.HasGenesis = (*AppModule)(nil) - _ module.HasName = (*AppModule)(nil) - _ module.HasConsensusVersion = (*AppModule)(nil) - _ module.HasInvariants = (*AppModule)(nil) - _ module.HasServices = (*AppModule)(nil) - _ module.HasProposalMsgs = (*AppModule)(nil) - _ appmodule.AppModule = (*AppModule)(nil) + _ module.AppModule = (*AppModule)(nil) + _ module.AppModuleBasic = (*AppModuleBasic)(nil) + _ module.AppModuleSimulation = (*AppModule)(nil) + _ module.HasGenesis = (*AppModule)(nil) + _ appmodule.HasConsensusVersion = (*AppModule)(nil) + _ module.HasInvariants = (*AppModule)(nil) + _ module.HasServices = (*AppModule)(nil) + _ module.HasProposalMsgs = (*AppModule)(nil) + _ appmodule.AppModule = (*AppModule)(nil) _ porttypes.IBCModule = (*IBCModule)(nil) ) // AppModuleBasic is the IBC Transfer AppModuleBasic -type AppModuleBasic struct{} +type AppModuleBasic struct { + cdc codec.Codec +} // Name implements AppModuleBasic interface func (AppModuleBasic) Name() string { @@ -54,7 +56,7 @@ func (AppModule) IsOnePerModuleType() {} func (AppModule) IsAppModule() {} // RegisterLegacyAminoCodec implements AppModuleBasic interface -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc registry.AminoRegistrar) { types.RegisterLegacyAminoCodec(cdc) } @@ -65,14 +67,14 @@ func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) // DefaultGenesis returns default genesis state as raw bytes for the ibc // transfer module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModuleBasic) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the ibc transfer module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var gs types.GenesisState - if err := cdc.UnmarshalJSON(bz, &gs); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &gs); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -107,9 +109,12 @@ type AppModule struct { } // NewAppModule creates a new 20-transfer module -func NewAppModule(k keeper.Keeper) AppModule { +func NewAppModule(k keeper.Keeper, cdc codec.Codec) AppModule { return AppModule{ keeper: k, + AppModuleBasic: AppModuleBasic{ + cdc: cdc, + }, } } @@ -144,17 +149,22 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { // InitGenesis performs genesis initialization for the ibc-transfer module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return am.keeper.InitGenesis(ctx, genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the ibc-transfer // module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs, err := am.keeper.ExportGenesis(ctx) + if err != nil { + return nil, err + } + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements AppModule/ConsensusVersion defining the current version of transfer. diff --git a/modules/apps/transfer/types/codec.go b/modules/apps/transfer/types/codec.go index 58d37e61112..51f4b2c1a28 100644 --- a/modules/apps/transfer/types/codec.go +++ b/modules/apps/transfer/types/codec.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/core/registry" "cosmossdk.io/x/authz" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" @@ -11,7 +12,7 @@ import ( // RegisterLegacyAminoCodec registers the necessary x/ibc transfer interfaces and concrete types // on the provided LegacyAmino codec. These types are used for Amino JSON serialization. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func RegisterLegacyAminoCodec(cdc registry.AminoRegistrar) { legacy.RegisterAminoMsg(cdc, &MsgTransfer{}, "cosmos-sdk/MsgTransfer") } diff --git a/modules/apps/transfer/types/msgs_test.go b/modules/apps/transfer/types/msgs_test.go index b68fb92e7cf..7c2f070b353 100644 --- a/modules/apps/transfer/types/msgs_test.go +++ b/modules/apps/transfer/types/msgs_test.go @@ -113,7 +113,7 @@ func TestMsgTransferGetSigners(t *testing.T) { msg := types.NewMsgTransfer(validPort, validChannel, coins, addr.String(), receiver, timeoutHeight, 0, "", nil) encodingCfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, transfer.AppModule{}) - signers, _, err := encodingCfg.Codec.GetMsgV1Signers(msg) + signers, _, err := encodingCfg.Codec.GetMsgSigners(msg) require.NoError(t, err) require.Equal(t, addr.Bytes(), signers[0]) } @@ -163,7 +163,7 @@ func TestMsgUpdateParamsGetSigners(t *testing.T) { } encodingCfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, transfer.AppModule{}) - signers, _, err := encodingCfg.Codec.GetMsgV1Signers(&msg) + signers, _, err := encodingCfg.Codec.GetMsgSigners(&msg) if tc.errMsg == "" { require.NoError(t, err) diff --git a/modules/core/02-client/abci.go b/modules/core/02-client/abci.go index 1b582a36e93..ed048962399 100644 --- a/modules/core/02-client/abci.go +++ b/modules/core/02-client/abci.go @@ -1,7 +1,7 @@ package client import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "context" "github.com/cosmos/ibc-go/v9/modules/core/02-client/keeper" "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -9,7 +9,7 @@ import ( ) // BeginBlocker is used to perform IBC client upgrades -func BeginBlocker(ctx sdk.Context, k *keeper.Keeper) { +func BeginBlocker(ctx context.Context, k *keeper.Keeper) { plan, err := k.GetUpgradePlan(ctx) if err == nil { // Once we are at the last block this chain will commit, set the upgraded consensus state @@ -19,17 +19,18 @@ func BeginBlocker(ctx sdk.Context, k *keeper.Keeper) { // In order for a client to upgrade successfully, the first block of the new chain must be committed // within the trusting period of the last block time on this chain. _, err := k.GetUpgradedClient(ctx, plan.Height) - if err == nil && ctx.BlockHeight() == plan.Height-1 { + hi := k.HeaderService.HeaderInfo(ctx) + if err == nil && hi.Height == plan.Height-1 { upgradedConsState := &ibctm.ConsensusState{ - Timestamp: ctx.BlockTime(), - NextValidatorsHash: ctx.BlockHeader().NextValidatorsHash, + Timestamp: hi.Time, + NextValidatorsHash: ctx.NextValidatorsHash, //TODO: need to pass the consensus modules blocked on https://github.com/cosmos/cosmos-sdk/pull/21480 } bz := types.MustMarshalConsensusState(k.Codec(), upgradedConsState) // SetUpgradedConsensusState always returns nil, hence the blank here. _ = k.SetUpgradedConsensusState(ctx, plan.Height, bz) - keeper.EmitUpgradeChainEvent(ctx, plan.Height) + keeper.EmitUpgradeChainEvent(ctx, k.Environment, plan.Height) } } } diff --git a/modules/core/02-client/keeper/client.go b/modules/core/02-client/keeper/client.go index 422fca31ba3..5cb2d5add40 100644 --- a/modules/core/02-client/keeper/client.go +++ b/modules/core/02-client/keeper/client.go @@ -36,10 +36,10 @@ func (k *Keeper) CreateClient(ctx sdk.Context, clientType string, clientState, c } initialHeight := clientModule.LatestHeight(ctx, clientID) - k.Logger(ctx).Info("client created at height", "client-id", clientID, "height", initialHeight.String()) + k.Logger.Info("client created at height", "client-id", clientID, "height", initialHeight.String()) defer telemetry.ReportCreateClient(clientType) - emitCreateClientEvent(ctx, clientID, clientType, initialHeight) + emitCreateClientEvent(ctx, k.Environment, clientID, clientType, initialHeight) return clientID, nil } @@ -63,22 +63,22 @@ func (k *Keeper) UpdateClient(ctx sdk.Context, clientID string, clientMsg export if foundMisbehaviour { clientModule.UpdateStateOnMisbehaviour(ctx, clientID, clientMsg) - k.Logger(ctx).Info("client frozen due to misbehaviour", "client-id", clientID) + k.Logger.Info("client frozen due to misbehaviour", "client-id", clientID) clientType := types.MustParseClientIdentifier(clientID) defer telemetry.ReportUpdateClient(foundMisbehaviour, clientType, clientID) - emitSubmitMisbehaviourEvent(ctx, clientID, clientType) + emitSubmitMisbehaviourEvent(ctx, k.Environment, clientID, clientType) return nil } consensusHeights := clientModule.UpdateState(ctx, clientID, clientMsg) - k.Logger(ctx).Info("client state updated", "client-id", clientID, "heights", consensusHeights) + k.Logger.Info("client state updated", "client-id", clientID, "heights", consensusHeights) clientType := types.MustParseClientIdentifier(clientID) defer telemetry.ReportUpdateClient(foundMisbehaviour, clientType, clientID) - emitUpdateClientEvent(ctx, clientID, clientType, consensusHeights, k.cdc, clientMsg) + emitUpdateClientEvent(ctx, k.Environment, clientID, clientType, consensusHeights, k.cdc, clientMsg) return nil } @@ -104,11 +104,11 @@ func (k *Keeper) UpgradeClient( } latestHeight := clientModule.LatestHeight(ctx, clientID) - k.Logger(ctx).Info("client state upgraded", "client-id", clientID, "height", latestHeight.String()) + k.Logger.Info("client state upgraded", "client-id", clientID, "height", latestHeight.String()) clientType := types.MustParseClientIdentifier(clientID) defer telemetry.ReportUpgradeClient(clientType, clientID) - emitUpgradeClientEvent(ctx, clientID, clientType, latestHeight) + emitUpgradeClientEvent(ctx, k.Environment, clientID, clientType, latestHeight) return nil } @@ -142,11 +142,11 @@ func (k *Keeper) RecoverClient(ctx sdk.Context, subjectClientID, substituteClien return err } - k.Logger(ctx).Info("client recovered", "client-id", subjectClientID) + k.Logger.Info("client recovered", "client-id", subjectClientID) clientType := types.MustParseClientIdentifier(subjectClientID) defer telemetry.ReportRecoverClient(clientType, subjectClientID) - emitRecoverClientEvent(ctx, subjectClientID, clientType) + emitRecoverClientEvent(ctx, k.Environment, subjectClientID, clientType) return nil } diff --git a/modules/core/02-client/keeper/events.go b/modules/core/02-client/keeper/events.go index 6727ede5b7a..ec9d27fef83 100644 --- a/modules/core/02-client/keeper/events.go +++ b/modules/core/02-client/keeper/events.go @@ -1,10 +1,13 @@ package keeper import ( + "context" "fmt" "strconv" "strings" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" upgradetypes "cosmossdk.io/x/upgrade/types" "github.com/cosmos/cosmos-sdk/codec" @@ -15,23 +18,21 @@ import ( ) // emitCreateClientEvent emits a create client event -func emitCreateClientEvent(ctx sdk.Context, clientID, clientType string, initialHeight exported.Height) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeCreateClient, - sdk.NewAttribute(types.AttributeKeyClientID, clientID), - sdk.NewAttribute(types.AttributeKeyClientType, clientType), - sdk.NewAttribute(types.AttributeKeyConsensusHeight, initialHeight.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) +func emitCreateClientEvent(ctx context.Context, env appmodule.Environment, clientID, clientType string, initialHeight exported.Height) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeCreateClient, + event.Attribute{Key: types.AttributeKeyClientID, Value: clientID}, + event.Attribute{Key: types.AttributeKeyClientType, Value: clientType}, + event.Attribute{Key: types.AttributeKeyConsensusHeight, Value: initialHeight.String()}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } // emitUpdateClientEvent emits an update client event -func emitUpdateClientEvent(ctx sdk.Context, clientID string, clientType string, consensusHeights []exported.Height, _ codec.BinaryCodec, _ exported.ClientMessage) { +func emitUpdateClientEvent(ctx context.Context, env appmodule.Environment, clientID string, clientType string, consensusHeights []exported.Height, _ codec.BinaryCodec, _ exported.ClientMessage) { var consensusHeightAttr string if len(consensusHeights) != 0 { consensusHeightAttr = consensusHeights[0].String() @@ -42,95 +43,84 @@ func emitUpdateClientEvent(ctx sdk.Context, clientID string, clientType string, consensusHeightsAttr[i] = height.String() } - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeUpdateClient, - sdk.NewAttribute(types.AttributeKeyClientID, clientID), - sdk.NewAttribute(types.AttributeKeyClientType, clientType), - // Deprecated: AttributeKeyConsensusHeight is deprecated and will be removed in a future release. - // Please use AttributeKeyConsensusHeights instead. - sdk.NewAttribute(types.AttributeKeyConsensusHeight, consensusHeightAttr), - sdk.NewAttribute(types.AttributeKeyConsensusHeights, strings.Join(consensusHeightsAttr, ",")), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeUpdateClient, + event.Attribute{Key: types.AttributeKeyClientID, Value: clientID}, + event.Attribute{Key: types.AttributeKeyClientType, Value: clientType}, + // Deprecated: AttributeKeyConsensusHeight is deprecated and will be removed in a future release. + // Please use AttributeKeyConsensusHeights instead. + event.Attribute{Key: types.AttributeKeyConsensusHeight, Value: consensusHeightAttr}, + event.Attribute{Key: types.AttributeKeyConsensusHeights, Value: strings.Join(consensusHeightsAttr, ",")}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } // emitUpgradeClientEvent emits an upgrade client event -func emitUpgradeClientEvent(ctx sdk.Context, clientID, clientType string, latestHeight exported.Height) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeUpgradeClient, - sdk.NewAttribute(types.AttributeKeyClientID, clientID), - sdk.NewAttribute(types.AttributeKeyClientType, clientType), - sdk.NewAttribute(types.AttributeKeyConsensusHeight, latestHeight.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) +func emitUpgradeClientEvent(ctx context.Context, env appmodule.Environment, clientID, clientType string, latestHeight exported.Height) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeUpgradeClient, + event.Attribute{Key: types.AttributeKeyClientID, Value: clientID}, + event.Attribute{Key: types.AttributeKeyClientType, Value: clientType}, + event.Attribute{Key: types.AttributeKeyConsensusHeight, Value: latestHeight.String()}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } // emitSubmitMisbehaviourEvent emits a client misbehaviour event -func emitSubmitMisbehaviourEvent(ctx sdk.Context, clientID string, clientType string) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeSubmitMisbehaviour, - sdk.NewAttribute(types.AttributeKeyClientID, clientID), - sdk.NewAttribute(types.AttributeKeyClientType, clientType), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) +func emitSubmitMisbehaviourEvent(ctx context.Context, env appmodule.Environment, clientID string, clientType string) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeSubmitMisbehaviour, + event.Attribute{Key: types.AttributeKeyClientID, Value: clientID}, + event.Attribute{Key: types.AttributeKeyClientType, Value: clientType}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } // emitRecoverClientEvent emits a recover client event -func emitRecoverClientEvent(ctx sdk.Context, clientID, clientType string) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeRecoverClient, - sdk.NewAttribute(types.AttributeKeySubjectClientID, clientID), - sdk.NewAttribute(types.AttributeKeyClientType, clientType), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) +func emitRecoverClientEvent(ctx context.Context, env appmodule.Environment, clientID, clientType string) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeRecoverClient, + event.Attribute{Key: types.AttributeKeySubjectClientID, Value: clientID}, + event.Attribute{Key: types.AttributeKeyClientType, Value: clientType}, + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } // emitScheduleIBCSoftwareUpgradeEvent emits a schedule IBC software upgrade event -func emitScheduleIBCSoftwareUpgradeEvent(ctx sdk.Context, title string, height int64) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeScheduleIBCSoftwareUpgrade, - sdk.NewAttribute(types.AttributeKeyUpgradePlanTitle, title), - sdk.NewAttribute(types.AttributeKeyUpgradePlanHeight, fmt.Sprintf("%d", height)), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) +func emitScheduleIBCSoftwareUpgradeEvent(ctx context.Context, env appmodule.Environment, title string, height int64) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeScheduleIBCSoftwareUpgrade, + event.Attribute{Key: types.AttributeKeyUpgradePlanTitle, Value: title}, + event.Attribute{Key: types.AttributeKeyUpgradePlanHeight, Value: fmt.Sprintf("%d", height)}, + ) + env.EventService.EventManager(ctx).EmitKV( + + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } // EmitUpgradeChainEvent emits an upgrade chain event. -func EmitUpgradeChainEvent(ctx sdk.Context, height int64) { - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeUpgradeChain, - sdk.NewAttribute(types.AttributeKeyUpgradePlanHeight, strconv.FormatInt(height, 10)), - sdk.NewAttribute(types.AttributeKeyUpgradeStore, upgradetypes.StoreKey), // which store to query proof of consensus state from - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - ), - }) +func EmitUpgradeChainEvent(ctx context.Context, env appmodule.Environment, height int64) { + env.EventService.EventManager(ctx).EmitKV( + types.EventTypeUpgradeChain, + event.Attribute{Key: types.AttributeKeyUpgradePlanHeight, Value: strconv.FormatInt(height, 10)}, + event.Attribute{Key: types.AttributeKeyUpgradeStore, Value: upgradetypes.StoreKey}, // which store to query proof of consensus state from + ) + env.EventService.EventManager(ctx).EmitKV( + sdk.EventTypeMessage, + event.Attribute{Key: sdk.AttributeKeyModule, Value: types.AttributeValueCategory}, + ) } diff --git a/modules/core/02-client/keeper/grpc_query.go b/modules/core/02-client/keeper/grpc_query.go index e0dafbd3294..ea566656f88 100644 --- a/modules/core/02-client/keeper/grpc_query.go +++ b/modules/core/02-client/keeper/grpc_query.go @@ -39,7 +39,7 @@ func NewQueryServer(k *Keeper) types.QueryServer { } // ClientState implements the Query/ClientState gRPC method -func (q *queryServer) ClientState(c context.Context, req *types.QueryClientStateRequest) (*types.QueryClientStateResponse, error) { +func (q *queryServer) ClientState(ctx context.Context, req *types.QueryClientStateRequest) (*types.QueryClientStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -48,7 +48,6 @@ func (q *queryServer) ClientState(c context.Context, req *types.QueryClientState return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) clientState, found := q.GetClientState(ctx, req.ClientId) if !found { return nil, status.Error( @@ -70,15 +69,13 @@ func (q *queryServer) ClientState(c context.Context, req *types.QueryClientState } // ClientStates implements the Query/ClientStates gRPC method -func (q *queryServer) ClientStates(c context.Context, req *types.QueryClientStatesRequest) (*types.QueryClientStatesResponse, error) { +func (q *queryServer) ClientStates(ctx context.Context, req *types.QueryClientStatesRequest) (*types.QueryClientStatesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(c) - var clientStates types.IdentifiedClientStates - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.KeyClientStorePrefix) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), host.KeyClientStorePrefix) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // filter any metadata stored under client state key @@ -114,7 +111,7 @@ func (q *queryServer) ClientStates(c context.Context, req *types.QueryClientStat } // ConsensusState implements the Query/ConsensusState gRPC method -func (q *queryServer) ConsensusState(c context.Context, req *types.QueryConsensusStateRequest) (*types.QueryConsensusStateResponse, error) { +func (q *queryServer) ConsensusState(ctx context.Context, req *types.QueryConsensusStateRequest) (*types.QueryConsensusStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -123,8 +120,6 @@ func (q *queryServer) ConsensusState(c context.Context, req *types.QueryConsensu return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) - var ( consensusState exported.ConsensusState found bool @@ -161,7 +156,7 @@ func (q *queryServer) ConsensusState(c context.Context, req *types.QueryConsensu } // ConsensusStates implements the Query/ConsensusStates gRPC method -func (q *queryServer) ConsensusStates(c context.Context, req *types.QueryConsensusStatesRequest) (*types.QueryConsensusStatesResponse, error) { +func (q *queryServer) ConsensusStates(ctx context.Context, req *types.QueryConsensusStatesRequest) (*types.QueryConsensusStatesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -170,10 +165,8 @@ func (q *queryServer) ConsensusStates(c context.Context, req *types.QueryConsens return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) - var consensusStates []types.ConsensusStateWithHeight - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // filter any metadata stored under consensus state key @@ -205,7 +198,7 @@ func (q *queryServer) ConsensusStates(c context.Context, req *types.QueryConsens } // ConsensusStateHeights implements the Query/ConsensusStateHeights gRPC method -func (q *queryServer) ConsensusStateHeights(c context.Context, req *types.QueryConsensusStateHeightsRequest) (*types.QueryConsensusStateHeightsResponse, error) { +func (q *queryServer) ConsensusStateHeights(ctx context.Context, req *types.QueryConsensusStateHeightsRequest) (*types.QueryConsensusStateHeightsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -214,10 +207,8 @@ func (q *queryServer) ConsensusStateHeights(c context.Context, req *types.QueryC return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) - var consensusStateHeights []types.Height - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) { // filter any metadata stored under consensus state key @@ -244,7 +235,7 @@ func (q *queryServer) ConsensusStateHeights(c context.Context, req *types.QueryC } // ClientStatus implements the Query/ClientStatus gRPC method -func (q *queryServer) ClientStatus(c context.Context, req *types.QueryClientStatusRequest) (*types.QueryClientStatusResponse, error) { +func (q *queryServer) ClientStatus(ctx context.Context, req *types.QueryClientStatusRequest) (*types.QueryClientStatusResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -253,7 +244,6 @@ func (q *queryServer) ClientStatus(c context.Context, req *types.QueryClientStat return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) clientStatus := q.GetClientStatus(ctx, req.ClientId) return &types.QueryClientStatusResponse{ @@ -262,8 +252,7 @@ func (q *queryServer) ClientStatus(c context.Context, req *types.QueryClientStat } // ClientParams implements the Query/ClientParams gRPC method -func (q *queryServer) ClientParams(c context.Context, _ *types.QueryClientParamsRequest) (*types.QueryClientParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) +func (q *queryServer) ClientParams(ctx context.Context, _ *types.QueryClientParamsRequest) (*types.QueryClientParamsResponse, error) { params := q.GetParams(ctx) return &types.QueryClientParamsResponse{ @@ -272,13 +261,11 @@ func (q *queryServer) ClientParams(c context.Context, _ *types.QueryClientParams } // UpgradedClientState implements the Query/UpgradedClientState gRPC method -func (q *queryServer) UpgradedClientState(c context.Context, req *types.QueryUpgradedClientStateRequest) (*types.QueryUpgradedClientStateResponse, error) { +func (q *queryServer) UpgradedClientState(ctx context.Context, req *types.QueryUpgradedClientStateRequest) (*types.QueryUpgradedClientStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(c) - plan, err := q.GetUpgradePlan(ctx) if err != nil { return nil, status.Error(codes.NotFound, err.Error()) @@ -307,16 +294,16 @@ func (q *queryServer) UpgradedClientState(c context.Context, req *types.QueryUpg } // UpgradedConsensusState implements the Query/UpgradedConsensusState gRPC method -func (q *queryServer) UpgradedConsensusState(c context.Context, req *types.QueryUpgradedConsensusStateRequest) (*types.QueryUpgradedConsensusStateResponse, error) { +func (q *queryServer) UpgradedConsensusState(ctx context.Context, req *types.QueryUpgradedConsensusStateRequest) (*types.QueryUpgradedConsensusStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(c) + height := q.HeaderService.HeaderInfo(ctx).Height - bz, err := q.GetUpgradedConsensusState(ctx, ctx.BlockHeight()) + bz, err := q.GetUpgradedConsensusState(ctx, height) if err != nil { - return nil, status.Errorf(codes.NotFound, "%s, height %d", err.Error(), ctx.BlockHeight()) + return nil, status.Errorf(codes.NotFound, "%s, height %d", err.Error(), height) } consensusState, err := types.UnmarshalConsensusState(q.cdc, bz) @@ -401,7 +388,7 @@ func (q *queryServer) VerifyMembership(c context.Context, req *types.QueryVerify ) if err := clientModule.VerifyMembership(cachedCtx, req.ClientId, req.ProofHeight, req.TimeDelay, req.BlockDelay, req.Proof, req.MerklePath, req.Value); err != nil { - q.Logger(ctx).Debug("proof verification failed", "key", req.MerklePath, "error", err) + q.Logger.Debug("proof verification failed", "key", req.MerklePath, "error", err) return &types.QueryVerifyMembershipResponse{ Success: false, }, nil diff --git a/modules/core/02-client/keeper/keeper.go b/modules/core/02-client/keeper/keeper.go index a921b8fc98f..016dba5a43b 100644 --- a/modules/core/02-client/keeper/keeper.go +++ b/modules/core/02-client/keeper/keeper.go @@ -6,9 +6,8 @@ import ( "fmt" "strings" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" upgradetypes "cosmossdk.io/x/upgrade/types" @@ -28,7 +27,7 @@ import ( // Keeper represents a type that grants read and write permissions to any client // state information type Keeper struct { - storeService corestore.KVStoreService + appmodule.Environment cdc codec.BinaryCodec router *types.Router legacySubspace types.ParamSubspace @@ -36,13 +35,13 @@ type Keeper struct { } // NewKeeper creates a new NewKeeper instance -func NewKeeper(cdc codec.BinaryCodec, storeService corestore.KVStoreService, legacySubspace types.ParamSubspace, uk types.UpgradeKeeper) *Keeper { +func NewKeeper(cdc codec.BinaryCodec, env appmodule.Environment, legacySubspace types.ParamSubspace, uk types.UpgradeKeeper) *Keeper { router := types.NewRouter() - localhostModule := localhost.NewLightClientModule(cdc, storeService) + localhostModule := localhost.NewLightClientModule(cdc, env) router.AddRoute(exported.Localhost, localhostModule) return &Keeper{ - storeService: storeService, + Environment: env, cdc: cdc, router: router, legacySubspace: legacySubspace, @@ -55,11 +54,11 @@ func (k *Keeper) Codec() codec.BinaryCodec { return k.cdc } -// Logger returns a module-specific logger. -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) -} +// // Logger returns a module-specific logger. +// func (Keeper) Logger(ctx context.Context) log.Logger { +// sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 +// return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +// } // AddRoute adds a new route to the underlying router. func (k *Keeper) AddRoute(clientType string, module exported.LightClientModule) { @@ -68,7 +67,7 @@ func (k *Keeper) AddRoute(clientType string, module exported.LightClientModule) // GetStoreProvider returns the light client store provider. func (k *Keeper) GetStoreProvider() types.StoreProvider { - return types.NewStoreProvider(k.storeService) + return types.NewStoreProvider(k.KVStoreService) } // Route returns the light client module for the given client identifier. @@ -142,7 +141,7 @@ func (k *Keeper) SetClientConsensusState(ctx context.Context, clientID string, h // GetNextClientSequence gets the next client sequence from the store. func (k *Keeper) GetNextClientSequence(ctx context.Context) uint64 { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.KeyNextClientSequence)) if err != nil { panic(err) @@ -156,7 +155,7 @@ func (k *Keeper) GetNextClientSequence(ctx context.Context) uint64 { // SetNextClientSequence sets the next client sequence to the store. func (k *Keeper) SetNextClientSequence(ctx context.Context, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set([]byte(types.KeyNextClientSequence), bz); err != nil { panic(err) @@ -167,10 +166,10 @@ func (k *Keeper) SetNextClientSequence(ctx context.Context, sequence uint64) { // objects. For each State object, cb will be called. If the cb returns true, // the iterator will close and stop. func (k *Keeper) IterateConsensusStates(ctx context.Context, cb func(clientID string, cs types.ConsensusStateWithHeight) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.KeyClientStorePrefix) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { keySplit := strings.Split(string(iterator.Key()), "/") // consensus key is in the format "clients//consensusStates/" @@ -192,10 +191,10 @@ func (k *Keeper) IterateConsensusStates(ctx context.Context, cb func(clientID st // iterateMetadata provides an iterator over all stored metadata keys in the client store. // For each metadata object, it will perform a callback. func (k *Keeper) iterateMetadata(ctx context.Context, cb func(clientID string, key, value []byte) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.KeyClientStorePrefix) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { split := strings.Split(string(iterator.Key()), "/") if len(split) == 3 && split[2] == string(host.KeyClientState) { @@ -358,10 +357,10 @@ func (k *Keeper) SetUpgradedConsensusState(ctx context.Context, planHeight int64 // objects using the provided store prefix. For each ClientState object, cb will be called. If the cb returns true, // the iterator will close and stop. func (k *Keeper) IterateClientStates(ctx context.Context, storePrefix []byte, cb func(clientID string, cs exported.ClientState) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.PrefixedClientStoreKey(storePrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { path := string(iterator.Key()) if !strings.Contains(path, host.KeyClientState) { @@ -393,7 +392,7 @@ func (k *Keeper) GetAllClients(ctx context.Context) []exported.ClientState { // namespace without being able to read/write other client's data func (k *Keeper) ClientStore(ctx context.Context, clientID string) storetypes.KVStore { clientPrefix := []byte(fmt.Sprintf("%s/%s/", host.KeyClientStorePrefix, clientID)) - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) return prefix.NewStore(store, clientPrefix) } @@ -436,7 +435,7 @@ func (k *Keeper) GetClientTimestampAtHeight(ctx context.Context, clientID string // GetParams returns the total set of ibc-client parameters. func (k *Keeper) GetParams(ctx context.Context) types.Params { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.ParamsKey)) if err != nil { panic(err) @@ -452,7 +451,7 @@ func (k *Keeper) GetParams(ctx context.Context) types.Params { // SetParams sets the total set of ibc-client parameters. func (k *Keeper) SetParams(ctx context.Context, params types.Params) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) if err := store.Set([]byte(types.ParamsKey), bz); err != nil { panic(err) @@ -484,8 +483,7 @@ func (k *Keeper) ScheduleIBCSoftwareUpgrade(ctx context.Context, plan upgradetyp } // emitting an event for scheduling an upgrade plan - sdkContext := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - emitScheduleIBCSoftwareUpgradeEvent(sdkContext, plan.Name, plan.Height) + emitScheduleIBCSoftwareUpgradeEvent(ctx, k.Environment, plan.Name, plan.Height) return nil } diff --git a/modules/core/02-client/keeper/migrations.go b/modules/core/02-client/keeper/migrations.go index d39a756ed93..95d64b5e19b 100644 --- a/modules/core/02-client/keeper/migrations.go +++ b/modules/core/02-client/keeper/migrations.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/ibc-go/v9/modules/core/02-client/migrations/v7" + v7 "github.com/cosmos/ibc-go/v9/modules/core/02-client/migrations/v7" "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" host "github.com/cosmos/ibc-go/v9/modules/core/24-host" "github.com/cosmos/ibc-go/v9/modules/core/exported" @@ -26,7 +26,7 @@ func NewMigrator(keeper *Keeper) Migrator { // - removes the localhost client // - asserts that existing tendermint clients are properly registered on the chain codec func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v7.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc, m.keeper) + return v7.MigrateStore(ctx, m.keeper.KVStoreService, m.keeper.cdc, m.keeper) } // MigrateParams migrates from consensus version 4 to 5. @@ -40,7 +40,7 @@ func (m Migrator) MigrateParams(ctx sdk.Context) error { } m.keeper.SetParams(ctx, params) - m.keeper.Logger(ctx).Info("successfully migrated client to self-manage params") + m.keeper.Logger.Info("successfully migrated client to self-manage params") return nil } diff --git a/modules/core/03-connection/keeper/grpc_query.go b/modules/core/03-connection/keeper/grpc_query.go index 859b6125332..20788e3d6d2 100644 --- a/modules/core/03-connection/keeper/grpc_query.go +++ b/modules/core/03-connection/keeper/grpc_query.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/store/prefix" "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -34,7 +33,7 @@ func NewQueryServer(k *Keeper) types.QueryServer { } // Connection implements the Query/Connection gRPC method -func (q *queryServer) Connection(c context.Context, req *types.QueryConnectionRequest) (*types.QueryConnectionResponse, error) { +func (q *queryServer) Connection(ctx context.Context, req *types.QueryConnectionRequest) (*types.QueryConnectionResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -43,7 +42,6 @@ func (q *queryServer) Connection(c context.Context, req *types.QueryConnectionRe return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) connection, found := q.GetConnection(ctx, req.ConnectionId) if !found { return nil, status.Error( @@ -59,16 +57,14 @@ func (q *queryServer) Connection(c context.Context, req *types.QueryConnectionRe } // Connections implements the Query/Connections gRPC method -func (q *queryServer) Connections(c context.Context, req *types.QueryConnectionsRequest) (*types.QueryConnectionsResponse, error) { +func (q *queryServer) Connections(ctx context.Context, req *types.QueryConnectionsRequest) (*types.QueryConnectionsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(c) - var connections []*types.IdentifiedConnection - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), []byte(host.KeyConnectionPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), []byte(host.KeyConnectionPrefix)) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { var result types.ConnectionEnd @@ -97,7 +93,7 @@ func (q *queryServer) Connections(c context.Context, req *types.QueryConnections } // ClientConnections implements the Query/ClientConnections gRPC method -func (q *queryServer) ClientConnections(c context.Context, req *types.QueryClientConnectionsRequest) (*types.QueryClientConnectionsResponse, error) { +func (q *queryServer) ClientConnections(ctx context.Context, req *types.QueryClientConnectionsRequest) (*types.QueryClientConnectionsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -106,7 +102,6 @@ func (q *queryServer) ClientConnections(c context.Context, req *types.QueryClien return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) clientConnectionPaths, found := q.GetClientConnectionPaths(ctx, req.ClientId) if !found { return nil, status.Error( @@ -122,7 +117,7 @@ func (q *queryServer) ClientConnections(c context.Context, req *types.QueryClien } // ConnectionClientState implements the Query/ConnectionClientState gRPC method -func (q *queryServer) ConnectionClientState(c context.Context, req *types.QueryConnectionClientStateRequest) (*types.QueryConnectionClientStateResponse, error) { +func (q *queryServer) ConnectionClientState(ctx context.Context, req *types.QueryConnectionClientStateRequest) (*types.QueryConnectionClientStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -131,8 +126,6 @@ func (q *queryServer) ConnectionClientState(c context.Context, req *types.QueryC return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) - connection, found := q.GetConnection(ctx, req.ConnectionId) if !found { return nil, status.Error( @@ -156,7 +149,7 @@ func (q *queryServer) ConnectionClientState(c context.Context, req *types.QueryC } // ConnectionConsensusState implements the Query/ConnectionConsensusState gRPC method -func (q *queryServer) ConnectionConsensusState(c context.Context, req *types.QueryConnectionConsensusStateRequest) (*types.QueryConnectionConsensusStateResponse, error) { +func (q *queryServer) ConnectionConsensusState(ctx context.Context, req *types.QueryConnectionConsensusStateRequest) (*types.QueryConnectionConsensusStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -165,8 +158,6 @@ func (q *queryServer) ConnectionConsensusState(c context.Context, req *types.Que return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) - connection, found := q.GetConnection(ctx, req.ConnectionId) if !found { return nil, status.Error( @@ -194,8 +185,7 @@ func (q *queryServer) ConnectionConsensusState(c context.Context, req *types.Que } // ConnectionParams implements the Query/ConnectionParams gRPC method. -func (q *queryServer) ConnectionParams(c context.Context, req *types.QueryConnectionParamsRequest) (*types.QueryConnectionParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) +func (q *queryServer) ConnectionParams(ctx context.Context, req *types.QueryConnectionParamsRequest) (*types.QueryConnectionParamsResponse, error) { params := q.GetParams(ctx) return &types.QueryConnectionParamsResponse{ diff --git a/modules/core/03-connection/keeper/handshake.go b/modules/core/03-connection/keeper/handshake.go index 0b52d58991a..00eefa385fa 100644 --- a/modules/core/03-connection/keeper/handshake.go +++ b/modules/core/03-connection/keeper/handshake.go @@ -47,7 +47,7 @@ func (k *Keeper) ConnOpenInit( connection := types.NewConnectionEnd(types.INIT, clientID, counterparty, versions, delayPeriod) k.SetConnection(ctx, connectionID, connection) - k.Logger(ctx).Info("connection state updated", "connection-id", connectionID, "previous-state", types.UNINITIALIZED, "new-state", types.INIT) + k.Logger.Info("connection state updated", "connection-id", connectionID, "previous-state", types.UNINITIALIZED, "new-state", types.INIT) defer telemetry.IncrCounter(1, "ibc", "connection", "open-init") @@ -106,7 +106,7 @@ func (k *Keeper) ConnOpenTry( } k.SetConnection(ctx, connectionID, connection) - k.Logger(ctx).Info("connection state updated", "connection-id", connectionID, "previous-state", types.UNINITIALIZED, "new-state", types.TRYOPEN) + k.Logger.Info("connection state updated", "connection-id", connectionID, "previous-state", types.UNINITIALIZED, "new-state", types.TRYOPEN) defer telemetry.IncrCounter(1, "ibc", "connection", "open-try") @@ -161,7 +161,7 @@ func (k *Keeper) ConnOpenAck( return err } - k.Logger(ctx).Info("connection state updated", "connection-id", connectionID, "previous-state", types.INIT, "new-state", types.OPEN) + k.Logger.Info("connection state updated", "connection-id", connectionID, "previous-state", types.INIT, "new-state", types.OPEN) defer telemetry.IncrCounter(1, "ibc", "connection", "open-ack") @@ -215,7 +215,7 @@ func (k *Keeper) ConnOpenConfirm( // Update ChainB's connection to Open connection.State = types.OPEN k.SetConnection(ctx, connectionID, connection) - k.Logger(ctx).Info("connection state updated", "connection-id", connectionID, "previous-state", types.TRYOPEN, "new-state", types.OPEN) + k.Logger.Info("connection state updated", "connection-id", connectionID, "previous-state", types.TRYOPEN, "new-state", types.OPEN) defer telemetry.IncrCounter(1, "ibc", "connection", "open-confirm") diff --git a/modules/core/03-connection/keeper/keeper.go b/modules/core/03-connection/keeper/keeper.go index 328e6898420..2a34d19a7ad 100644 --- a/modules/core/03-connection/keeper/keeper.go +++ b/modules/core/03-connection/keeper/keeper.go @@ -4,9 +4,8 @@ import ( "context" "errors" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" @@ -25,28 +24,28 @@ import ( type Keeper struct { // implements gRPC QueryServer interface types.QueryServer + appmodule.Environment - storeService corestore.KVStoreService legacySubspace types.ParamSubspace cdc codec.BinaryCodec clientKeeper types.ClientKeeper } // NewKeeper creates a new IBC connection Keeper instance -func NewKeeper(cdc codec.BinaryCodec, storeService corestore.KVStoreService, legacySubspace types.ParamSubspace, ck types.ClientKeeper) *Keeper { +func NewKeeper(cdc codec.BinaryCodec, env appmodule.Environment, legacySubspace types.ParamSubspace, ck types.ClientKeeper) *Keeper { return &Keeper{ - storeService: storeService, + Environment: env, cdc: cdc, legacySubspace: legacySubspace, clientKeeper: ck, } } -// Logger returns a module-specific logger. -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) -} +// // Logger returns a module-specific logger. +// func (Keeper) Logger(ctx context.Context) log.Logger { +// sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 +// return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +// } // GetCommitmentPrefix returns the IBC connection store prefix as a commitment // Prefix @@ -66,7 +65,7 @@ func (k *Keeper) GenerateConnectionIdentifier(ctx context.Context) string { // GetConnection returns a connection with a particular identifier func (k *Keeper) GetConnection(ctx context.Context, connectionID string) (types.ConnectionEnd, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.ConnectionKey(connectionID)) if err != nil { panic(err) @@ -85,7 +84,7 @@ func (k *Keeper) GetConnection(ctx context.Context, connectionID string) (types. // HasConnection returns a true if the connection with the given identifier // exists in the store. func (k *Keeper) HasConnection(ctx context.Context, connectionID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.ConnectionKey(connectionID)) if err != nil { return false @@ -95,7 +94,7 @@ func (k *Keeper) HasConnection(ctx context.Context, connectionID string) bool { // SetConnection sets a connection to the store func (k *Keeper) SetConnection(ctx context.Context, connectionID string, connection types.ConnectionEnd) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&connection) if err := store.Set(host.ConnectionKey(connectionID), bz); err != nil { panic(err) @@ -105,7 +104,7 @@ func (k *Keeper) SetConnection(ctx context.Context, connectionID string, connect // GetClientConnectionPaths returns all the connection paths stored under a // particular client func (k *Keeper) GetClientConnectionPaths(ctx context.Context, clientID string) ([]string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.ClientConnectionsKey(clientID)) if err != nil { panic(err) @@ -122,7 +121,7 @@ func (k *Keeper) GetClientConnectionPaths(ctx context.Context, clientID string) // SetClientConnectionPaths sets the connections paths for client func (k *Keeper) SetClientConnectionPaths(ctx context.Context, clientID string, paths []string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) clientPaths := types.ClientPaths{Paths: paths} bz := k.cdc.MustMarshal(&clientPaths) if err := store.Set(host.ClientConnectionsKey(clientID), bz); err != nil { @@ -132,7 +131,7 @@ func (k *Keeper) SetClientConnectionPaths(ctx context.Context, clientID string, // GetNextConnectionSequence gets the next connection sequence from the store. func (k *Keeper) GetNextConnectionSequence(ctx context.Context) uint64 { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.KeyNextConnectionSequence)) if err != nil { panic(err) @@ -147,7 +146,7 @@ func (k *Keeper) GetNextConnectionSequence(ctx context.Context) uint64 { // SetNextConnectionSequence sets the next connection sequence to the store. func (k *Keeper) SetNextConnectionSequence(ctx context.Context, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set([]byte(types.KeyNextConnectionSequence), bz); err != nil { panic(err) @@ -178,11 +177,11 @@ func (k *Keeper) GetAllClientConnectionPaths(ctx context.Context) []types.Connec // For each ConnectionEnd, cb will be called. If the cb returns true, the // iterator will close and stop. func (k *Keeper) IterateConnections(ctx context.Context, cb func(types.IdentifiedConnection) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyConnectionPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var connection types.ConnectionEnd k.cdc.MustUnmarshal(iterator.Value(), &connection) @@ -232,7 +231,7 @@ func (k *Keeper) addConnectionToClient(ctx context.Context, clientID, connection // GetParams returns the total set of ibc-connection parameters. func (k *Keeper) GetParams(ctx context.Context) types.Params { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.ParamsKey)) if err != nil { panic(err) @@ -249,7 +248,7 @@ func (k *Keeper) GetParams(ctx context.Context) types.Params { // SetParams sets the total set of ibc-connection parameters. func (k *Keeper) SetParams(ctx context.Context, params types.Params) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) if err := store.Set([]byte(types.ParamsKey), bz); err != nil { panic(err) diff --git a/modules/core/03-connection/keeper/migrations.go b/modules/core/03-connection/keeper/migrations.go index d668687d017..83503ebf971 100644 --- a/modules/core/03-connection/keeper/migrations.go +++ b/modules/core/03-connection/keeper/migrations.go @@ -35,6 +35,6 @@ func (m Migrator) MigrateParams(ctx sdk.Context) error { } m.keeper.SetParams(ctx, params) - m.keeper.Logger(ctx).Info("successfully migrated connection to self-manage params") + m.keeper.Logger.Info("successfully migrated connection to self-manage params") return nil } diff --git a/modules/core/04-channel/keeper/grpc_query.go b/modules/core/04-channel/keeper/grpc_query.go index 648a8028534..d2ef8fed802 100644 --- a/modules/core/04-channel/keeper/grpc_query.go +++ b/modules/core/04-channel/keeper/grpc_query.go @@ -65,7 +65,7 @@ func (q *queryServer) Channels(ctx context.Context, req *types.QueryChannelsRequ } var channels []*types.IdentifiedChannel - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), []byte(host.KeyChannelEndPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), []byte(host.KeyChannelEndPrefix)) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { var result types.Channel @@ -106,7 +106,7 @@ func (q *queryServer) ConnectionChannels(ctx context.Context, req *types.QueryCo var channels []*types.IdentifiedChannel - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), []byte(host.KeyChannelEndPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), []byte(host.KeyChannelEndPrefix)) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // filter any metadata stored under channel key @@ -254,7 +254,7 @@ func (q *queryServer) PacketCommitments(ctx context.Context, req *types.QueryPac ) } var commitments []*types.PacketState - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.PacketCommitmentPrefixKey(req.PortId, req.ChannelId)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), host.PacketCommitmentPrefixKey(req.PortId, req.ChannelId)) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { keySplit := strings.Split(string(key), "/") @@ -352,7 +352,7 @@ func (q *queryServer) PacketAcknowledgements(ctx context.Context, req *types.Que ) } var acks []*types.PacketState - store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.PacketAcknowledgementPrefixKey(req.PortId, req.ChannelId)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.KVStoreService.OpenKVStore(ctx)), host.PacketAcknowledgementPrefixKey(req.PortId, req.ChannelId)) // if a list of packet sequences is provided then query for each specific ack and return a list <= len(req.PacketCommitmentSequences) // otherwise, maintain previous behaviour and perform paginated query diff --git a/modules/core/04-channel/keeper/handshake.go b/modules/core/04-channel/keeper/handshake.go index 635b178e067..ab2c7561b0f 100644 --- a/modules/core/04-channel/keeper/handshake.go +++ b/modules/core/04-channel/keeper/handshake.go @@ -76,7 +76,7 @@ func (k *Keeper) WriteOpenInitChannel( k.SetNextSequenceRecv(ctx, portID, channelID, 1) k.SetNextSequenceAck(ctx, portID, channelID, 1) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.UNINITIALIZED, "new-state", types.INIT) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.UNINITIALIZED, "new-state", types.INIT) defer telemetry.IncrCounter(1, "ibc", "channel", "open-init") @@ -169,7 +169,7 @@ func (k *Keeper) WriteOpenTryChannel( k.SetChannel(ctx, portID, channelID, channel) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.UNINITIALIZED, "new-state", types.TRYOPEN) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.UNINITIALIZED, "new-state", types.TRYOPEN) defer telemetry.IncrCounter(1, "ibc", "channel", "open-try") @@ -239,7 +239,7 @@ func (k *Keeper) WriteOpenAckChannel( channel.Counterparty.ChannelId = counterpartyChannelID k.SetChannel(ctx, portID, channelID, channel) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.INIT, "new-state", types.OPEN) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.INIT, "new-state", types.OPEN) defer telemetry.IncrCounter(1, "ibc", "channel", "open-ack") @@ -306,7 +306,7 @@ func (k *Keeper) WriteOpenConfirmChannel( channel.State = types.OPEN k.SetChannel(ctx, portID, channelID, channel) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.TRYOPEN, "new-state", types.OPEN) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.TRYOPEN, "new-state", types.OPEN) defer telemetry.IncrCounter(1, "ibc", "channel", "open-confirm") @@ -347,7 +347,7 @@ func (k *Keeper) ChanCloseInit( return errorsmod.Wrapf(connectiontypes.ErrInvalidConnectionState, "connection state is not OPEN (got %s)", connectionEnd.State) } - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", channel.State, "new-state", types.CLOSED) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", channel.State, "new-state", types.CLOSED) defer telemetry.IncrCounter(1, "ibc", "channel", "close-init") @@ -410,7 +410,7 @@ func (k *Keeper) ChanCloseConfirm( // If the channel is closing during an upgrade, then we can delete all upgrade information. if k.hasUpgrade(ctx, portID, channelID) { k.deleteUpgradeInfo(ctx, portID, channelID) - k.Logger(ctx).Info( + k.Logger.Info( "upgrade info deleted", "port_id", portID, "channel_id", channelID, @@ -418,7 +418,7 @@ func (k *Keeper) ChanCloseConfirm( ) } - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", channel.State, "new-state", types.CLOSED) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", channel.State, "new-state", types.CLOSED) defer telemetry.IncrCounter(1, "ibc", "channel", "close-confirm") diff --git a/modules/core/04-channel/keeper/keeper.go b/modules/core/04-channel/keeper/keeper.go index 75b27605a01..5579ca91cdf 100644 --- a/modules/core/04-channel/keeper/keeper.go +++ b/modules/core/04-channel/keeper/keeper.go @@ -8,9 +8,8 @@ import ( db "github.com/cosmos/cosmos-db" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" @@ -33,7 +32,7 @@ type Keeper struct { // implements gRPC QueryServer interface types.QueryServer - storeService corestore.KVStoreService + appmodule.Environment cdc codec.BinaryCodec clientKeeper types.ClientKeeper connectionKeeper types.ConnectionKeeper @@ -44,14 +43,14 @@ type Keeper struct { // NewKeeper creates a new IBC channel Keeper instance func NewKeeper( cdc codec.BinaryCodec, - storeService corestore.KVStoreService, + env appmodule.Environment, clientKeeper types.ClientKeeper, connectionKeeper types.ConnectionKeeper, portKeeper types.PortKeeper, scopedKeeper exported.ScopedKeeper, ) *Keeper { return &Keeper{ - storeService: storeService, + Environment: env, cdc: cdc, clientKeeper: clientKeeper, connectionKeeper: connectionKeeper, @@ -60,11 +59,11 @@ func NewKeeper( } } -// Logger returns a module-specific logger. -func (Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) -} +// // Logger returns a module-specific logger. +// func (Keeper) Logger(ctx context.Context) log.Logger { +// sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 +// return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +// } // GenerateChannelIdentifier returns the next channel identifier. func (k *Keeper) GenerateChannelIdentifier(ctx context.Context) string { @@ -78,7 +77,7 @@ func (k *Keeper) GenerateChannelIdentifier(ctx context.Context) string { // HasChannel true if the channel with the given identifiers exists in state. func (k *Keeper) HasChannel(ctx context.Context, portID, channelID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.ChannelKey(portID, channelID)) if err != nil { panic(err) @@ -88,7 +87,7 @@ func (k *Keeper) HasChannel(ctx context.Context, portID, channelID string) bool // GetChannel returns a channel with a particular identifier binded to a specific port func (k *Keeper) GetChannel(ctx context.Context, portID, channelID string) (types.Channel, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.ChannelKey(portID, channelID)) if err != nil { panic(err) @@ -104,7 +103,7 @@ func (k *Keeper) GetChannel(ctx context.Context, portID, channelID string) (type // SetChannel sets a channel to the store func (k *Keeper) SetChannel(ctx context.Context, portID, channelID string, channel types.Channel) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&channel) if err := store.Set(host.ChannelKey(portID, channelID), bz); err != nil { panic(err) @@ -123,7 +122,7 @@ func (k *Keeper) GetAppVersion(ctx context.Context, portID, channelID string) (s // GetNextChannelSequence gets the next channel sequence from the store. func (k *Keeper) GetNextChannelSequence(ctx context.Context) uint64 { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.KeyNextChannelSequence)) if err != nil { panic(err) @@ -137,7 +136,7 @@ func (k *Keeper) GetNextChannelSequence(ctx context.Context) uint64 { // SetNextChannelSequence sets the next channel sequence to the store. func (k *Keeper) SetNextChannelSequence(ctx context.Context, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set([]byte(types.KeyNextChannelSequence), bz); err != nil { panic(err) @@ -146,7 +145,7 @@ func (k *Keeper) SetNextChannelSequence(ctx context.Context, sequence uint64) { // GetNextSequenceSend gets a channel's next send sequence from the store func (k *Keeper) GetNextSequenceSend(ctx context.Context, portID, channelID string) (uint64, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.NextSequenceSendKey(portID, channelID)) if err != nil { panic(err) @@ -160,7 +159,7 @@ func (k *Keeper) GetNextSequenceSend(ctx context.Context, portID, channelID stri // SetNextSequenceSend sets a channel's next send sequence to the store func (k *Keeper) SetNextSequenceSend(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set(host.NextSequenceSendKey(portID, channelID), bz); err != nil { panic(err) @@ -169,7 +168,7 @@ func (k *Keeper) SetNextSequenceSend(ctx context.Context, portID, channelID stri // GetNextSequenceRecv gets a channel's next receive sequence from the store func (k *Keeper) GetNextSequenceRecv(ctx context.Context, portID, channelID string) (uint64, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.NextSequenceRecvKey(portID, channelID)) if err != nil { panic(err) @@ -183,7 +182,7 @@ func (k *Keeper) GetNextSequenceRecv(ctx context.Context, portID, channelID stri // SetNextSequenceRecv sets a channel's next receive sequence to the store func (k *Keeper) SetNextSequenceRecv(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set(host.NextSequenceRecvKey(portID, channelID), bz); err != nil { panic(err) @@ -192,7 +191,7 @@ func (k *Keeper) SetNextSequenceRecv(ctx context.Context, portID, channelID stri // GetNextSequenceAck gets a channel's next ack sequence from the store func (k *Keeper) GetNextSequenceAck(ctx context.Context, portID, channelID string) (uint64, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.NextSequenceAckKey(portID, channelID)) if err != nil { panic(err) @@ -207,7 +206,7 @@ func (k *Keeper) GetNextSequenceAck(ctx context.Context, portID, channelID strin // SetNextSequenceAck sets a channel's next ack sequence to the store func (k *Keeper) SetNextSequenceAck(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set(host.NextSequenceAckKey(portID, channelID), bz); err != nil { panic(err) @@ -216,7 +215,7 @@ func (k *Keeper) SetNextSequenceAck(ctx context.Context, portID, channelID strin // GetPacketReceipt gets a packet receipt from the store func (k *Keeper) GetPacketReceipt(ctx context.Context, portID, channelID string, sequence uint64) (string, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.PacketReceiptKey(portID, channelID, sequence)) if err != nil { panic(err) @@ -231,7 +230,7 @@ func (k *Keeper) GetPacketReceipt(ctx context.Context, portID, channelID string, // SetPacketReceipt sets an empty packet receipt to the store func (k *Keeper) SetPacketReceipt(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(host.PacketReceiptKey(portID, channelID, sequence), []byte{byte(1)}); err != nil { panic(err) } @@ -239,7 +238,7 @@ func (k *Keeper) SetPacketReceipt(ctx context.Context, portID, channelID string, // deletePacketReceipt deletes a packet receipt from the store func (k *Keeper) deletePacketReceipt(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(host.PacketReceiptKey(portID, channelID, sequence)); err != nil { panic(err) } @@ -247,7 +246,7 @@ func (k *Keeper) deletePacketReceipt(ctx context.Context, portID, channelID stri // GetPacketCommitment gets the packet commitment hash from the store func (k *Keeper) GetPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) []byte { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.PacketCommitmentKey(portID, channelID, sequence)) if err != nil { panic(err) @@ -258,7 +257,7 @@ func (k *Keeper) GetPacketCommitment(ctx context.Context, portID, channelID stri // HasPacketCommitment returns true if the packet commitment exists func (k *Keeper) HasPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.PacketCommitmentKey(portID, channelID, sequence)) if err != nil { panic(err) @@ -268,14 +267,14 @@ func (k *Keeper) HasPacketCommitment(ctx context.Context, portID, channelID stri // SetPacketCommitment sets the packet commitment hash to the store func (k *Keeper) SetPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64, commitmentHash []byte) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(host.PacketCommitmentKey(portID, channelID, sequence), commitmentHash); err != nil { panic(err) } } func (k *Keeper) deletePacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(host.PacketCommitmentKey(portID, channelID, sequence)); err != nil { panic(err) } @@ -283,7 +282,7 @@ func (k *Keeper) deletePacketCommitment(ctx context.Context, portID, channelID s // SetPacketAcknowledgement sets the packet ack hash to the store func (k *Keeper) SetPacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64, ackHash []byte) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Set(host.PacketAcknowledgementKey(portID, channelID, sequence), ackHash); err != nil { panic(err) } @@ -291,7 +290,7 @@ func (k *Keeper) SetPacketAcknowledgement(ctx context.Context, portID, channelID // GetPacketAcknowledgement gets the packet ack hash from the store func (k *Keeper) GetPacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64) ([]byte, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.PacketAcknowledgementKey(portID, channelID, sequence)) if err != nil { panic(err) @@ -306,7 +305,7 @@ func (k *Keeper) GetPacketAcknowledgement(ctx context.Context, portID, channelID // HasPacketAcknowledgement check if the packet ack hash is already on the store func (k *Keeper) HasPacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.PacketAcknowledgementKey(portID, channelID, sequence)) if err != nil { panic(err) @@ -316,7 +315,7 @@ func (k *Keeper) HasPacketAcknowledgement(ctx context.Context, portID, channelID // deletePacketAcknowledgement deletes the packet ack hash from the store func (k *Keeper) deletePacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(host.PacketAcknowledgementKey(portID, channelID, sequence)); err != nil { panic(err) } @@ -326,7 +325,7 @@ func (k *Keeper) deletePacketAcknowledgement(ctx context.Context, portID, channe // For each sequence, cb will be called. If the cb returns true, the iterator // will close and stop. func (k *Keeper) IteratePacketSequence(ctx context.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64) bool) { - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { portID, channelID, err := host.ParseChannelPath(string(iterator.Key())) if err != nil { @@ -344,7 +343,7 @@ func (k *Keeper) IteratePacketSequence(ctx context.Context, iterator db.Iterator // GetAllPacketSendSeqs returns all stored next send sequences. func (k *Keeper) GetAllPacketSendSeqs(ctx context.Context) (seqs []types.PacketSequence) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyNextSeqSendPrefix)) k.IteratePacketSequence(ctx, iterator, func(portID, channelID string, nextSendSeq uint64) bool { ps := types.NewPacketSequence(portID, channelID, nextSendSeq) @@ -356,7 +355,7 @@ func (k *Keeper) GetAllPacketSendSeqs(ctx context.Context) (seqs []types.PacketS // GetAllPacketRecvSeqs returns all stored next recv sequences. func (k *Keeper) GetAllPacketRecvSeqs(ctx context.Context) (seqs []types.PacketSequence) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyNextSeqRecvPrefix)) k.IteratePacketSequence(ctx, iterator, func(portID, channelID string, nextRecvSeq uint64) bool { ps := types.NewPacketSequence(portID, channelID, nextRecvSeq) @@ -368,7 +367,7 @@ func (k *Keeper) GetAllPacketRecvSeqs(ctx context.Context) (seqs []types.PacketS // GetAllPacketAckSeqs returns all stored next acknowledgements sequences. func (k *Keeper) GetAllPacketAckSeqs(ctx context.Context) (seqs []types.PacketSequence) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyNextSeqAckPrefix)) k.IteratePacketSequence(ctx, iterator, func(portID, channelID string, nextAckSeq uint64) bool { ps := types.NewPacketSequence(portID, channelID, nextAckSeq) @@ -382,7 +381,7 @@ func (k *Keeper) GetAllPacketAckSeqs(ctx context.Context) (seqs []types.PacketSe // packet commitment, cb will be called. If the cb returns true, the iterator will close // and stop. func (k *Keeper) IteratePacketCommitment(ctx context.Context, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyPacketCommitmentPrefix)) k.iterateHashes(ctx, iterator, cb) } @@ -401,7 +400,7 @@ func (k *Keeper) GetAllPacketCommitments(ctx context.Context) (commitments []typ // at a specified channel. For each packet commitment, cb will be called. If the cb returns // true, the iterator will close and stop. func (k *Keeper) IteratePacketCommitmentAtChannel(ctx context.Context, portID, channelID string, cb func(_, _ string, sequence uint64, hash []byte) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.PacketCommitmentPrefixKey(portID, channelID)) k.iterateHashes(ctx, iterator, cb) } @@ -421,7 +420,7 @@ func (k *Keeper) GetAllPacketCommitmentsAtChannel(ctx context.Context, portID, c // receipt, cb will be called. If the cb returns true, the iterator will close // and stop. func (k *Keeper) IteratePacketReceipt(ctx context.Context, cb func(portID, channelID string, sequence uint64, receipt []byte) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyPacketReceiptPrefix)) k.iterateHashes(ctx, iterator, cb) } @@ -440,7 +439,7 @@ func (k *Keeper) GetAllPacketReceipts(ctx context.Context) (receipts []types.Pac // acknowledgement, cb will be called. If the cb returns true, the iterator will close // and stop. func (k *Keeper) IteratePacketAcknowledgement(ctx context.Context, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyPacketAckPrefix)) k.iterateHashes(ctx, iterator, cb) } @@ -459,10 +458,10 @@ func (k *Keeper) GetAllPacketAcks(ctx context.Context) (acks []types.PacketState // Channel, cb will be called. If the cb returns true, the iterator will close // and stop. func (k *Keeper) IterateChannels(ctx context.Context, cb func(types.IdentifiedChannel) bool) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyChannelEndPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var channel types.Channel k.cdc.MustUnmarshal(iterator.Value(), &channel) @@ -481,9 +480,9 @@ func (k *Keeper) GetAllChannelsWithPortPrefix(ctx context.Context, portPrefix st if strings.TrimSpace(portPrefix) == "" { return k.GetAllChannels(ctx) } - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.FilteredPortPrefix(portPrefix)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) var filteredChannels []types.IdentifiedChannel for ; iterator.Valid(); iterator.Next() { @@ -555,7 +554,7 @@ func (k *Keeper) GetChannelConnection(ctx context.Context, portID, channelID str // GetUpgradeErrorReceipt returns the upgrade error receipt for the provided port and channel identifiers. func (k *Keeper) GetUpgradeErrorReceipt(ctx context.Context, portID, channelID string) (types.ErrorReceipt, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.ChannelUpgradeErrorKey(portID, channelID)) if err != nil { panic(err) @@ -573,7 +572,7 @@ func (k *Keeper) GetUpgradeErrorReceipt(ctx context.Context, portID, channelID s // setUpgradeErrorReceipt sets the provided error receipt in store using the port and channel identifiers. func (k *Keeper) setUpgradeErrorReceipt(ctx context.Context, portID, channelID string, errorReceipt types.ErrorReceipt) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&errorReceipt) if err := store.Set(host.ChannelUpgradeErrorKey(portID, channelID), bz); err != nil { panic(err) @@ -582,7 +581,7 @@ func (k *Keeper) setUpgradeErrorReceipt(ctx context.Context, portID, channelID s // hasUpgrade returns true if a proposed upgrade exists in store func (k *Keeper) hasUpgrade(ctx context.Context, portID, channelID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.ChannelUpgradeKey(portID, channelID)) if err != nil { panic(err) @@ -592,7 +591,7 @@ func (k *Keeper) hasUpgrade(ctx context.Context, portID, channelID string) bool // GetUpgrade returns the proposed upgrade for the provided port and channel identifiers. func (k *Keeper) GetUpgrade(ctx context.Context, portID, channelID string) (types.Upgrade, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.ChannelUpgradeKey(portID, channelID)) if err != nil { panic(err) @@ -610,7 +609,7 @@ func (k *Keeper) GetUpgrade(ctx context.Context, portID, channelID string) (type // SetUpgrade sets the proposed upgrade using the provided port and channel identifiers. func (k *Keeper) SetUpgrade(ctx context.Context, portID, channelID string, upgrade types.Upgrade) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&upgrade) if err := store.Set(host.ChannelUpgradeKey(portID, channelID), bz); err != nil { panic(err) @@ -619,7 +618,7 @@ func (k *Keeper) SetUpgrade(ctx context.Context, portID, channelID string, upgra // deleteUpgrade deletes the upgrade for the provided port and channel identifiers. func (k *Keeper) deleteUpgrade(ctx context.Context, portID, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(host.ChannelUpgradeKey(portID, channelID)); err != nil { panic(err) } @@ -627,7 +626,7 @@ func (k *Keeper) deleteUpgrade(ctx context.Context, portID, channelID string) { // hasCounterpartyUpgrade returns true if a counterparty upgrade exists in store func (k *Keeper) hasCounterpartyUpgrade(ctx context.Context, portID, channelID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.ChannelCounterpartyUpgradeKey(portID, channelID)) if err != nil { panic(err) @@ -637,7 +636,7 @@ func (k *Keeper) hasCounterpartyUpgrade(ctx context.Context, portID, channelID s // GetCounterpartyUpgrade gets the counterparty upgrade from the store. func (k *Keeper) GetCounterpartyUpgrade(ctx context.Context, portID, channelID string) (types.Upgrade, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.ChannelCounterpartyUpgradeKey(portID, channelID)) if err != nil { panic(err) @@ -655,7 +654,7 @@ func (k *Keeper) GetCounterpartyUpgrade(ctx context.Context, portID, channelID s // SetCounterpartyUpgrade sets the counterparty upgrade in the store. func (k *Keeper) SetCounterpartyUpgrade(ctx context.Context, portID, channelID string, upgrade types.Upgrade) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&upgrade) if err := store.Set(host.ChannelCounterpartyUpgradeKey(portID, channelID), bz); err != nil { panic(err) @@ -664,7 +663,7 @@ func (k *Keeper) SetCounterpartyUpgrade(ctx context.Context, portID, channelID s // deleteCounterpartyUpgrade deletes the counterparty upgrade in the store. func (k *Keeper) deleteCounterpartyUpgrade(ctx context.Context, portID, channelID string) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := store.Delete(host.ChannelCounterpartyUpgradeKey(portID, channelID)); err != nil { panic(err) } @@ -678,7 +677,7 @@ func (k *Keeper) deleteUpgradeInfo(ctx context.Context, portID, channelID string // SetParams sets the channel parameters. func (k *Keeper) SetParams(ctx context.Context, params types.Params) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) if err := store.Set([]byte(types.ParamsKey), bz); err != nil { panic(err) @@ -687,7 +686,7 @@ func (k *Keeper) SetParams(ctx context.Context, params types.Params) { // GetParams returns the total set of the channel parameters. func (k *Keeper) GetParams(ctx context.Context) types.Params { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get([]byte(types.ParamsKey)) if err != nil { panic(err) @@ -704,7 +703,7 @@ func (k *Keeper) GetParams(ctx context.Context) types.Params { // common functionality for IteratePacketCommitment and IteratePacketAcknowledgement func (k *Keeper) iterateHashes(ctx context.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { keySplit := strings.Split(string(iterator.Key()), "/") @@ -725,16 +724,16 @@ func (k *Keeper) iterateHashes(ctx context.Context, iterator db.Iterator, cb fun // HasInflightPackets returns true if there are packet commitments stored at the specified // port and channel, and false otherwise. func (k *Keeper) HasInflightPackets(ctx context.Context, portID, channelID string) bool { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.PacketCommitmentPrefixKey(portID, channelID)) - defer coretypes.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) + defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() }) return iterator.Valid() } // setRecvStartSequence sets the channel's recv start sequence to the store. func (k *Keeper) setRecvStartSequence(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set(host.RecvStartSequenceKey(portID, channelID), bz); err != nil { panic(err) @@ -746,7 +745,7 @@ func (k *Keeper) setRecvStartSequence(ctx context.Context, portID, channelID str // upon a successful channel upgrade. It will be used for replay protection of // historical packets and as the upper bound for pruning stale packet receives. func (k *Keeper) GetRecvStartSequence(ctx context.Context, portID, channelID string) (uint64, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.RecvStartSequenceKey(portID, channelID)) if err != nil { panic(err) @@ -761,7 +760,7 @@ func (k *Keeper) GetRecvStartSequence(ctx context.Context, portID, channelID str // SetPruningSequenceStart sets a channel's pruning sequence start to the store. func (k *Keeper) SetPruningSequenceStart(ctx context.Context, portID, channelID string, sequence uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) if err := store.Set(host.PruningSequenceStartKey(portID, channelID), bz); err != nil { panic(err) @@ -770,7 +769,7 @@ func (k *Keeper) SetPruningSequenceStart(ctx context.Context, portID, channelID // GetPruningSequenceStart gets a channel's pruning sequence start from the store. func (k *Keeper) GetPruningSequenceStart(ctx context.Context, portID, channelID string) (uint64, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(host.PruningSequenceStartKey(portID, channelID)) if err != nil { panic(err) @@ -785,7 +784,7 @@ func (k *Keeper) GetPruningSequenceStart(ctx context.Context, portID, channelID // HasPruningSequenceStart returns true if the pruning sequence start is set for the specified channel. func (k *Keeper) HasPruningSequenceStart(ctx context.Context, portID, channelID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) has, err := store.Has(host.PruningSequenceStartKey(portID, channelID)) if err != nil { panic(err) diff --git a/modules/core/04-channel/keeper/migrations.go b/modules/core/04-channel/keeper/migrations.go index 9a382d26265..c83cf865022 100644 --- a/modules/core/04-channel/keeper/migrations.go +++ b/modules/core/04-channel/keeper/migrations.go @@ -20,6 +20,6 @@ func NewMigrator(keeper *Keeper) Migrator { func (m Migrator) MigrateParams(ctx sdk.Context) error { params := channeltypes.DefaultParams() m.keeper.SetParams(ctx, params) - m.keeper.Logger(ctx).Info("successfully migrated ibc channel params") + m.keeper.Logger.Info("successfully migrated ibc channel params") return nil } diff --git a/modules/core/04-channel/keeper/packet.go b/modules/core/04-channel/keeper/packet.go index 65410bcd11b..d7946ddad6f 100644 --- a/modules/core/04-channel/keeper/packet.go +++ b/modules/core/04-channel/keeper/packet.go @@ -87,7 +87,7 @@ func (k *Keeper) SendPacket( emitSendPacketEvent(sdkCtx, packet, channel, timeoutHeight) - k.Logger(ctx).Info( + k.Logger.Info( "packet sent", "sequence", strconv.FormatUint(packet.GetSequence(), 10), "src_port", sourcePort, @@ -180,7 +180,7 @@ func (k *Keeper) RecvPacket( } // log that a packet has been received & executed - k.Logger(ctx).Info( + k.Logger.Info( "packet received", "sequence", strconv.FormatUint(packet.GetSequence(), 10), "src_port", packet.GetSourcePort(), @@ -325,7 +325,7 @@ func (k *Keeper) WriteAcknowledgement( ) // log that a packet acknowledgement has been written - k.Logger(ctx).Info( + k.Logger.Info( "acknowledgement written", "sequence", strconv.FormatUint(packet.GetSequence(), 10), "src_port", packet.GetSourcePort(), @@ -444,7 +444,7 @@ func (k *Keeper) AcknowledgePacket( k.deletePacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) // log that a packet has been acknowledged - k.Logger(ctx).Info( + k.Logger.Info( "packet acknowledged", "sequence", strconv.FormatUint(packet.GetSequence(), 10), "src_port", packet.GetSourcePort(), @@ -477,7 +477,7 @@ func (k *Keeper) handleFlushState(ctx context.Context, packet types.Packet, chan if timeout.Elapsed(selfHeight, selfTimestamp) { // packet flushing timeout has expired, abort the upgrade // committing an error receipt to state, deleting upgrade information and restoring the channel. - k.Logger(ctx).Info("upgrade aborted", "port_id", packet.GetSourcePort(), "channel_id", packet.GetSourceChannel(), "upgrade_sequence", channel.UpgradeSequence) + k.Logger.Info("upgrade aborted", "port_id", packet.GetSourcePort(), "channel_id", packet.GetSourceChannel(), "upgrade_sequence", channel.UpgradeSequence) k.MustAbortUpgrade(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), timeout.ErrTimeoutElapsed(selfHeight, selfTimestamp)) } else if !k.HasInflightPackets(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) { // set the channel state to flush complete if all packets have been acknowledged/flushed. diff --git a/modules/core/04-channel/keeper/timeout.go b/modules/core/04-channel/keeper/timeout.go index 98156a68147..74a43006990 100644 --- a/modules/core/04-channel/keeper/timeout.go +++ b/modules/core/04-channel/keeper/timeout.go @@ -148,7 +148,7 @@ func (k *Keeper) TimeoutExecuted( // all upgrade information is deleted and the channel is set to CLOSED. if channel.State == types.FLUSHING { k.deleteUpgradeInfo(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) - k.Logger(ctx).Info( + k.Logger.Info( "upgrade info deleted", "port_id", packet.GetSourcePort(), "channel_id", packet.GetSourceChannel(), @@ -161,7 +161,7 @@ func (k *Keeper) TimeoutExecuted( emitChannelClosedEvent(ctx, packet, channel) } - k.Logger(ctx).Info( + k.Logger.Info( "packet timed-out", "sequence", strconv.FormatUint(packet.GetSequence(), 10), "src_port", packet.GetSourcePort(), diff --git a/modules/core/04-channel/keeper/upgrade.go b/modules/core/04-channel/keeper/upgrade.go index cee41cbf4f0..7b9391a5fe2 100644 --- a/modules/core/04-channel/keeper/upgrade.go +++ b/modules/core/04-channel/keeper/upgrade.go @@ -67,7 +67,7 @@ func (k *Keeper) WriteUpgradeInitChannel(ctx context.Context, portID, channelID k.SetChannel(ctx, portID, channelID, channel) k.SetUpgrade(ctx, portID, channelID, upgrade) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "state", channel.State, "upgrade-sequence", fmt.Sprintf("%d", channel.UpgradeSequence)) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "state", channel.State, "upgrade-sequence", fmt.Sprintf("%d", channel.UpgradeSequence)) return channel, upgrade } @@ -235,7 +235,7 @@ func (k *Keeper) WriteUpgradeTryChannel(ctx context.Context, portID, channelID s upgrade.Fields.Version = upgradeVersion k.SetUpgrade(ctx, portID, channelID, upgrade) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.OPEN, "new-state", channel.State) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", types.OPEN, "new-state", channel.State) return channel, upgrade } @@ -366,7 +366,7 @@ func (k *Keeper) WriteUpgradeAckChannel(ctx context.Context, portID, channelID s previousState := channel.State channel.State = types.FLUSHCOMPLETE k.SetChannel(ctx, portID, channelID, channel) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", channel.State) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", channel.State) } upgrade, found := k.GetUpgrade(ctx, portID, channelID) @@ -490,7 +490,7 @@ func (k *Keeper) WriteUpgradeConfirmChannel(ctx context.Context, portID, channel previousState := channel.State channel.State = types.FLUSHCOMPLETE k.SetChannel(ctx, portID, channelID, channel) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", channel.State) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", channel.State) } k.SetCounterpartyUpgrade(ctx, portID, channelID, counterpartyUpgrade) @@ -647,7 +647,7 @@ func (k *Keeper) WriteUpgradeOpenChannel(ctx context.Context, portID, channelID // delete state associated with upgrade which is no longer required. k.deleteUpgradeInfo(ctx, portID, channelID) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", types.OPEN) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", types.OPEN) return channel } @@ -725,7 +725,7 @@ func (k *Keeper) WriteUpgradeCancelChannel(ctx context.Context, portID, channelI channel = k.restoreChannel(ctx, portID, channelID, sequence, channel) k.WriteErrorReceipt(ctx, portID, channelID, types.NewUpgradeError(sequence, types.ErrInvalidUpgrade)) - k.Logger(ctx).Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", types.OPEN) + k.Logger.Info("channel state updated", "port-id", portID, "channel-id", channelID, "previous-state", previousState, "new-state", types.OPEN) } // ChanUpgradeTimeout times out an outstanding upgrade. @@ -845,7 +845,7 @@ func (k *Keeper) WriteUpgradeTimeoutChannel( channel = k.restoreChannel(ctx, portID, channelID, channel.UpgradeSequence, channel) k.WriteErrorReceipt(ctx, portID, channelID, types.NewUpgradeError(channel.UpgradeSequence, types.ErrUpgradeTimeout)) - k.Logger(ctx).Info("channel state restored", "port-id", portID, "channel-id", channelID) + k.Logger.Info("channel state restored", "port-id", portID, "channel-id", channelID) return channel, upgrade } diff --git a/modules/core/04-channel/types/acknowledgement_test.go b/modules/core/04-channel/types/acknowledgement_test.go index 73304ecd87f..edddef900c8 100644 --- a/modules/core/04-channel/types/acknowledgement_test.go +++ b/modules/core/04-channel/types/acknowledgement_test.go @@ -7,6 +7,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" cmtstate "github.com/cometbft/cometbft/state" "github.com/cosmos/ibc-go/v9/modules/core/04-channel/types" @@ -106,14 +107,14 @@ func (suite *TypesTestSuite) TestABCICodeDeterminism() { // different ABCI error code used errDifferentABCICode := ibcerrors.ErrNotFound - deliverTx := sdkerrors.ResponseExecTxResultWithEvents(err, gasUsed, gasWanted, []abcitypes.Event{}, false) - execTxResults := []*abcitypes.ExecTxResult{deliverTx} + deliverTx := sdkerrors.ResponseExecTxResultWithEvents(err, gasUsed, gasWanted, []abci.Event{}, false) + execTxResults := []*abci.ExecTxResult{deliverTx} - deliverTxSameABCICode := sdkerrors.ResponseExecTxResultWithEvents(errSameABCICode, gasUsed, gasWanted, []abcitypes.Event{}, false) - resultsSameABCICode := []*abcitypes.ExecTxResult{deliverTxSameABCICode} + deliverTxSameABCICode := sdkerrors.ResponseExecTxResultWithEvents(errSameABCICode, gasUsed, gasWanted, []abci.Event{}, false) + resultsSameABCICode := []*abci.ExecTxResult{deliverTxSameABCICode} - deliverTxDifferentABCICode := sdkerrors.ResponseExecTxResultWithEvents(errDifferentABCICode, gasUsed, gasWanted, []abcitypes.Event{}, false) - resultsDifferentABCICode := []*abcitypes.ExecTxResult{deliverTxDifferentABCICode} + deliverTxDifferentABCICode := sdkerrors.ResponseExecTxResultWithEvents(errDifferentABCICode, gasUsed, gasWanted, []abci.Event{}, false) + resultsDifferentABCICode := []*abci.ExecTxResult{deliverTxDifferentABCICode} hash := cmtstate.TxResultsHash(execTxResults) hashSameABCICode := cmtstate.TxResultsHash(resultsSameABCICode) diff --git a/modules/core/keeper/keeper.go b/modules/core/keeper/keeper.go index 0ed9e438cad..2871436f1fa 100644 --- a/modules/core/keeper/keeper.go +++ b/modules/core/keeper/keeper.go @@ -5,7 +5,7 @@ import ( "reflect" "strings" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" "github.com/cosmos/cosmos-sdk/codec" @@ -21,6 +21,8 @@ import ( // Keeper defines each ICS keeper for IBC type Keeper struct { + appmodule.Environment + ClientKeeper *clientkeeper.Keeper ConnectionKeeper *connectionkeeper.Keeper ChannelKeeper *channelkeeper.Keeper @@ -33,7 +35,7 @@ type Keeper struct { // NewKeeper creates a new ibc Keeper func NewKeeper( - cdc codec.BinaryCodec, storeService corestore.KVStoreService, paramSpace types.ParamSubspace, + cdc codec.BinaryCodec, env appmodule.Environment, paramSpace types.ParamSubspace, upgradeKeeper clienttypes.UpgradeKeeper, scopedKeeper capabilitykeeper.ScopedKeeper, authority string, ) *Keeper { @@ -50,10 +52,10 @@ func NewKeeper( panic(errors.New("authority must be non-empty")) } - clientKeeper := clientkeeper.NewKeeper(cdc, storeService, paramSpace, upgradeKeeper) - connectionKeeper := connectionkeeper.NewKeeper(cdc, storeService, paramSpace, clientKeeper) + clientKeeper := clientkeeper.NewKeeper(cdc, env, paramSpace, upgradeKeeper) + connectionKeeper := connectionkeeper.NewKeeper(cdc, env, paramSpace, clientKeeper) portKeeper := portkeeper.NewKeeper(scopedKeeper) - channelKeeper := channelkeeper.NewKeeper(cdc, storeService, clientKeeper, connectionKeeper, portKeeper, scopedKeeper) + channelKeeper := channelkeeper.NewKeeper(cdc, env, clientKeeper, connectionKeeper, portKeeper, scopedKeeper) return &Keeper{ cdc: cdc, diff --git a/modules/light-clients/09-localhost/light_client_module.go b/modules/light-clients/09-localhost/light_client_module.go index d18cbce8eef..519ba8769e1 100644 --- a/modules/light-clients/09-localhost/light_client_module.go +++ b/modules/light-clients/09-localhost/light_client_module.go @@ -4,11 +4,10 @@ import ( "bytes" "context" - corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" commitmenttypes "github.com/cosmos/ibc-go/v9/modules/core/23-commitment/types" @@ -33,15 +32,15 @@ var _ exported.LightClientModule = (*LightClientModule)(nil) // LightClientModule implements the core IBC api.LightClientModule interface. type LightClientModule struct { - cdc codec.BinaryCodec - storeService corestore.KVStoreService + appmodule.Environment + cdc codec.BinaryCodec } // NewLightClientModule creates and returns a new 09-localhost LightClientModule. -func NewLightClientModule(cdc codec.BinaryCodec, storeService corestore.KVStoreService) *LightClientModule { +func NewLightClientModule(cdc codec.BinaryCodec, env appmodule.Environment) *LightClientModule { return &LightClientModule{ - cdc: cdc, - storeService: storeService, + cdc: cdc, + Environment: env, } } @@ -83,7 +82,7 @@ func (l LightClientModule) VerifyMembership( path exported.Path, value []byte, ) error { - ibcStore := l.storeService.OpenKVStore(ctx) + ibcStore := l.KVStoreService.OpenKVStore(ctx) // ensure the proof provided is the expected sentinel localhost client proof if !bytes.Equal(proof, SentinelProof) { @@ -127,7 +126,7 @@ func (l LightClientModule) VerifyNonMembership( proof []byte, path exported.Path, ) error { - ibcStore := l.storeService.OpenKVStore(ctx) + ibcStore := l.KVStoreService.OpenKVStore(ctx) // ensure the proof provided is the expected sentinel localhost client proof if !bytes.Equal(proof, SentinelProof) { @@ -167,9 +166,9 @@ func (LightClientModule) LatestHeight(ctx context.Context, _ string) exported.He // TimestampAtHeight returns the current block time retrieved from the application context. The localhost client does not store consensus states and thus // cannot provide a timestamp for the provided height. -func (LightClientModule) TimestampAtHeight(ctx context.Context, _ string, _ exported.Height) (uint64, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 - return uint64(sdkCtx.BlockTime().UnixNano()), nil +func (lcm LightClientModule) TimestampAtHeight(ctx context.Context, _ string, _ exported.Height) (uint64, error) { + ti := lcm.HeaderService.HeaderInfo(ctx).Time.UnixNano() + return uint64(ti), nil } // RecoverClient returns an error. The localhost cannot be modified by proposals.