# All files / indexer-management client.ts

96.67% Statements 29/30
50% Branches 3/6
100% Functions 4/4
96.67% Lines 29/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    3181x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x

    1x

    1x

    1x

    16x

    16x
    16x
    16x

    2x

    2x

    2x

    2x
    2x

    1x

    16x

    16x
    16x
    16x

    16x

    16x

    16x

     import { buildSchema, print } from 'graphql'
    import gql from 'graphql-tag'
    import { executeExchange } from '@urql/exchange-execute'
    import { Client, ClientOptions } from '@urql/core'
    import {
      equal,
      Eventual,
      Logger,
      mutable,
      NetworkContracts,
      WritableEventual,
    } from '@graphprotocol/common-ts'
    import { NetworkSubgraph } from '../network-subgraph'

    import { IndexerManagementModels, IndexingRuleCreationAttributes } from './models'

    import indexingRuleResolvers from './resolvers/indexing-rules'
    import statusResolvers from './resolvers/indexer-status'
    import costModelResolvers from './resolvers/cost-models'
    import poiDisputeResolvers from './resolvers/poi-disputes'
    import { BigNumber } from 'ethers'
    import { Op, Sequelize } from 'sequelize'
    import { IndexingStatusResolver } from '../indexing-status'

    export interface IndexerManagementFeatures {
      injectDai: boolean
    }

    export interface IndexerManagementResolverContext {
      models: IndexerManagementModels
      address: string
      contracts: NetworkContracts
      indexingStatusResolver: IndexingStatusResolver
      networkSubgraph: NetworkSubgraph
      logger?: Logger
      defaults: IndexerManagementDefaults
      features: IndexerManagementFeatures
      dai: Eventual<string>
    }

    const SCHEMA_SDL = gql`
      scalar BigInt

      enum IndexingDecisionBasis {
        rules
        never
        always
      }

      type POIDispute {
        allocationID: String!
        subgraphDeploymentID: String!
        allocationIndexer: String!
        allocationAmount: BigInt!
        allocationProof: String!
        closedEpoch: Int!
        closedEpochStartBlockHash: String!
        closedEpochStartBlockNumber: Int!
        closedEpochReferenceProof: String!
        previousEpochStartBlockHash: String!
        previousEpochStartBlockNumber: Int!
        previousEpochReferenceProof: String!
        status: String!
      }

      input POIDisputeInput {
        allocationID: String!
        subgraphDeploymentID: String!
        allocationIndexer: String!
        allocationAmount: BigInt!
        allocationProof: String!
        closedEpoch: Int!
        closedEpochStartBlockHash: String!
        closedEpochStartBlockNumber: Int!
        closedEpochReferenceProof: String!
        previousEpochStartBlockHash: String!
        previousEpochStartBlockNumber: Int!
        previousEpochReferenceProof: String!
        status: String!
      }

      type IndexingRule {
        deployment: String!
        allocationAmount: BigInt
        parallelAllocations: Int
        maxAllocationPercentage: Float
        minSignal: BigInt
        maxSignal: BigInt
        minStake: BigInt
        minAverageQueryFees: BigInt
        custom: String
        decisionBasis: IndexingDecisionBasis!
      }

      input IndexingRuleInput {
        deployment: String!
        allocationAmount: BigInt
        parallelAllocations: Int
        maxAllocationPercentage: Float
        minSignal: BigInt
        maxSignal: BigInt
        minStake: BigInt
        minAverageQueryFees: BigInt
        custom: String
        decisionBasis: IndexingDecisionBasis
      }

      type GeoLocation {
        latitude: String!
        longitude: String!
      }

      type IndexerRegistration {
        url: String
        address: String
        registered: Boolean!
        location: GeoLocation
      }

      type IndexingError {
        handler: String
        message: String!
      }

      type BlockPointer {
        number: Int!
        hash: String!
      }

      type ChainIndexingStatus {
        network: String!
        latestBlock: BlockPointer!
        chainHeadBlock: BlockPointer!
        earliestBlock: BlockPointer!
      }

      type IndexerDeployment {
        subgraphDeployment: String!
        synced: Boolean!
        health: String!
        fatalError: IndexingError
        node: String!
        chains: [ChainIndexingStatus]
      }

      type IndexerAllocation {
        id: String!
        allocatedTokens: BigInt!
        createdAtEpoch: Int!
        closedAtEpoch: Int
        subgraphDeployment: String!
        signalAmount: BigInt!
        stakedTokens: BigInt!
      }

      type IndexerEndpointTest {
        test: String!
        error: String
        possibleActions: [String]!
      }

      type IndexerEndpoint {
        url: String
        healthy: Boolean!
        tests: [IndexerEndpointTest!]!
      }

      type IndexerEndpoints {
        service: IndexerEndpoint!
        status: IndexerEndpoint!
      }

      type CostModel {
        deployment: String!
        model: String
        variables: String
      }

      input CostModelInput {
        deployment: String!
        model: String
        variables: String
      }

      type Query {
        indexingRule(deployment: String!, merged: Boolean! = false): IndexingRule
        indexingRules(merged: Boolean! = false): [IndexingRule!]!
        indexerRegistration: IndexerRegistration!
        indexerDeployments: [IndexerDeployment]!
        indexerAllocations: [IndexerAllocation]!
        indexerEndpoints: IndexerEndpoints!

        costModels(deployments: [String!]): [CostModel!]!
        costModel(deployment: String!): CostModel

        dispute(allocationID: String!): POIDispute
        disputes(status: String!, minClosedEpoch: Int!): [POIDispute]!
        disputesClosedAfter(closedAfterBlock: BigInt!): [POIDispute]!
      }

      type Mutation {
        setIndexingRule(rule: IndexingRuleInput!): IndexingRule!
        deleteIndexingRule(deployment: String!): Boolean!
        deleteIndexingRules(deployments: [String!]!): Boolean!

        setCostModel(costModel: CostModelInput!): CostModel!

        storeDisputes(disputes: [POIDisputeInput!]!): [POIDispute!]
        deleteDisputes(allocationIDs: [String!]!): Int!
      }
    `

    export interface IndexerManagementDefaults {
      globalIndexingRule: Omit<
        IndexingRuleCreationAttributes,
        'deployment' | 'allocationAmount'
      > & { allocationAmount: BigNumber }
    }

    export interface IndexerManagementClientOptions {
      models: IndexerManagementModels
      address: string
      contracts: NetworkContracts
      indexingStatusResolver: IndexingStatusResolver
      networkSubgraph: NetworkSubgraph
      logger?: Logger
      defaults: IndexerManagementDefaults
      features: IndexerManagementFeatures
    }

    export class IndexerManagementClient extends Client {
      private logger?: Logger
      private models: IndexerManagementModels
      private dai: WritableEventual<string>

      constructor(
        clientOptions: ClientOptions,
        options: IndexerManagementClientOptions,
        featureOptions: { dai: WritableEventual<string> },
      ) {
        super(clientOptions)

        this.logger = options.logger
        this.models = options.models
        this.dai = featureOptions.dai
      }

      public async setDai(value: string): Promise<void> {
        // Get current value
        const oldValue = this.dai.valueReady ? await this.dai.value() : undefined

        // Don't do anything if there is no change
        Iif (equal(oldValue, value)) {
          return
        }

        // Notify others of the new value
        this.dai.push(value)

        // Update DAI in all cost models
        const update = `'${JSON.stringify({ DAI: value })}'::jsonb`
        await this.models.CostModel.update(
          {
            // This merges DAI into the variables, overwriting existing values
            variables: Sequelize.literal(`coalesce(variables, '{}'::jsonb) || ${update}`),
          },
          {
            // This is just a non-obvious way to match all models
            where: { deployment: { [Op.not]: null } },
          },
        )
      }
    }

    export const createIndexerManagementClient = async (
      options: IndexerManagementClientOptions,
    ): Promise<IndexerManagementClient> => {
      const {
        models,
        address,
        contracts,
        indexingStatusResolver,
        networkSubgraph,
        logger,
        defaults,
        features,
      } = options
      const schema = buildSchema(print(SCHEMA_SDL))
      const resolvers = {
        ...indexingRuleResolvers,
        ...statusResolvers,
        ...costModelResolvers,
        ...poiDisputeResolvers,
      }

      const dai: WritableEventual<string> = mutable()

      const exchange = executeExchange({
        schema,
        rootValue: resolvers,
        context: {
          models,
          address,
          contracts,
          indexingStatusResolver,
          networkSubgraph,
          logger: logger ? logger.child({ component: 'IndexerManagementClient' }) : undefined,
          defaults,
          features,
          dai,
        },
      })

      return new IndexerManagementClient({ url: 'no-op', exchanges: [exchange] }, options, {
        dai,
      })
    }