|
| 1 | +/* eslint-disable no-console, no-await-in-loop */ |
| 2 | +import { gql, request } from 'graphql-request'; |
| 3 | + |
| 4 | +import { SUPPORTED_NETWORK_INFO } from './client'; |
| 5 | + |
| 6 | +const GRAPH_HEALTH_ENDPOINT = 'https://api.thegraph.com/index-node/graphql'; |
| 7 | + |
| 8 | +const statusQuery = gql` |
| 9 | + query getSubgraphStatus($subgraph: String!) { |
| 10 | + status: indexingStatusForCurrentVersion(subgraphName: $subgraph) { |
| 11 | + chains { |
| 12 | + latestBlock { |
| 13 | + number |
| 14 | + } |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | +`; |
| 19 | + |
| 20 | +const getLatestBlock = async (subgraph: string): Promise<number> => { |
| 21 | + const data = await request(GRAPH_HEALTH_ENDPOINT, statusQuery, { |
| 22 | + subgraph, |
| 23 | + }); |
| 24 | + return data.status.chains[0].latestBlock.number; |
| 25 | +}; |
| 26 | + |
| 27 | +const UPDATE_INTERVAL = 10000; |
| 28 | + |
| 29 | +class SubgraphHealthStore { |
| 30 | + graphHealth: Record<string, number> = {}; |
| 31 | + |
| 32 | + constructor() { |
| 33 | + // console.debug('@quest-chains/sdk: health store init'); |
| 34 | + this.updateSubgraphHealth(); |
| 35 | + } |
| 36 | + |
| 37 | + public async updateSubgraphHealth() { |
| 38 | + await Promise.all( |
| 39 | + Object.values(SUPPORTED_NETWORK_INFO).map(async info => { |
| 40 | + this.graphHealth[info.chainId] = await getLatestBlock(info.subgraphName); |
| 41 | + }), |
| 42 | + ); |
| 43 | + // console.debug('@quest-chains/sdk: updated graph health:', this.graphHealth); |
| 44 | + setTimeout(() => this.updateSubgraphHealth(), UPDATE_INTERVAL); |
| 45 | + } |
| 46 | + |
| 47 | + status() { |
| 48 | + return this.graphHealth; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +const HealthStoreSingleton = (function () { |
| 53 | + let instance: SubgraphHealthStore; |
| 54 | + |
| 55 | + function createInstance() { |
| 56 | + return new SubgraphHealthStore(); |
| 57 | + } |
| 58 | + |
| 59 | + return { |
| 60 | + getInstance: function () { |
| 61 | + if (!instance) { |
| 62 | + instance = createInstance(); |
| 63 | + } |
| 64 | + return instance; |
| 65 | + }, |
| 66 | + }; |
| 67 | +})(); |
| 68 | + |
| 69 | +const getSubgraphStatus = () => HealthStoreSingleton.getInstance().status(); |
| 70 | + |
| 71 | +const initSubgraphHealthStore = getSubgraphStatus; |
| 72 | + |
| 73 | +initSubgraphHealthStore(); |
| 74 | + |
| 75 | +export const getSubgraphLatestBlock = (chainId: string): number => getSubgraphStatus()[chainId]; |
0 commit comments