subgraphs > Developing > Creating > Writing AssemblyScript Mappings

Writing AssemblyScript Mappings

Reading time: 4 min

Aperçu

Lien vers cette section

The mappings take data from a particular source and transform it into entities that are defined within your schema. Mappings are written in a subset of TypeScript called AssemblyScript which can be compiled to WASM (WebAssembly). AssemblyScript is stricter than normal TypeScript, yet provides a familiar syntax.

Écriture de mappages

Lien vers cette section

For each event handler that is defined in subgraph.yaml under mapping.eventHandlers, create an exported function of the same name. Each handler must accept a single parameter called event with a type corresponding to the name of the event which is being handled.

In the example subgraph, src/mapping.ts contains handlers for the NewGravatar and UpdatedGravatar events:

import { NewGravatar, UpdatedGravatar } from '../generated/Gravity/Gravity'
import { Gravatar } from '../generated/schema'
export function handleNewGravatar(event: NewGravatar): void {
let gravatar = new Gravatar(event.params.id)
gravatar.owner = event.params.owner
gravatar.displayName = event.params.displayName
gravatar.imageUrl = event.params.imageUrl
gravatar.save()
}
export function handleUpdatedGravatar(event: UpdatedGravatar): void {
let id = event.params.id
let gravatar = Gravatar.load(id)
if (gravatar == null) {
gravatar = new Gravatar(id)
}
gravatar.owner = event.params.owner
gravatar.displayName = event.params.displayName
gravatar.imageUrl = event.params.imageUrl
gravatar.save()
}

The first handler takes a NewGravatar event and creates a new Gravatar entity with new Gravatar(event.params.id.toHex()), populating the entity fields using the corresponding event parameters. This entity instance is represented by the variable gravatar, with an id value of event.params.id.toHex().

The second handler tries to load the existing Gravatar from the Graph Node store. If it does not exist yet, it is created on-demand. The entity is then updated to match the new event parameters before it is saved back to the store using gravatar.save().

ID recommandés pour la création de nouvelles entités

Lien vers cette section

It is highly recommended to use Bytes as the type for id fields, and only use String for attributes that truly contain human-readable text, like the name of a token. Below are some recommended id values to consider when creating new entities.

  • transfer.id = event.transaction.hash

  • let id = event.transaction.hash.concatI32(event.logIndex.toI32())

  • For entities that store aggregated data, for e.g, daily trade volumes, the id usually contains the day number. Here, using a Bytes as the id is beneficial. Determining the id would look like

let dayID = event.block.timestamp.toI32() / 86400
let id = Bytes.fromI32(dayID)
  • Convert constant addresses to Bytes.

const id = Bytes.fromHexString('0xdead...beef')

There is a Graph Typescript Library which contains utilities for interacting with the Graph Node store and conveniences for handling smart contract data and entities. It can be imported into mapping.ts from @graphprotocol/graph-ts.

Traitement des entités ayant des identifiants identiques

Lien vers cette section

Lors de la création et de l'enregistrement d'une nouvelle entité, si une entité avec le même ID existe déjà, les propriétés de la nouvelle entité sont toujours préférées lors du processus de fusion. Cela signifie que l'entité existante sera mise à jour avec les valeurs de la nouvelle entité.

Si une valeur nulle est intentionnellement définie pour un champ de la nouvelle entité avec le même ID, l'entité existante sera mise à jour avec la valeur nulle.

Si aucune valeur n'est définie pour un champ de la nouvelle entité avec le même ID, le champ aura également la valeur null.

Génération de code

Lien vers cette section

Afin de faciliter et de sécuriser le travail avec les contrats intelligents, les événements et les entités, la CLI Graph peut générer des types AssemblyScript à partir du schéma GraphQL du subgraph et des ABI de contrat inclus dans les sources de données.

Cela se fait avec

graph codegen [--output-dir <OUTPUT_DIR>] [<MANIFEST>]

but in most cases, subgraphs are already preconfigured via package.json to allow you to simply run one of the following to achieve the same:

# Yarn
yarn codegen
# NPM
npm run codegen

This will generate an AssemblyScript class for every smart contract in the ABI files mentioned in subgraph.yaml, 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. All of these types are written to <OUTPUT_DIR>/<DATA_SOURCE_NAME>/<ABI_NAME>.ts. In the example subgraph, this would be generated/Gravity/Gravity.ts, allowing mappings to import these types with.

import {
// La classe de contrat :
Gravity,
// Les classes d'événements :
NewGravatar,
UpdatedGravatar,
} from '../generated/Gravity/Gravity'

In addition to this, one class is generated for each entity type in the subgraph's GraphQL schema. These classes provide type-safe entity loading, read and write access to entity fields as well as a save() method to write entities to store. All entity classes are written to <OUTPUT_DIR>/schema.ts, allowing mappings to import them with

import { Gravatar } from '../generated/schema'

Note: The code generation must be performed again after every change to the GraphQL schema or the ABIs included in the manifest. It must also be performed at least once before building or deploying the subgraph.

Code generation does not check your mapping code in src/mapping.ts. If you want to check that before trying to deploy your subgraph to Graph Explorer, you can run yarn build and fix any syntax errors that the TypeScript compiler might find.

Modifier une page

Précédente
The Graph QL Schema
Suivante
Advance Subgraph Features
Modifier une page