-
Notifications
You must be signed in to change notification settings - Fork 109
/
monitor.ts
705 lines (660 loc) · 20.5 KB
/
monitor.ts
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
import {
Allocation,
AllocationStatus,
Epoch,
INDEXER_ERROR_MESSAGES,
indexerError,
IndexerErrorCode,
IndexingStatusResolver,
NetworkSubgraph,
parseGraphQLAllocation,
parseGraphQLEpochs,
parseGraphQLSubgraphDeployment,
Subgraph,
SubgraphDeployment,
SubgraphVersion,
} from '@graphprotocol/indexer-common'
import {
Address,
Eventual,
Logger,
mutable,
NetworkContracts,
SubgraphDeploymentID,
timer,
toAddress,
} from '@graphprotocol/common-ts'
import gql from 'graphql-tag'
import { providers, utils, Wallet } from 'ethers'
// The new read only Network class
export class NetworkMonitor {
constructor(
private contracts: NetworkContracts,
private indexer: Address,
private logger: Logger,
private indexingStatusResolver: IndexingStatusResolver,
private networkSubgraph: NetworkSubgraph,
private ethereum: providers.BaseProvider,
) {}
async currentEpoch(): Promise<number> {
return (await this.contracts.epochManager.currentEpoch()).toNumber()
}
async maxAllocationEpoch(): Promise<number> {
return await this.contracts.staking.maxAllocationEpochs()
}
async allocation(allocationID: string): Promise<Allocation | undefined> {
const result = await this.networkSubgraph.query(
gql`
query allocation($allocation: String!) {
allocation(id: $allocation) {
id
status
indexer {
id
}
allocatedTokens
createdAtEpoch
createdAtBlockHash
closedAtEpoch
subgraphDeployment {
id
ipfsHash
stakedTokens
signalledTokens
queryFeesAmount
}
}
}
`,
{ allocation: allocationID.toLocaleLowerCase() },
)
if (result.error) {
throw result.error
}
if (!result.data.allocation || result.data.length == 0) {
this.logger.warn(`No active allocation with id '${allocationID}' found`)
return undefined
}
return parseGraphQLAllocation(result.data.allocation)
}
async allocations(status: AllocationStatus): Promise<Allocation[]> {
try {
const result = await this.networkSubgraph.query(
gql`
query allocations($indexer: String!, $status: AllocationStatus!) {
allocations(
where: { indexer: $indexer, status: $status }
first: 1000
orderBy: createdAtBlockNumber
orderDirection: asc
) {
id
indexer {
id
}
allocatedTokens
createdAtEpoch
closedAtEpoch
createdAtBlockHash
subgraphDeployment {
id
stakedTokens
signalledTokens
queryFeesAmount
}
}
}
`,
{
indexer: this.indexer.toLocaleLowerCase(),
status: status,
},
)
if (result.error) {
throw result.error
}
if (
!result.data.allocations ||
result.data.length === 0 ||
result.data.allocations.length === 0
) {
this.logger.warn(
`No ${
AllocationStatus[status.toUpperCase() as keyof typeof AllocationStatus]
} allocations found for indexer '${this.indexer}'`,
)
return []
}
return result.data.allocations.map(parseGraphQLAllocation)
} catch (error) {
const err = indexerError(IndexerErrorCode.IE010, error)
this.logger.error(`Failed to query indexer allocations`, {
err,
})
throw err
}
}
async epochs(epochNumbers: number[]): Promise<Epoch[]> {
try {
const result = await this.networkSubgraph.query(
gql`
query epochs($epochs: [Int!]!) {
epoches(where: { id_in: $epochs }, first: 1000) {
id
startBlock
endBlock
signalledTokens
stakeDeposited
queryFeeRebates
totalRewards
totalIndexerRewards
totalDelegatorRewards
}
}
`,
{
epochs: epochNumbers,
},
)
if (result.error) {
throw result.error
}
return result.data.epoches.map(parseGraphQLEpochs)
} catch (error) {
const err = indexerError(IndexerErrorCode.IE038, error)
this.logger.error(INDEXER_ERROR_MESSAGES[IndexerErrorCode.IE038], {
err,
})
throw err
}
}
async recentlyClosedAllocations(
currentEpoch: number,
range: number,
): Promise<Allocation[]> {
try {
const result = await this.networkSubgraph.query(
gql`
query allocations($indexer: String!, $closedAtEpochThreshold: Int!) {
indexer(id: $indexer) {
allocations: totalAllocations(
where: {
indexer: $indexer
status: Closed
closedAtEpoch_gte: $closedAtEpochThreshold
}
first: 1000
) {
id
indexer {
id
}
allocatedTokens
createdAtEpoch
closedAtEpoch
createdAtBlockHash
subgraphDeployment {
id
stakedTokens
signalledTokens
queryFeesAmount
}
}
}
}
`,
{
indexer: this.indexer.toLocaleLowerCase(),
closedAtEpochThreshold: currentEpoch - range,
},
)
if (result.error) {
throw result.error
}
if (!result.data) {
throw new Error(`No data / indexer not found on chain`)
}
if (!result.data.indexer) {
throw new Error(`Indexer not found on chain`)
}
return result.data.indexer.allocations.map(parseGraphQLAllocation)
} catch (error) {
const err = indexerError(IndexerErrorCode.IE010, error)
this.logger.error(`Failed to query indexer's recently closed allocations`, {
err,
})
throw err
}
}
async closedAllocations(
subgraphDeploymentId: SubgraphDeploymentID,
): Promise<Allocation[]> {
try {
const result = await this.networkSubgraph.query(
gql`
query allocations($indexer: String!, $subgraphDeploymentId: String!) {
indexer(id: $indexer) {
allocations: totalAllocations(
where: {
indexer: $indexer
status: Closed
subgraphDeployment: $subgraphDeploymentId
}
first: 5
orderBy: closedAtBlockNumber
orderDirection: desc
) {
id
poi
indexer {
id
}
allocatedTokens
createdAtEpoch
closedAtEpoch
createdAtBlockHash
subgraphDeployment {
id
stakedTokens
signalledTokens
queryFeesAmount
}
}
}
}
`,
{
indexer: this.indexer.toLocaleLowerCase(),
subgraphDeploymentId: subgraphDeploymentId.display.bytes32,
},
)
if (result.error) {
throw result.error
}
if (!result.data) {
throw new Error(`No data / indexer not found on chain`)
}
if (!result.data.indexer) {
throw new Error(`Indexer not found on chain`)
}
return result.data.indexer.allocations.map(parseGraphQLAllocation)
} catch (error) {
const err = indexerError(IndexerErrorCode.IE010, error)
this.logger.error(
`Failed to query indexer's previously closed allocation for the deployment`,
{
err,
},
)
throw err
}
}
async subgraphs(ids: string[]): Promise<Subgraph[]> {
if (ids.length == 0) {
return []
}
let subgraphs: Subgraph[] = []
const queryProgress = {
lastId: '',
first: 20,
fetched: 0,
exhausted: false,
retriesRemaining: 10,
}
this.logger.info(`Query subgraphs in batches of ${queryProgress.first}`)
while (!queryProgress.exhausted) {
this.logger.debug(`Query subgraphs by id`, {
queryProgress: queryProgress,
subgraphIds: ids,
})
try {
const result = await this.networkSubgraph.query(
gql`
query subgraphs($first: Int!, $lastId: String!, $subgraphs: [String!]!) {
subgraphs(
where: { id_gt: $lastId, id_in: $subgraphs }
orderBy: id
orderDirection: asc
first: $first
) {
id
versionCount
versions {
version
createdAt
subgraphDeployment {
id
}
}
}
}
`,
{
first: queryProgress.first,
lastId: queryProgress.lastId,
subgraphs: ids,
},
)
if (result.error) {
throw result.error
}
// Convert return object to Subgraph interface
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const results = result.data.subgraphs.map((subgraph: any) => {
subgraph.versions = subgraph.versions.map(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(versionItem: any) => {
return {
version: versionItem.version,
createdAt: versionItem.createdAt,
deployment: new SubgraphDeploymentID(versionItem.subgraphDeployment.id),
} as SubgraphVersion
},
)
return subgraph
})
// In the case of a fresh graph network there will be no published subgraphs, handle gracefully
if (results.length == 0 && queryProgress.fetched == 0) {
this.logger.warn('No subgraph deployments found matching provided ids', {
retriesRemaining: queryProgress.retriesRemaining,
subgraphIds: ids,
})
throw new Error(`No subgraph deployments found matching provided ids: ${ids}`)
}
queryProgress.exhausted = results.length < queryProgress.first
queryProgress.fetched += results.length
queryProgress.lastId = results[results.length - 1].id
subgraphs = subgraphs.concat(results)
} catch (error) {
queryProgress.retriesRemaining--
this.logger.error(`Failed to query subgraphs by id`, {
retriesRemaining: queryProgress.retriesRemaining,
error: error,
})
if (queryProgress.retriesRemaining <= 0) {
const err = indexerError(IndexerErrorCode.IE009, error)
this.logger.error(`Failed to query subgraphs`, {
err,
})
throw err
}
}
}
this.logger.debug(`Found ${subgraphs.length} matching subgraphs`, {
subgraphs,
})
return subgraphs
}
async subgraphDeployment(ipfsHash: string): Promise<SubgraphDeployment | undefined> {
try {
const result = await this.networkSubgraph.query(
gql`
query subgraphDeployments($ipfsHash: String!) {
subgraphDeployments(where: { ipfsHash: $ipfsHash }) {
id
ipfsHash
deniedAt
stakedTokens
signalledTokens
queryFeesAmount
indexerAllocations {
indexer {
id
}
}
}
}
`,
{
ipfsHash: ipfsHash,
},
)
if (result.error) {
throw result.error
}
if (
!result.data ||
!result.data.subgraphDeployments ||
result.data.subgraphDeployments.length === 0
) {
this.logger.warn(
`SubgraphDeployment with ipfsHash = ${ipfsHash} not found on chain`,
)
return undefined
}
// TODO: Make and use parseGraphqlDeployment() function
return parseGraphQLSubgraphDeployment(result.data.subgraphDeployments[0])
} catch (error) {
const err = indexerError(IndexerErrorCode.IE010, error)
this.logger.error(
`Failed to query subgraphDeployment with ipfsHash = ${ipfsHash}`,
{
err,
},
)
throw err
}
}
async subgraphDeployments(): Promise<SubgraphDeployment[]> {
const deployments = []
const queryProgress = {
lastId: '',
first: 10,
fetched: 0,
exhausted: false,
retriesRemaining: 10,
}
this.logger.debug(`Query subgraph deployments in batches of ${queryProgress.first}`)
while (!queryProgress.exhausted) {
this.logger.trace(`Query subgraph deployments`, {
queryProgress: queryProgress,
})
try {
const result = await this.networkSubgraph.query(
gql`
query subgraphDeployments($first: Int!, $lastId: String!) {
subgraphDeployments(
where: { id_gt: $lastId }
orderBy: id
orderDirection: asc
first: $first
) {
id
ipfsHash
deniedAt
stakedTokens
signalledTokens
queryFeesAmount
indexerAllocations {
indexer {
id
}
}
}
}
`,
{ first: queryProgress.first, lastId: queryProgress.lastId },
)
if (result.error) {
throw result.error
}
const networkDeployments = result.data.subgraphDeployments
// In the case of a fresh graph network there will be no published subgraphs, handle gracefully
if (networkDeployments.length == 0 && queryProgress.fetched == 0) {
this.logger.warn('Failed to query subgraph deployments: no deployments found', {
retriesRemaining: queryProgress.retriesRemaining,
})
throw new Error('No subgraph deployments returned')
}
queryProgress.exhausted = networkDeployments.length < queryProgress.first
queryProgress.fetched += networkDeployments.length
queryProgress.lastId = networkDeployments[networkDeployments.length - 1].id
deployments.push(...networkDeployments.map(parseGraphQLSubgraphDeployment))
} catch (err) {
queryProgress.retriesRemaining--
this.logger.warn(`Failed to query subgraph deployments`, {
retriesRemaining: queryProgress.retriesRemaining,
error: err,
})
if (queryProgress.retriesRemaining <= 0) {
const error = indexerError(IndexerErrorCode.IE009, err.message)
this.logger.error(`Failed to query subgraph deployments worth indexing`, {
error,
})
throw error
}
}
}
this.logger.debug(`Finished fetching subgraph deployments published to network`, {
publishedSubgraphs: queryProgress.fetched,
})
return deployments
}
async resolvePOI(
allocation: Allocation,
poi: string | undefined,
force: boolean,
): Promise<string> {
// poi = undefined, force=true -- submit even if poi is 0x0
// poi = defined, force=true -- no generatedPOI needed, just submit the POI supplied (with some sanitation?)
// poi = undefined, force=false -- submit with generated POI if one available
// poi = defined, force=false -- submit user defined POI only if generated POI matches
switch (force) {
case true:
switch (!!poi) {
case true:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return poi!
case false:
return (
(await this.indexingStatusResolver.proofOfIndexing(
allocation.subgraphDeployment.id,
await this.ethereum.getBlock(
(await this.contracts.epochManager.currentEpochBlock()).toNumber(),
),
allocation.indexer,
)) || utils.hexlify(Array(32).fill(0))
)
}
break
case false: {
// Obtain the start block of the current epoch
const epochStartBlockNumber =
await this.contracts.epochManager.currentEpochBlock()
const epochStartBlock = await this.ethereum.getBlock(
epochStartBlockNumber.toNumber(),
)
const generatedPOI = await this.indexingStatusResolver.proofOfIndexing(
allocation.subgraphDeployment.id,
epochStartBlock,
allocation.indexer,
)
switch (poi == generatedPOI) {
case true:
if (poi == undefined) {
const deploymentStatus = await this.indexingStatusResolver.indexingStatus([
allocation.subgraphDeployment.id,
])
throw indexerError(
IndexerErrorCode.IE067,
`POI not available for deployment at current epoch start block.
currentEpochStartBlock: ${epochStartBlockNumber}
deploymentStatus: ${
deploymentStatus.length > 0
? JSON.stringify(deploymentStatus)
: 'not deployed'
}`,
)
} else {
return poi
}
case false:
if (poi == undefined && generatedPOI !== undefined) {
return generatedPOI
} else if (poi !== undefined && generatedPOI == undefined) {
return poi
}
throw indexerError(
IndexerErrorCode.IE068,
`User provided POI does not match reference fetched from the graph-node. Use '--force' to bypass this POI accuracy check.
POI: ${poi},
referencePOI: ${generatedPOI}`,
)
}
}
}
}
async monitorNetworkPauses(
logger: Logger,
contracts: NetworkContracts,
networkSubgraph: NetworkSubgraph,
): Promise<Eventual<boolean>> {
return timer(60_000)
.reduce(async (currentlyPaused) => {
try {
const result = await networkSubgraph.query(
gql`
{
graphNetworks {
isPaused
}
}
`,
)
if (result.error) {
throw result.error
}
if (!result.data || result.data.length === 0) {
throw indexerError(
IndexerErrorCode.IE007,
`No data returned by network subgraph`,
)
}
return result.data.graphNetworks[0].isPaused
} catch (err) {
logger.warn(`Failed to check for network pause, assuming it has not changed`, {
err: indexerError(IndexerErrorCode.IE007, err),
paused: currentlyPaused,
})
return currentlyPaused
}
}, await contracts.controller.paused())
.map((paused) => {
logger.info(paused ? `Network paused` : `Network active`)
return paused
})
}
async monitorIsOperator(
logger: Logger,
contracts: NetworkContracts,
indexerAddress: Address,
wallet: Wallet,
): Promise<Eventual<boolean>> {
// If indexer and operator address are identical, operator status is
// implicitly granted => we'll never have to check again
if (indexerAddress === toAddress(wallet.address)) {
logger.info(`Indexer and operator are identical, operator status granted`)
return mutable(true)
}
return timer(60_000)
.reduce(async (isOperator) => {
try {
return await contracts.staking.isOperator(wallet.address, indexerAddress)
} catch (err) {
logger.warn(
`Failed to check operator status for indexer, assuming it has not changed`,
{ err: indexerError(IndexerErrorCode.IE008, err), isOperator },
)
return isOperator
}
}, await contracts.staking.isOperator(wallet.address, indexerAddress))
.map((isOperator) => {
logger.info(
isOperator
? `Have operator status for indexer`
: `No operator status for indexer`,
)
return isOperator
})
}
}