2.4 KiB
Query Services
A Protobuf Query service processes queries. Query services are specific to the module in which they are defined, and only process queries defined within said module. They are called from BaseApp's Query method. {synopsis}
Pre-requisite Readings
- Module Manager {prereq}
- Messages and Queries {prereq}
Querier type
The querier type defined in the Cosmos SDK will be deprecated in favor of gRPC Services. It specifies the typical structure of a querier function:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/types/queryable.go#L9
Let us break it down:
- The
Contextcontains all the necessary information needed to process thequery, as well as a branch of the latest state. It is primarily used by thekeeperto access the state. - The
pathis an array ofstrings that contains the type of the query, and that can also containqueryarguments. Seequeriesfor more information. - The
reqitself is primarily used to retrieve arguments if they are too large to fit in thepath. This is done using theDatafield ofreq. - The result in
[]bytereturned toBaseApp, marshalled using the application'scodec.
Implementation of a module query service
gRPC Service
When defining a Protobuf Query service, a QueryServer interface is generated for each module with all the service methods:
type QueryServer interface {
QueryBalance(context.Context, *QueryBalanceParams) (*types.Coin, error)
QueryAllBalances(context.Context, *QueryAllBalancesParams) (*QueryAllBalancesResponse, error)
}
These custom queries methods should be implemented by a module's keeper, typically in ./keeper/grpc_query.go. The first parameter of these methods is a generic context.Context, whereas querier methods generally need an instance of sdk.Context to read
from the store. Therefore, the Cosmos SDK provides a function sdk.UnwrapSDKContext to retrieve the sdk.Context from the provided
context.Context.
Here's an example implementation for the bank module:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/x/bank/keeper/grpc_query.go
Next {hide}
Learn about BeginBlocker and EndBlocker {hide}