Skip to main content

Multichain Quick Start - Kava (EVM & Cosmos)

SubQuery TeamAbout 4 min

Multichain Quick Start - Kava (EVM & Cosmos)

This page explains how to create an multi-chain indexer for Kavaopen in new window, the first Layer-1 blockchain to combine the speed and scalability of the Cosmos SDK with the developer support of Ethereum, empowering developers to build for Web3 and next-gen blockchain technologies through its unique co-chain architecture.

File not found

After finishing this guide, you'll get the ability to connect event data efficiently across various diverse networks. Additionally, you'll obtain the know-how to set up a SubQuery indexer that enables monitoring, tracking, and aggregating events within a single unified system.

In the earlier Quickstart section , you should have taken note of three crucial files. To initiate the setup of a project from scratch, you can proceed to follow the steps outlined in the initialisation description.

As a prerequisite, you will need to generate types from the ABI files of each smart contract. Additionally, you can kickstart your project by using the EVM Scaffolding approach (detailed here). You'll find all the relevant events to be scaffolded in the documentation for each type of smart contract.

For instance, you can locate the ABI for USDT on Kava EVM smart contract at the bottom of this pageopen in new window.

To prepare for the Cosmos segment, generating types from the proto files is a necessary step. You can get these types from the officially published Cosmos sources, available hereopen in new window.

In the earlier Quickstart section , you should have taken note of three crucial files. To initiate the setup of a project from scratch, you can proceed to follow the steps outlined in the initialisation description.

Note

Check the final code repository hereopen in new window to observe the integration of all previously mentioned configurations into a unified codebase.

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.

To begin, we will establish an EVM indexer. In this illustration, we introduce specific a smart contract along with its respective methods and logs:

project.yaml
dataSources:
  - kind: ethereum/Runtime
    startBlock: 5391456
    options:
      abi: erc20
      address: "0x919C1c267BC06a7039e03fcc2eF738525769109c"
    assets:
      erc20:
        file: ./abis/erc20.abi.json
    mapping:
      file: ./dist/index.js
      handlers:
        - kind: ethereum/LogHandler
          handler: handleEVMLog
          filter:
            topics:
              - Transfer(address from, address to, uint256 value)

In the provided snippet, we're managing an individual log named Transfer. This log is set to be sent as an argument to a handling function known as handleEVMLog.

Note

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

Next, change the name of the file mentioned above to kava-evm.yaml to indicate that this file holds the Ethereum configuration.

File not found

subquery-multichain.yaml
specVersion: 1.0.0
query:
  name: "@subql/query"
  version: "*"
projects:
  - kava-cosmos.yaml
  - kava-evm.yaml

Also, you will end up with the individual chains' manifest files like those:

kava-evm.yaml
specVersion: 1.0.0
version: 0.0.1
name: kava-evm-starter
description: >-
  In this manifest file, we set up the SubQuery indexer to fetch all USDT transactions on the Kava EVM Network
runner:
  node:
    name: "@subql/node-ethereum"
    version: ">=3.0.0"
  query:
    name: "@subql/query"
    version: "*"
schema:
  file: ./schema.graphql
network:
  chainId: "2222"
  endpoint:
    - https://evm.kava.io
    - https://evm.data.kava.io
    - https://evm.data.kava.chainstacklabs.com
dataSources:
  - kind: ethereum/Runtime
    startBlock: 5391456
    options:
      abi: erc20
      address: "0x919C1c267BC06a7039e03fcc2eF738525769109c"
    assets:
      erc20:
        file: ./abis/erc20.abi.json
    mapping:
      file: ./dist/index.js
      handlers:
        - kind: ethereum/LogHandler
          handler: handleEVMLog
          filter:
            topics:
              - Transfer(address from, address to, uint256 value)
repository: https://github.com/subquery/ethereum-subql-starter

File not found

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.

type CosmosTransfers @entity {
  id: ID!
  blockHeight: BigInt
  txHash: String
  fromAddress: Address!
  toAddress: Address!
  amount: String
  denomination: String
}

type EVMTransfers @entity {
  id: ID! # Transaction hash
  value: BigInt!
  to: Address!
  from: Address!
  contractAddress: Address!
}

type Address @entity {
  id: ID!
  cosmosAddress: String!
  evmAddress: String!
}

This schema defines three types of transfers: CosmosTransfers, representing transfers within the Cosmos network; EVMTransfers, representing transfers within EVM; and Address, which links both Cosmos and EVM addresses.

CosmosTransfers holds details like block height, transaction hash, sender and receiver addresses, transferred amount, and denomination. EVMTransfers stores transaction hash, transferred value, sender, receiver, and contract address. Address links IDs with respective Cosmos and EVM addresses through their unique identifiers.

SubQuery simplifies and ensures type-safety when working with GraphQL entities, smart contracts, events, cosmos messages, and etc. The SubQuery CLI will generate types based on your project's GraphQL schema and any contract ABIs included in the data sources.

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.

It will also generate a class for every contract event, offering convenient access to event parameters, as well as information about the block and transaction from which the event originated. You can find detailed information on how this is achieved in the EVM Codegen from ABIs section. All of these types are stored in the src/types/abi-interfaces and src/types/contracts directories.

Also 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.

You can conveniently import all these types:

import { EVMTransfers, CosmosTransfers, Address } from "../types";
import { CosmosEvent } from "@subql/types-cosmos";
import {
  ApproveTransaction,
  TransferLog,
} from "../types/abi-interfaces/Erc20Abi";

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.

Setting up mappings contract is straightforward. In this instance, the mappings are stored within the src/mappings directory, with the sole mapping file being mappingHandlers.ts. Now, let's take a closer look at it:

function kavaToEthAddress(kavaAddress: string) {
  return ethers.utils.getAddress(
    ethers.utils.hexlify(bech32.fromWords(bech32.decode(kavaAddress).words)),
  );
}

function ethToKavaAddress(ethereumAddress: string) {
  return bech32.encode(
    "kava",
    bech32.toWords(
      ethers.utils.arrayify(ethers.utils.getAddress(ethereumAddress)),
    ),
  );
}

async function checkGetUserAddress(
  cosmosAddress: string,
  evmAddress: string,
): Promise<Address> {
  let addressId = `${cosmosAddress}-${evmAddress}`;
  let userRecord = await Address.get(addressId);
  if (!userRecord) {
    userRecord = Address.create({
      id: addressId,
      cosmosAddress: cosmosAddress,
      evmAddress: evmAddress,
    });
    await userRecord.save();
  }
  return userRecord;
}

export async function handleEVMLog(transferLog: TransferLog): Promise<void> {
  logger.info("transaction: " + transferLog.transactionHash);
  let from = transferLog.transaction.from.toString();
  let to = transferLog.transaction.to.toString();
  let contractAddress = transferLog.address;
  assert(transferLog.args, "Expected args to exist");
  const transaction = EVMTransfers.create({
    id: transferLog.transactionHash,
    value: transferLog.args.value.toBigInt(),
    fromId: (
      await checkGetUserAddress(ethToKavaAddress(from), from)
    ).id.toString(),
    toId: (await checkGetUserAddress(ethToKavaAddress(to), to)).id.toString(),
    contractAddressId: (
      await checkGetUserAddress(
        ethToKavaAddress(contractAddress),
        contractAddress,
      )
    ).id.toString(),
  });

  await transaction.save();
}

export async function handleCosmosEvent(event: CosmosEvent): Promise<void> {
  logger.info(`New transfer event at block ${event.block.block.header.height}`);
  let from = event.msg.msg.decodedMsg.fromAddress;
  let to = event.msg.msg.decodedMsg.toAddress;
  const newTransfers = CosmosTransfers.create({
    id: `${event.tx.hash}-${event.msg.idx}-${event.idx}`,
    blockHeight: BigInt(event.block.block.header.height),
    txHash: event.tx.hash,
    fromAddressId: (
      await checkGetUserAddress(from, kavaToEthAddress(from))
    ).id.toString(),
    toAddressId: (
      await checkGetUserAddress(to, kavaToEthAddress(to))
    ).id.toString(),
    amount: event.msg.msg.decodedMsg.amount[0].amount,
    denomination: event.msg.msg.decodedMsg.amount[0].denom,
  });

  await newTransfers.save();
}

The handleEVMLog function processes Ethereum Virtual Machine (EVM) transfer logs, extracting relevant information such as transaction details, addresses involved, and amounts transferred. It creates and saves corresponding EVMTransfers records.

Similarly, the handleCosmosEvent function deals with Cosmos transfer events, extracting details like block height, transaction hash, addresses, amount, and denomination before creating and storing CosmosTransfers records.

Both handlers use the util functions to convert addresses from Kava (a blockchain platform) to Ethereum and vice versa (kavaToEthAddress and ethToKavaAddress respectively). The checkGetUserAddress function checks if a user's address exists, creating a new record if not.

🎉 At this stage, we have successfully incorporated all the desired entities and mappings that can be retrieved from networks. For each of these entities, we've a single mapping handler to structure and store the data in a queryable format.

Note

Check the final code repository hereopen in new window to observe the integration of all previously mentioned configurations into a unified codebase.

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 {
  cosmosTransfers(first: 1) {
    nodes {
      id
      blockHeight
      txHash
      fromAddressId
      toAddressId
      amount
      denomination
    }
  }
  eVMTransfers(first: 1) {
    nodes {
      id
      value
      fromId
      contractAddressId
    }
  }
  addresses(first: 1) {
    nodes {
      id
      cosmosAddress
      evmAddress
    }
  }
}

The responce will be the following:

{
  "data": {
    "cosmosTransfers": {
      "nodes": [
        {
          "id": "009A7E670FB2EF68A17EEB2E198E0B85C35A6DDE8E95CCEC4DD64021B6E90476-0-1078",
          "blockHeight": "8039327",
          "txHash": "009A7E670FB2EF68A17EEB2E198E0B85C35A6DDE8E95CCEC4DD64021B6E90476",
          "fromAddressId": "kava1m6x4n93x0axf2hh057z26wug8gklkw8zs7750k-0xDE8D5996267f4c955eeFA784Ad3b883A2DFB38e2",
          "toAddressId": "kava1wndgd4hzpmhlnvfekcvfrhy29uayq3wqt8665c-0x74dA86d6e20EEff9B139b61891DC8A2F3a4045C0",
          "amount": "109889000",
          "denomination": "ukava"
        }
      ]
    },
    "eVMTransfers": {
      "nodes": [
        {
          "id": "0x0130a657ee77972d4617864ac4c5d8caf0c429c949df4afad1ecf8d66a743018",
          "value": "316477976",
          "fromId": "kava1aymgtuam5qcpdupt6xpghtwkr9vc3k2s8xa3ez-0xe93685f3bBA03016F02bD1828BaDD6195988D950",
          "contractAddressId": "kava1jxwpcfnmcp48qw0q8lxzaaec2ftkjyyukk965k-0x919C1c267BC06a7039e03fcc2eF738525769109c"
        }
      ]
    },
    "addresses": {
      "nodes": [
        {
          "id": "kava107cchp25ly68yydyzvauprnwlr60739e3z7kem-0x7FB18B8554f9347211A4133BC08e6eF8F4FF44B9",
          "cosmosAddress": "kava107cchp25ly68yydyzvauprnwlr60739e3z7kem",
          "evmAddress": "0x7FB18B8554f9347211A4133BC08e6eF8F4FF44B9"
        }
      ]
    }
  }
}

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.