Building Subgraphs on Cosmos
Reading time: 6 min
This guide is an introduction on building subgraphs indexing based blockchains.
The Graph allows developers to process blockchain events and make the resulting data easily available via an open GraphQL API, known as a subgraph. is now able to process Cosmos events, which means Cosmos developers can now build subgraphs to easily index on-chain events.
There are four types of handlers supported in Cosmos subgraphs:
- Block handlers run whenever a new block is appended to the chain.
- Event handlers run when a specific event is emitted.
- Transaction handlers run when a transaction occurs.
- Message handlers run when a specific message occurs.
are objects that contain information about the execution of the application. They are mainly used by service providers like block explorers and wallets to track the execution of various messages and index transactions.
are module-specific objects that trigger state transitions within the scope of the module they belong to.
Even though all data can be accessed with a block handler, other handlers enable subgraph developers to process data in a much more granular way.
is a CLI tool to build and deploy subgraphs, version >=0.30.0
is required in order to work with Cosmos subgraphs.
is a library of subgraph-specific types, version >=0.27.0
is required in order to work with Cosmos subgraphs.
There are three key parts when it comes to defining a subgraph:
subgraph.yaml: a YAML file containing the subgraph manifest, which identifies which events to track and how to process them.
schema.graphql: a GraphQL schema that defines what data is stored for your subgraph, and how to query it via GraphQL.
AssemblyScript Mappings: code that translates from blockchain data to the entities defined in your schema.
The subgraph manifest (subgraph.yaml
) identifies the data sources for the subgraph, the triggers of interest, and the functions (handlers
) that should be run in response to those triggers. See below for an example subgraph manifest for a Cosmos subgraph:
specVersion: 0.0.5description: Cosmos Subgraph Exampleschema:file: ./schema.graphql # link to the schema filedataSources:- kind: cosmosname: CosmosHubnetwork: cosmoshub-4 # This will change for each cosmos-based blockchain. In this case, the example uses the Cosmos Hub mainnet.source:startBlock: 0 # Required for Cosmos, set this to 0 to start indexing from chain genesismapping:apiVersion: 0.0.7language: wasm/assemblyscriptblockHandlers:- handler: handleNewBlock # the function name in the mapping fileeventHandlers:- event: rewards # the type of the event that will be handledhandler: handleReward # the function name in the mapping filetransactionHandlers:- handler: handleTransaction # the function name in the mapping filemessageHandlers:- message: /cosmos.staking.v1beta1.MsgDelegate # the type of a messagehandler: handleMsgDelegate # the function name in the mapping filefile: ./src/mapping.ts # link to the file with the Assemblyscript mappings
- Cosmos subgraphs introduce a new
kind
of data source (cosmos
). - The
network
should correspond to a chain in the Cosmos ecosystem. In the example, the Cosmos Hub mainnet is used.
Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition .
The handlers for processing events are written in .
Cosmos indexing introduces Cosmos-specific data types to the .
class Block {header: Headerevidence: EvidenceListresultBeginBlock: ResponseBeginBlockresultEndBlock: ResponseEndBlocktransactions: Array<TxResult>validatorUpdates: Array<Validator>}class EventData {event: Eventblock: HeaderOnlyBlocktx: TransactionContext}class TransactionData {tx: TxResultblock: HeaderOnlyBlock}class MessageData {message: Anyblock: HeaderOnlyBlocktx: TransactionContext}class TransactionContext {hash: Bytesindex: u32code: u32gasWanted: i64gasUsed: i64}class HeaderOnlyBlock {header: Header}class Header {version: ConsensuschainId: stringheight: u64time: TimestamplastBlockId: BlockIDlastCommitHash: BytesdataHash: BytesvalidatorsHash: BytesnextValidatorsHash: BytesconsensusHash: BytesappHash: ByteslastResultsHash: BytesevidenceHash: BytesproposerAddress: Byteshash: Bytes}class TxResult {height: u64index: u32tx: Txresult: ResponseDeliverTxhash: Bytes}class Event {eventType: stringattributes: Array<EventAttribute>}class Any {typeUrl: stringvalue: Bytes}
Each handler type comes with its own data structure that is passed as an argument to a mapping function.
- Block handlers receive the
Block
type. - Event handlers receive the
EventData
type. - Transaction handlers receive the
TransactionData
type. - Message handlers receive the
MessageData
type.
As a part of MessageData
the message handler receives a transaction context, which contains the most important information about a transaction that encompasses a message. The transaction context is also available in the EventData
type, but only when the corresponding event is associated with a transaction. Additionally, all handlers receive a reference to a block (HeaderOnlyBlock
).
You can find the full list of types for the Cosmos integration .
It's important to note that Cosmos messages are chain-specific and they are passed to a subgraph in the form of a serialized payload. As a result, the message data needs to be decoded in a mapping function before it can be processed.
An example of how to decode message data in a subgraph can be found .
The first step before starting to write the subgraph mappings is to generate the type bindings based on the entities that have been defined in the subgraph schema file (schema.graphql
). This will allow the mapping functions to create new objects of those types and save them to the store. This is done by using the codegen
CLI command:
$ graph codegen
Once the mappings are ready, the subgraph needs to be built. This step will highlight any errors the manifest or the mappings might have. A subgraph needs to build successfully in order to be deployed to the Graph Node. It can be done using the build
CLI command:
$ graph build
Once your subgraph has been created, you can deploy your subgraph by using the graph deploy
CLI command:
Subgraph Studio
Visit the Subgraph Studio to create a new subgraph.
graph deploy subgraph-name
Local Graph Node (based on default configuration):
graph create subgraph-name --node http://localhost:8020
graph deploy subgraph-name --node http://localhost:8020/ --ipfs http://localhost:5001
The GraphQL endpoint for Cosmos subgraphs is determined by the schema definition, with the existing API interface. Please visit the for more information.
The is the first blockchain in the ecosystem. You can visit the for more information.
Cosmos Hub mainnet is cosmoshub-4
. Cosmos Hub current testnet is theta-testnet-001
.
Other Cosmos Hub networks, i.e. cosmoshub-3
, are halted, therefore no data is provided for them.
Osmosis support in Graph Node and on Subgraph Studio is in beta: please contact the graph team with any questions about building Osmosis subgraphs!
is a decentralized, cross-chain automated market maker (AMM) protocol built on top of the Cosmos SDK. It allows users to create custom liquidity pools and trade IBC-enabled tokens. You can visit the for more information.
Osmosis mainnet is osmosis-1
. Osmosis current testnet is osmo-test-4
.
Here are some example subgraphs for reference: