Skip to main content
Subgraphs provide indexed blockchain data through GraphQL APIs, enabling efficient querying of Mezo protocol data. This guide covers subgraph endpoints and deployment with Goldsky.

Overview

Mezo subgraphs provide:

Indexed Data

Fast access to blockchain data without scanning blocks

GraphQL API

Flexible querying with powerful filtering and sorting

Real-time Updates

Live synchronization with the blockchain

Custom Logic

Transform and aggregate on-chain data

Development Setup

Prerequisites

Before working with subgraphs, ensure you have:
  • Node.js 18+ (check repository’s .nvmrc for exact version)
  • npm or yarn package manager
  • Git
  • Graph CLI
  • Goldsky account

Installation

git clone https://github.com/mezo-org/subgraphs.git
cd subgraphs

Repository Structure

Mezo subgraph repositories contain:

Schema Definition

Define your data models in schema.graphql:
schema.graphql
type Token @entity {
  id: ID!
  name: String!
  symbol: String!
  decimals: Int!
  totalSupply: BigInt!
}

type Transfer @entity {
  id: ID!
  from: Bytes!
  to: Bytes!
  amount: BigInt!
  timestamp: BigInt!
  transactionHash: Bytes!
}
Use the @entity directive to mark types that should be stored and queryable.

Subgraph Manifest

Configure your subgraph in subgraph.yaml:
subgraph.yaml
specVersion: 0.0.5
schema:
  file: ./schema.graphql
dataSources:
  - kind: ethereum
    name: MUSDToken
    network: mezo-mainnet
    source:
      address: "0x..." # Contract address
      abi: MUSD
      startBlock: 0
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.7
      language: wasm/assemblyscript
      entities:
        - Token
        - Transfer
      abis:
        - name: MUSD
          file: ./abis/MUSD.json
      eventHandlers:
        - event: Transfer(indexed address,indexed address,uint256)
          handler: handleTransfer
      file: ./src/mapping.ts

Mapping Logic

Implement event handlers in src/mapping.ts:
src/mapping.ts
import { Transfer as TransferEvent } from "../generated/MUSDToken/MUSD"
import { Transfer, Token } from "../generated/schema"
import { BigInt } from "@graphprotocol/graph-ts"

export function handleTransfer(event: TransferEvent): void {
  // Create transfer entity
  let transfer = new Transfer(
    event.transaction.hash.toHex() + "-" + event.logIndex.toString()
  )
  
  transfer.from = event.params.from
  transfer.to = event.params.to
  transfer.amount = event.params.value
  transfer.timestamp = event.block.timestamp
  transfer.transactionHash = event.transaction.hash
  
  transfer.save()
  
  // Update token entity
  let token = Token.load("1")
  if (token == null) {
    token = new Token("1")
    token.name = "Mezo USD"
    token.symbol = "MUSD"
    token.decimals = 18
    token.totalSupply = BigInt.fromI32(0)
  }
  
  token.save()
}

Code Generation

Generate TypeScript types from your schema:
graph codegen

Testing

Unit Tests

Write unit tests for your mappings:
tests/musd.test.ts
import { describe, test, assert } from "matchstick-as/assembly/index"
import { handleTransfer } from "../src/mapping"
import { createTransferEvent } from "./utils"

describe("MUSD Transfer", () => {
  test("Should create transfer entity", () => {
    let event = createTransferEvent(
      "0xfrom",
      "0xto",
      BigInt.fromI32(1000)
    )
    
    handleTransfer(event)
    
    assert.fieldEquals(
      "Transfer",
      event.transaction.hash.toHex(),
      "amount",
      "1000"
    )
  })
})

Run Tests

npm test

Deployment with Goldsky

Setup Goldsky

npm install -g @goldsky/cli
Create a Goldsky account at goldsky.com before authenticating.

Deploy Subgraph

# Deploy to Goldsky
goldsky subgraph deploy <subgraph-name> <version>

# Example
goldsky subgraph deploy musd-subgraph 1.0.0

Goldsky Configuration

Create a Goldsky configuration file:
goldsky.json
{
  "version": "1",
  "name": "musd-subgraph",
  "schema": "./schema.graphql",
  "dataSources": [
    {
      "name": "MUSD",
      "network": "mezo-mainnet",
      "address": "0x...",
      "startBlock": 0
    }
  ]
}

Querying Subgraphs

GraphQL Queries

Once deployed, query your subgraph using GraphQL:
# Get recent transfers
{
  transfers(first: 10, orderBy: timestamp, orderDirection: desc) {
    id
    from
    to
    amount
    timestamp
    transactionHash
  }
}

Client Integration

GraphQL Request

Integrate subgraph queries using graphql-request:
import { request, gql } from 'graphql-request'

const endpoint = 'https://api.goldsky.com/api/public/project_...'

const query = gql`
  {
    transfers(first: 10, orderBy: timestamp, orderDirection: desc) {
      id
      from
      to
      amount
      timestamp
    }
  }
`

async function getTransfers() {
  const data = await request(endpoint, query)
  return data.transfers
}

Apollo Client

Use Apollo Client for React applications:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'

const client = new ApolloClient({
  uri: 'https://api.goldsky.com/api/public/project_...',
  cache: new InMemoryCache()
})

const GET_TRANSFERS = gql`
  query GetTransfers {
    transfers(first: 10, orderBy: timestamp, orderDirection: desc) {
      id
      from
      to
      amount
      timestamp
    }
  }
`

client.query({ query: GET_TRANSFERS })
  .then(result => console.log(result))

Monitoring and Maintenance

Health Checks

Monitor subgraph health and sync status:
# Check sync status
goldsky subgraph status <subgraph-name>

Updating Subgraphs

Deploy new versions:
# Deploy updated version
goldsky subgraph deploy <subgraph-name> <new-version>

# Example
goldsky subgraph deploy musd-subgraph 1.1.0

Error Handling

Common issues and solutions:
  1. Sync Lag: Check RPC endpoint health and connectivity
  2. Failed Handlers: Review mapping logic and error logs
  3. Schema Mismatches: Ensure schema matches deployed version

Best Practices

Schema Design

Meaningful Names

Use descriptive entity and field names

Clear Relationships

Define entity relationships properly

Index Fields

Index frequently queried fields

Immutable IDs

Use immutable, unique entity IDs

Mapping Logic

  • Error Handling: Handle null values and edge cases gracefully
  • Gas Efficiency: Minimize entity loads and saves
  • Consistency: Maintain data consistency across entities
  • Testing: Write comprehensive unit tests for all handlers

Performance

  • Start Block: Set appropriate start blocks to reduce sync time
  • Batch Processing: Process events efficiently in batches
  • Caching: Use entity caching to reduce database queries
  • Pagination: Implement proper pagination in queries
For detailed subgraph schemas, deployment configurations, and protocol-specific mappings, refer to the individual subgraph repositories in the Mezo organization.

Additional Resources

Goldsky Documentation

Complete Goldsky platform documentation

The Graph Docs

Subgraph development guide

GraphQL Documentation

GraphQL query language reference

AssemblyScript

Mapping language documentation

Mezo Discord

Join the community for support

FAQ

Frequently asked questions

Build docs developers (and LLMs) love