Skip to main content

Cronos Quick Start

SubQuery TeamAbout 3 min

Cronos Quick Start

The goal of this quick start guide is to adapt the standard starter project in the Cronos Network and then begin indexing all transfers of Cro Crow Tokenopen in new window.


Important

Cronos is an EVM compatible (Ethermint) chain, as such there are two options for indexing Cronos data. You can index chain data via the standard Cosmos RPC interface, or via Ethereum APIs. For Cronos, we provide a starter project for each.

Info

This network is based on the Cosmos SDK, which means you can index chain data via the standard Cosmos RPC interface.

Before we begin, make sure that you have initialised your project using the provided steps in the Start Here section. You must complete the suggested 4 stepsopen in new window for Cosmos users.

Tips

The final code of this project can be found hereopen in new window.

Your Project Manifest File

The Project Manifest file is an entry point to your project. It defines most of the details on how SubQuery will index and transform the chain data.

For Cosmos chains, there are four types of mapping handlers (and you can have more than one in each project):

  • BlockHanders: On each and every block, run a mapping function
  • TransactionHandlers: On each and every transaction, run a mapping function
  • MessageHandlers: On each and every message that matches optional filter criteria, run a mapping function
  • EventHanders: On each and every event that matches optional filter criteria, run a mapping function

Note that the manifest file has already been set up correctly and doesn’t require significant changes, but you need to change the datasource handlers. This section lists the triggers that the manifest file looks for on the blockchain to start indexing.

Important

There are two versions of this file depending on your choice to index data via the ETH or Cosmos RPC

ETH
{
  dataSources: [
    {
      kind: EthereumDatasourceKind.Runtime,
      // Contract creation of Pangolin Token https://snowtrace.io/tx/0xfab84552e997848a43f05e440998617d641788d355e3195b6882e9006996d8f9
      startBlock: 446,
      options: {
        // Must be a key of assets
        abi: "erc20",
        address: "0x5c7f8a570d578ed84e63fdfa7b1ee72deae1ae23",
        // Wrapped CRO https://cronos.org/explorer/address/0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23
      },
      assets: new Map([["erc20", { file: "./erc20.abi.json" }]]),
      mapping: {
        file: "./dist/index.js",
        handlers: [
          {
            kind: EthereumHandlerKind.Call,
            handler: "handleTransaction",
            filter: {
              /**
               * The function can either be the function fragment or signature
               * function: '0x095ea7b3'
               * function: '0x7ff36ab500000000000000000000000000000000000000000000000000000000'
               */
              function: "approve(address guy, uint256 wad)",
            },
          },
          {
            kind: EthereumHandlerKind.Event,
            handler: "handleLog",
            filter: {
              /**
               * Follows standard log filters https://docs.ethers.io/v5/concepts/events/
               * address: "0x60781C2586D68229fde47564546784ab3fACA982"
               */
              topics: ["Transfer(address src, address dst, uint256 wad)"],
            },
          },
        ],
      },
    },
  ],
}

The above code defines that you will be running a handleTransfer mapping function whenever there is an event emitted with the transfer method. Check out our Manifest File documentation to get more information about the Project Manifest (project.ts) file.

Note

Please note that Cro Crow token requires a specific ABI interface. You need to:

Check out our Manifest File documentation to get more information about the Project Manifest (project.ts) file.

Update Your GraphQL Schema File

The schema.graphql file determines the shape of your data from SubQuery due to the mechanism of the GraphQL query language. Hence, updating the GraphQL Schema file is the perfect place to start. It allows you to define your end goal right at the start.

Update the schema.graphql file as follows. The aim is to index all transfers of Cro Crow Tokenopen in new window.

type Transfer @entity {
  id: ID! # Transfer hash
  from: String!
  to: String!
  tokenId: BigInt!
}

Note

Importantly, these relationships can not only establish one-to-many connections but also extend to include many-to-many associations. To delve deeper into entity relationships, you can refer to this section. If you prefer a more example-based approach, our dedicated Hero Course Module can provide further insights.

SubQuery simplifies and ensures type-safety when working with GraphQL entities, actions, and transactions.

yarn
yarn codegen

This action will generate a new directory (or update the existing one) named src/types. Inside this directory, you will find automatically generated entity classes corresponding to each type defined in your schema.graphql. These classes facilitate type-safe operations for loading, reading, and writing entity fields. You can learn more about this process in the GraphQL Schema section.

If you've expressed a preference to employ the Cosmos message based on the provided proto files, this command will also generate types for your listed protobufs and save them into src/types directory, providing you with more typesafety. For example, you can find Osmosis' protobuf definitions in the official documentationopen in new window. Read about how this is done in Cosmos Codegen from CosmWasm Protobufs and Cosmos Manifest File Configuration.

Now that you have made essential changes to the GraphQL Schema file, let’s go ahead with the next configuration.

If you're creating as an CosmWasm based project, this command will also generate types for your listed protobufs and save them into src/types directory, providing you with more typesafety. Read about how this is done in Cosmos Codegen from CosmWasm Protobufs.

If you're creating as an EVM based project, this command will also generate ABI types and save them into src/types using the npx typechain --target=ethers-v5 command, allowing you to bind these contracts to specific addresses in the mappings and call read-only contract methods against the block being processed.

It will also generate a class for every contract event to provide easy access to event parameters, as well as the block and transaction the event originated from. Read about how this is done in EVM Codegen from ABIs.

Check out the GraphQL Schema documentation to get in-depth information on schema.graphql file.

Now that you have made essential changes to the GraphQL Schema file, let’s proceed ahead with the Mapping Function’s configuration.

Add a Mapping Function

Mapping functions define how blockchain data is transformed into the optimised GraphQL entities that we previously defined in the schema.graphql file.

Navigate to the default mapping function in the src/mappings directory. You will see setup types for ABI TransferEventArgs and ApproveCallArgs. Delete those for approvals. You will also see two exported functions: handleEthermintEvmEvent & handleEthermintEvmCall or handleLog & handleTransaction. Delete them as well.

Important

There are two versions of this file depending on your choice to index data via the ETH or Cosmos RPC

Update your mapping files to match the following (note the additional imports):

ETH
import { Transfer } from "../types";
import { EthereumLog } from "@subql/types-ethereum";
import { BigNumber } from "@ethersproject/bignumber";

// Setup types from ABI
type TransferEventArgs = [string, string, BigNumber] & {
  from: string;
  to: string;
  tokenId: BigNumber;
};

// Save all transfers
export async function handleTransfer(
  log: EthereumLog<TransferEventArgs>,
): Promise<void> {
  const transfer = Transfer.create({
    id: log.transactionHash,
    from: log.args.from,
    to: log.args.to,
    tokenId: log.args.tokenId.toBigInt(),
  });

  await transfer.save();
}

Check out our Mappings documentation and get information on the mapping functions in detail.

Build Your Project

Next, build your work to run your new SubQuery project. Run the build command from the project's root directory as given here:

yarn
yarn build

Important

Whenever you make changes to your mapping functions, you must rebuild your project.

Now, you are ready to run your first SubQuery project. Let’s check out the process of running your project in detail.

Whenever you create a new SubQuery Project, first, you must run it locally on your computer and test it and using Docker is the easiest and quickiest way to do this.

Run Your Project Locally with Docker

The docker-compose.yml file defines all the configurations that control how a SubQuery node runs. For a new project, which you have just initialised, you won't need to change anything.

However, visit the Running SubQuery Locally to get more information on the file and the settings.

Run the following command under the project directory:

yarn
yarn start:docker

Note

It may take a few minutes to download the required images and start the various nodes and Postgres databases.

Query your Project

Next, let's query our project. Follow these three simple steps to query your SubQuery project:

  1. Open your browser and head to http://localhost:3000.

  2. You will see a GraphQL playground in the browser and the schemas which are ready to query.

  3. Find the Docs tab on the right side of the playground which should open a documentation drawer. This documentation is automatically generated and it helps you find what entities and methods you can query.

Try the following queries to understand how it works for your new SubQuery starter project. Don’t forget to learn more about the GraphQL Query language.

{
  query {
    transfers(first: 5) {
      nodes {
        id
        to
        from
        tokenId
      }
    }
  }
}

You will see the result similar to below:

{
  "data": {
    "transfers": {
      "nodes": [
        {
          "id": "0xff2bcbf7445c48f95b9e9bb770076e1562db2b58881338ea65c8c60aae1f4d20",
          "from": "0xe40E86209bf7A563B23dc5625ea968F9DD9269fA",
          "to": "0x281c2b2a0d5a3db358356537Fb4E1ac6Df9715f0",
          "tokenId": "1160"
        },
        {
          "id": "0xfbc0594cde0776813f02804e816ecd153f0a3e201523479f93f85b5423e5e1c6",
          "from": "0x9B94F48372f5ED14f860B86f606ffb61D908E4dC",
          "to": "0x05d6889ea1593b6e58B3366A95Ac923FC00A37AA",
          "tokenId": "4921"
        },
        {
          "id": "0xc601f604b5c3a6c78257b0e946429d7085c7a9f04b4c985d499c1118465bc30f",
          "from": "0x00779809C0089d269C719F5953F7528E4dcE1Bdc",
          "to": "0x45DfaDC5e74f8Fb62Be7893aA7c1f34db7C26D8d",
          "tokenId": "7085"
        }
      ]
    }
  }
}

Note

The final code of this project can be found hereopen in new window.

What's next?

Congratulations! You have now a locally running SubQuery project that accepts GraphQL API requests for transferring data.

Tip

Find out how to build a performant SubQuery project and avoid common mistakes in Project Optimisation.

Click here to learn what should be your next step in your SubQuery journey.