8 minutes
Construcción de subgrafos en NEAR
This guide is an introduction to building subgraphs indexing smart contracts on the NEAR blockchain.
¿Qué es NEAR?
NEAR is a smart contract platform for building decentralized applications. Visit the official documentation for more information.
¿Qué son los subgrafos NEAR?
The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. Graph Node is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts.
Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs:
- Handlers de bloques: se ejecutan en cada nuevo bloque
- Handlers de recibos: se realizan cada vez que se ejecuta un mensaje en una cuenta específica
Un recibo es el único objeto procesable del sistema. Cuando hablamos de “procesar una transacción” en la plataforma NEAR, esto significa eventualmente “aplicar recibos” en algún momento.
Construcción de un subgrafo NEAR
@graphprotocol/graph-cli
is a command-line tool for building and deploying subgraphs.
@graphprotocol/graph-ts
is a library of subgraph-specific types.
NEAR subgraph development requires graph-cli
above version 0.23.0
, and graph-ts
above version 0.23.0
.
Construir un subgrafo NEAR es muy similar a construir un subgrafo que indexa Ethereum.
Hay tres aspectos de la definición de subgrafo:
subgraph.yaml: the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new kind
of data source.
schema.graphql: a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by the existing documentation.
AssemblyScript Mappings: AssemblyScript code that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality.
Durante el desarrollo del subgrafo hay dos comandos clave:
$ graph codegen # genera tipos a partir del archivo de esquema identificado en el manifiesto$ graph build # genera Web Assembly a partir de los archivos de AssemblyScript y prepara todos los archivos de subgrafo en una carpeta /build
Definición de manifiesto del subgrafo
The subgraph manifest (subgraph.yaml
) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph:
specVersion: 0.0.2schema: file: ./src/schema.graphql # link to the schema filedataSources: - kind: near network: near-mainnet source: account: app.good-morning.near # This data source will monitor this account startBlock: 10662188 # Required for NEAR mapping: apiVersion: 0.0.5 language: wasm/assemblyscript blockHandlers: - handler: handleNewBlock # the function name in the mapping file receiptHandlers: - handler: handleReceipt # the function name in the mapping file file: ./src/mapping.ts # link to the file with the Assemblyscript mappings
- NEAR subgraphs introduce a new
kind
of data source (near
) - The
network
should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR’s mainnet isnear-mainnet
, and NEAR’s testnet isnear-testnet
- NEAR data sources introduce an optional
source.account
field, which is a human-readable ID corresponding to a NEAR account. This can be an account or a sub-account. - NEAR data sources introduce an alternative optional
source.accounts
field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match:[app|good].*[morning.near|morning.testnet]
. If only a list of prefixes or suffixes is necessary the other field can be omitted.
accounts: prefixes: - app - good suffixes: - morning.near - morning.testnet
Las fuentes de datos NEAR admiten dos tipos de handlers:
blockHandlers
: run on every new NEAR block. Nosource.account
is required.receiptHandlers
: run on every receipt where the data source’ssource.account
is the recipient. Note that only exact matches are processed (subaccounts must be added as independent data sources).
Definición de esquema
Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition here.
Asignaciones de AssemblyScript
The handlers for processing events are written in AssemblyScript.
NEAR indexing introduces NEAR-specific data types to the AssemblyScript API.
class ExecutionOutcome { gasBurnt: u64, blockHash: Bytes, id: Bytes, logs: Array<string>, receiptIds: Array<Bytes>, tokensBurnt: BigInt, executorId: string, }class ActionReceipt { predecessorId: string, receiverId: string, id: CryptoHash, signerId: string, gasPrice: BigInt, outputDataReceivers: Array<DataReceiver>, inputDataIds: Array<CryptoHash>, actions: Array<ActionValue>, }class BlockHeader { height: u64, prevHeight: u64,// Always zero when version < V3 epochId: Bytes, nextEpochId: Bytes, chunksIncluded: u64, hash: Bytes, prevHash: Bytes, timestampNanosec: u64, randomValue: Bytes, gasPrice: BigInt, totalSupply: BigInt, latestProtocolVersion: u32, }class ChunkHeader { gasUsed: u64, gasLimit: u64, shardId: u64, chunkHash: Bytes, prevBlockHash: Bytes, balanceBurnt: BigInt, }class Block { author: string, header: BlockHeader, chunks: Array<ChunkHeader>, }class ReceiptWithOutcome { outcome: ExecutionOutcome, receipt: ActionReceipt, block: Block, }
These types are passed to block & receipt handlers:
- Block handlers will receive a
Block
- Receipt handlers will receive a
ReceiptWithOutcome
Otherwise, the rest of the AssemblyScript API is available to NEAR subgraph developers during mapping execution.
This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new json.fromString(...)
function is available as part of the JSON API to allow developers to easily process these logs.
Deployando un subgrafo NEAR
Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node >=v0.26.x
(this version has not yet been tagged & released).
Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names:
near-mainnet
near-testnet
More information on creating and deploying subgraphs on Subgraph Studio can be found here.
As a quick primer - the first step is to “create” your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from your Dashboard: “Create a subgraph”.
Once your subgraph has been created, you can deploy your subgraph by using the graph deploy
CLI command:
$ graph create --node <graph-node-url> <subgraph-name> # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI)$ graph deploy --node <graph-node-url> --ipfs https://api.thegraph.com/ipfs/ <subgraph-name> # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash
La configuración del nodo dependerá de dónde se implemente el subgrafo.
Subgraph Studio
graph authgraph deploy <subgraph-name>
Graph Node Local (basado en la configuración predeterminada)
graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 <subgraph-name>
Una vez que se haya implementado su subgrafo, Graph Node lo indexará. Puede comprobar su progreso consultando el propio subgrafo:
{ _meta { block { number } }}
Indexación NEAR con un Graph Node local
Ejecutar un Graph Node que indexa NEAR tiene los siguientes requisitos operativos:
- NEAR Indexer Framework con instrumentación Firehose
- Componente(s) NEAR Firehose
- Graph Node con endpoint de Firehose configurado
Pronto proporcionaremos más información sobre cómo ejecutar los componentes anteriores.
Consultando un subgrafo NEAR
The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the GraphQL API documentation for more information.
Subgrafos de ejemplo
Here are some example subgraphs for reference:
FAQ
¿Cómo funciona la beta?
El soporte NEAR está en versión beta, lo que significa que puede haber cambios en la API a medida que continuamos trabajando para mejorar la integración. Envíe un correo electrónico a near@thegraph.com para que podamos ayudarlo a crear subgrafos NEAR y mantenerte actualizado sobre los últimos desarrollos!
¿Puede un subgrafo indexar las cadenas NEAR y EVM?
No, un subgrafo sólo puede admitir fuentes de datos de una cadena/red.
¿Pueden los subgrafos reaccionar a activadores más específicos?
Actualmente, solo se admiten los activadores de Bloque y Recibo. Estamos investigando activadores para llamadas a funciones a una cuenta específica. También estamos interesados en admitir activadores de eventos, una vez que NEAR tenga soporte nativo para eventos.
¿Se activarán los handlers de recibos para las cuentas y sus subcuentas?
If an account
is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an accounts
field, with suffixes
and prefixes
specified to match accounts and sub-accounts, for example the following would match all mintbase1.near
sub-accounts:
accounts: suffixes: - mintbase1.near
¿Pueden los subgrafos NEAR realizar view calls a cuentas NEAR durante las asignaciones?
Esto no es compatible. Estamos evaluando si esta funcionalidad es necesaria para la indexación.
¿Puedo usar plantillas de fuente de datos en mi subgrafo NEAR?
Esto no es compatible actualmente. Estamos evaluando si esta funcionalidad es necesaria para la indexación.
Los subgrafos de Ethereum admiten versiones “pendientes” y “actuales”, ¿cómo puedo implementar una versión “pendiente” de un subgrafo NEAR?
La funcionalidad pendiente aún no es compatible con los subgrafos NEAR. Mientras tanto, puedes implementar una nueva versión en un subgrafo “nombrado” diferente y luego, cuando se sincroniza con el encabezado de la cadena, puedes volver a implementarlo en su subgrafo principal “nombrado”, que usará el mismo ID de implementación subyacente, por lo que el subgrafo principal se sincronizará instantáneamente.
Mi pregunta no ha sido respondida, ¿dónde puedo obtener más ayuda para crear subgrafos NEAR?
If it is a general question about subgraph development, there is a lot more information in the rest of the Developer documentation. Otherwise please join The Graph Protocol Discord and ask in the #near channel or email near@thegraph.com.