Skip to main content

Kilt Quick Start

SubQuery TeamAbout 3 min

Kilt Quick Start

This quick start guide introduces SubQuery's Substrate Kilt Spiritnet support by using an example project in Kilt Spiritnet. The example project indexes all Attestations createdopen in new window and revokedopen in new window on the Kilt Spiritnet Blockchainopen 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.

The project that we are developing throughout this guide can be found hereopen in new window

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.

The Kilt-spiritinet-credentials-example project has two entities: Attestation and Aggregation (which has a foreign key to Dapp). These index basic block data such as the timestamp, height, and hash along with some other attributes related to the event.

type Attestation @entity {
  id: ID! #id is ClaimHashOf
  createdDate: Date! #date of creation of the attestation
  createdBlock: BigInt! #block of creation of the attestation
  creator: String! # Account address
  creationClaimHash: String!
  attestationId: String! #Id of the attester
  hash: String! #extrensic hash
  delegationID: String
  revokedDate: Date
  revokedBlock: BigInt
  revokedClaimHash: String
}

type Aggregation @entity {
  # This is an entity allowing us to calculate all the attesations created and revoked in one day
  id: ID! # AAAA-MM-DD
  attestationsCreated: Int!
  attestationsRevoked: Int!
}
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.

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 Polkadot, there are three types of mapping handlers (and you can have more than one in each project):

  • BlockHanders: On each and every block, run a mapping function
  • EventHandlers: On each and every Event that matches optional filter criteria, run a mapping function
  • CallHanders: On each and every extrinsic call 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 look for on the blockchain to start indexing.

We are indexing all attestations creation and revoking events from the Kilt Spiritnet blockchain. This section in the Project Manifest now imports all the correct definitions and lists the triggers that we look for on the blockchain when indexing.

{
  dataSources: [
    {
      kind: SubstrateDatasourceKind.Runtime,
      startBlock: 1,
      mapping: {
        file: "./dist/index.js",
        handlers: [
          {
            kind: SubstrateHandlerKind.Event,
            handler: "handleAttestationCreated",
            filter: {
              module: "attestation",
              method: "AttestationCreated",
            },
          },
          {
            kind: SubstrateHandlerKind.Event,
            handler: "handleAttestationRevoked",
            filter: {
              module: "attestation",
              method: "AttestationRevoked",
            },
          },
        ],
      },
    },
  ],
}

The above code indicates that you will be running a handleAttestationCreated mapping function whenever there is an AttestationCreated event on any transaction from the Kilt Blockchain. Similarly, we will run the handleAttestationRevoked mapping function whenever there is a AttestationRevoked log on Kilt.

Check out our Substrate documentation to get more information about the Project Manifest (project.ts) file for Polkadot chains.

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

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. There is one more function that was created in the mapping file handleDailyUpdate. This function allows us to calculate daily aggregated attestations created and revoked.

export async function handleAttestationCreated(
  event: SubstrateEvent
): Promise<void> {
  logger.info(
    `New attestation created at block ${event.block.block.header.number}`
  );
  // A new attestation has been created.\[attester ID, claim hash, CType hash, (optional) delegation ID\]
  const {
    event: {
      data: [attesterID, claimHash, hash, delegationID],
    },
  } = event;

  const attestation = Attestation.create({
    id: claimHash.toString(),
    createdDate: event.block.timestamp,
    createdBlock: event.block.block.header.number.toBigInt(),
    creator: event.extrinsic.extrinsic.signer.toString(),
    creationClaimHash: claimHash.toString(),
    hash: hash.toString(),
    attestationId: attesterID.toString(),
    delegationID: delegationID ? delegationID.toString() : null,
  });

  await attestation.save();

  await handleDailyUpdate(event.block.timestamp, "CREATED");
}

export async function handleAttestationRevoked(
  event: SubstrateEvent
): Promise<void> {
  logger.info(
    `New attestation revoked at block ${event.block.block.header.number}`
  );
  // An attestation has been revoked.\[account id, claim hash\]
  const {
    event: {
      data: [accountID, claimHash],
    },
  } = event;

  const attestation = await Attestation.get(claimHash.toString());

  assert(attestation, "Can't find an attestation");
  attestation.revokedDate = event.block.timestamp;
  attestation.revokedBlock = event.block.block.header.number.toBigInt();
  attestation.revokedClaimHash = claimHash.toString();

  await attestation.save();

  await handleDailyUpdate(event.block.timestamp, "REVOKED");
}

export async function handleDailyUpdate(
  date: Date,
  type: "CREATED" | "REVOKED"
): Promise<void> {
  const id = date.toISOString().slice(0, 10);
  let aggregation = await Aggregation.get(id);
  if (!aggregation) {
    aggregation = Aggregation.create({
      id,
      attestationsCreated: 0,
      attestationsRevoked: 0,
    });
  }
  if (type === "CREATED") {
    aggregation.attestationsCreated++;
  } else if (type === "REVOKED") {
    aggregation.attestationsRevoked++;
  }

  await aggregation.save();
}

The handleAttestationCreated function receives event data from the Kilt execution environment whenever an call matches the filters that was specified previously in the project.ts. It instantiates a new Attestation entity and populates the fields with data from the Substrate Call payload. Then the .save() function is used to save the new entity (SubQuery will automatically save this to the database). The same can be said for the handleAttestationRevoked. The only difference is for the attestations revoked we do not need to instantiate a new Attestation entity.

There is one more function that was created in the mapping file handleDailyUpdate. This function allows us to calculate daily aggregated attestations created and revoked.

Note

For more information on mapping functions, please refer to our Mappings documentation.

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 {
  attestations(first: 2, orderBy: CREATED_DATE_DESC) {
    nodes {
      id
      createdDate
      attestationId
      hash
      delegationID
      revokedDate
    }
  }
  aggregations(first: 2, orderBy: ID_DESC) {
    nodes {
      id
      attestationsCreated
      attestationsRevoked
    }
  }
}

Tips

There is a Docs tab on the right side of the playground which should open a documentation drawer. This documentation is automatically generated and helps you find what entities and methods you can query. To learn more about the GraphQL Query language here.

You should see results similar to below:

{
  "data": {
    "attestations": {
      "nodes": [
        {
          "id": "0xacdd8c76cb2cffde5e1924d8b879655e75dae2617ead6ec0a87328cbe4ef5ca8",
          "createdDate": "2022-09-29T10:38:54.542",
          "attestationId": "4pnfkRn5UurBJTW92d9TaVLR2CqJdY4z5HPjrEbpGyBykare",
          "hash": "0xd8c61a235204cb9e3c6acb1898d78880488846a7247d325b833243b46d923abe",
          "delegationID": "",
          "revokedDate": null
        },
        {
          "id": "0xa9bb0bc92ad7eb79fbde4983de508794fa2b8e9f9f88236be24c2ac517f29750",
          "createdDate": "2022-09-29T10:36:48.306",
          "attestationId": "4pnfkRn5UurBJTW92d9TaVLR2CqJdY4z5HPjrEbpGyBykare",
          "hash": "0xcef8f3fe5aa7379faea95327942fd77287e1c144e3f53243e55705f11e890a4c",
          "delegationID": "",
          "revokedDate": null
        }
      ]
    },
    "aggregations": {
      "nodes": [
        {
          "id": "2022-09-29",
          "attestationsCreated": 5,
          "attestationsRevoked": 0
        },
        {
          "id": "2022-09-28",
          "attestationsCreated": 23,
          "attestationsRevoked": 0
        }
      ]
    }
  }
}

Congratulations! You have now a locally running SubQuery project that accepts GraphQL API requests for events related to attestations createdopen in new window and revokedopen in new window on the Kilt Spiritnet Blockchainopen 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.