Mappings

Mappings describe how Substate events should be handled by the indexer

A mapping file is a standalone typescript module defining how the Substrate events of interest should be handled by the Hydra indexer.

The event handlers (aka mappings) should by convention be named <RuntimeModule>_<EventName> . For example, a handler for treasury.Proposal events should be named treasury_Proposal

Each handler must have exactly two arguments exported by the Indexer: the db handle which gives access to the database and SubstrateEvent which contains all the necessary data extracted by the indexer from the Substrate chain.

Let us look at the sample mapping generated by the scaffolder

import { SubstrateEvent, DB } from '../generated/indexer';
import { Proposal } from '../generated/graphql-server/src/modules/proposal/proposal.model';
import { ProposalStatus } from '../generated/graphql-server/src/modules/enums/enums';
import { assert } from 'console';
import * as BN from 'bn.js';

// New proposal
export async function handleProposed(db: DB, event: SubstrateEvent) {
  const { ProposalIndex } = event.event_params;
  if (event.extrinsic) {
    const proposal = new Proposal();
    proposal.proposalIndex = new BN(ProposalIndex.toString());
    proposal.value = new BN(event.extrinsic.args[0].toString());
    proposal.bond = new BN(event.extrinsic.args[0].toString());
    proposal.beneficiary = Buffer.from(event.extrinsic.args[1].toString());
    proposal.proposer = Buffer.from(event.extrinsic.signer.toString());
    proposal.status = ProposalStatus.NONE;

    await db.save<Proposal>(proposal);
  }
}

Note that required entity classes are exported from

../generated/graphql-server/src/modules/<entity type>/<entity type>

and this is where all the auto-generated classes live by default.

Next, the body of the handler transforms the event parameters and extrinsic arguments into the properties of the entity. There is currently no way to enforce type safety here and one should instead inspect the event parameters and extrinsics for the event in question. In the example above, we can consult the Kusama explorer and check that

  • ProposalIndex is a single named param of treasury.Proposed event

  • The extrinsic has to arguments: value and beneficiary, propagated to the entity in a straightforward fashion.

Type-safe mappings and runtime upgrades will be supported in future releases of Hydra.

Last updated