Subgraph Deployment with Goldsky
This guide covers how to deploy and manage subgraphs for Mezo protocols using Goldsky’s infrastructure. Subgraphs enable efficient querying of blockchain data through GraphQL APIs.
Overview
Subgraphs provide:
- Indexed Data: Fast access to blockchain data
- GraphQL API: Flexible querying interface
- Real-time Updates: Live data synchronization
- Custom Logic: Transform and aggregate on-chain data
Repository Structure
Mezo subgraph repositories typically contain:
- schema.graphql: GraphQL schema definitions
- subgraph.yaml: Subgraph manifest
- src/: Mapping logic (AssemblyScript)
- abis/: Contract ABIs
- tests/: Unit tests
Development Setup
Prerequisites
- Node.js 18+ (check repository’s
.nvmrcfor exact version) - npm or yarn package manager
- Git
- Graph CLI
- Goldsky account
Installation
- Clone the subgraph repository:
git clone https://github.com/mezo-org/subgraphs.gitcd subgraphs- Install dependencies:
npm install# oryarn install- Install Graph CLI:
npm install -g @graphprotocol/graph-cliSubgraph Development
Schema Definition
Define your data models in 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!}Subgraph Manifest
Configure your subgraph in subgraph.yaml:
specVersion: 0.0.5schema: file: ./schema.graphqldataSources: - 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.tsMapping Logic
Implement event handlers in 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:
# Generate typesgraph codegen
# Build subgraphgraph buildTesting
Unit Tests
Write unit tests for your mappings:
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:
# Run all testsnpm test
# Run specific testgraph testDeployment with Goldsky
Prerequisites
- Create Goldsky Account: Sign up at goldsky.com
- Install Goldsky CLI:
npm install -g @goldsky/cli- Authenticate:
goldsky loginDeployment Process
- Deploy Subgraph:
# Deploy to Goldskygoldsky subgraph deploy <subgraph-name> <version>
# Examplegoldsky subgraph deploy musd-subgraph 1.0.0- Monitor Deployment:
# Check deployment statusgoldsky subgraph status <subgraph-name>
# View logsgoldsky subgraph logs <subgraph-name>Configuration
Create a Goldsky configuration file:
{ "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:
# Get recent transfers{ transfers(first: 10, orderBy: timestamp, orderDirection: desc) { id from to amount timestamp transactionHash }}
# Get token information{ token(id: "1") { name symbol decimals totalSupply }}
# Filter transfers by address{ transfers(where: { from: "0x..." }) { id to amount timestamp }}Client Integration
Integrate subgraph queries in your dApp:
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 Integration
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:
# Check sync statusgoldsky subgraph status <subgraph-name>
# View sync laggoldsky subgraph info <subgraph-name>Updating Subgraphs
Deploy new versions:
# Deploy updated versiongoldsky subgraph deploy <subgraph-name> <new-version>
# Examplegoldsky subgraph deploy musd-subgraph 1.1.0Error Handling
Common issues and solutions:
- Sync Lag: Check RPC endpoint health
- Failed Handlers: Review mapping logic and logs
- Schema Mismatches: Ensure schema matches deployment
Best Practices
Schema Design
- Entities: Use meaningful entity names
- Relationships: Define clear entity relationships
- Indexing: Index frequently queried fields
- Immutability: Use immutable IDs for entities
Mapping Logic
- Error Handling: Handle null values gracefully
- Gas Efficiency: Minimize entity loads and saves
- Consistency: Maintain data consistency
- Testing: Write comprehensive unit tests
Performance
- Start Block: Set appropriate start blocks
- Batch Processing: Process events in batches
- Caching: Use entity caching effectively
- Pagination: Implement proper pagination in queries
Additional Resources
- Goldsky Documentation - Goldsky platform docs
- The Graph Documentation - Subgraph development guide
- GraphQL Documentation - GraphQL query language
- AssemblyScript Documentation - Mapping language
Support
For subgraph development support:
- Join the Mezo Discord
- Check subgraph repository issues on GitHub
- Review the FAQ
- Contact Goldsky Support