-
Notifications
You must be signed in to change notification settings - Fork 127
/
allocations.ts
1143 lines (1029 loc) · 35.6 KB
/
allocations.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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
formatGRT,
Logger,
NetworkContracts,
parseGRT,
SubgraphDeploymentID,
toAddress,
} from '@graphprotocol/common-ts'
import {
Action,
ActionType,
allocationIdProof,
AllocationResult,
AllocationStatus,
CloseAllocationResult,
CreateAllocationResult,
fetchIndexingRules,
IndexerError,
indexerError,
IndexerErrorCode,
IndexerManagementModels,
IndexingDecisionBasis,
IndexingRuleAttributes,
isActionFailure,
isDeploymentWorthAllocatingTowards,
ReallocateAllocationResult,
ReceiptCollector,
SubgraphIdentifierType,
TransactionManager,
uniqueAllocationID,
upsertIndexingRule,
} from '@graphprotocol/indexer-common'
import {
BigNumber,
BigNumberish,
ContractReceipt,
PopulatedTransaction,
providers,
utils,
} from 'ethers'
import { NetworkMonitor } from './monitor'
import { SubgraphManager } from './subgraphs'
import { BytesLike } from '@ethersproject/bytes'
import pMap from 'p-map'
import { ActionFailure } from '../allocations/types'
export interface AllocateTransactionParams {
indexer: string
subgraphDeploymentID: BytesLike
tokens: BigNumberish
allocationID: string
metadata: BytesLike
proof: BytesLike
}
export interface UnallocateTransactionParams {
allocationID: string
poi: BytesLike
}
export interface ReallocateTransactionParams {
closingAllocationID: string
poi: BytesLike
indexer: string
subgraphDeploymentID: BytesLike
tokens: BigNumberish
newAllocationID: string
metadata: BytesLike
proof: BytesLike
}
export type PopulateTransactionResult = PopulatedTransaction | ActionFailure
export type TransactionResult =
| ContractReceipt
| 'paused'
| 'unauthorized'
| ActionFailure[]
export class AllocationManager {
constructor(
private contracts: NetworkContracts,
private logger: Logger,
private indexer: string,
private models: IndexerManagementModels,
private networkMonitor: NetworkMonitor,
private receiptCollector: ReceiptCollector,
private subgraphManager: SubgraphManager,
private transactionManager: TransactionManager,
) {}
async executeBatch(actions: Action[]): Promise<AllocationResult[]> {
const result = await this.executeTransactions(actions)
if (Array.isArray(result)) {
return result as ActionFailure[]
}
return await this.confirmTransactions(result, actions)
}
async executeTransactions(actions: Action[]): Promise<TransactionResult> {
if (actions.length < 1) {
throw Error('Failed to populate batch transaction: no transactions supplied')
}
const populateTransactionsResults = await this.prepareTransactions(actions)
const failedTransactionPreparations = populateTransactionsResults
.filter((result) => isActionFailure(result))
.map((result) => result as ActionFailure)
if (failedTransactionPreparations.length > 0) {
return failedTransactionPreparations
}
const callData = populateTransactionsResults
.map((tx) => tx as PopulatedTransaction)
.filter((tx: PopulatedTransaction) => !!tx.data)
.map((tx) => tx.data as string)
return await this.transactionManager.executeTransaction(
async () => this.contracts.staking.estimateGas.multicall(callData),
async (gasLimit) => this.contracts.staking.multicall(callData, { gasLimit }),
this.logger.child({
actions: `${JSON.stringify(actions.map((action) => action.id))}`,
function: 'staking.multicall',
}),
)
}
async confirmTransactions(
receipt: ContractReceipt | 'paused' | 'unauthorized',
actions: Action[],
): Promise<AllocationResult[]> {
const results = pMap(
actions,
async (action) => {
try {
return await this.confirmActionExecution(receipt, action)
} catch (error) {
return {
actionID: action.id,
transactionID: undefined,
failureReason:
error instanceof IndexerError
? error.code
: 'Failed to confirm transactions',
}
}
},
{ stopOnError: false },
)
return results
}
findEvent(
eventType: string,
contractInterface: utils.Interface,
logKey: string,
logValue: string,
receipt: ContractReceipt,
): utils.Result | undefined {
const events: Event[] | providers.Log[] = receipt.events || receipt.logs
return events
.filter((event) =>
event.topics.includes(contractInterface.getEventTopic(eventType)),
)
.map((event) =>
contractInterface.decodeEventLog(eventType, event.data, event.topics),
)
.find(
(eventLogs: utils.Result) =>
eventLogs[logKey].toLocaleLowerCase() === logValue.toLocaleLowerCase(),
)
}
async confirmActionExecution(
receipt: ContractReceipt | 'paused' | 'unauthorized',
action: Action,
): Promise<AllocationResult> {
switch (action.type) {
case ActionType.ALLOCATE:
return await this.confirmAllocate(
action.id,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
action.deploymentID!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
action.amount!,
receipt,
)
case ActionType.UNALLOCATE:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return await this.confirmUnallocate(action.id, action.allocationID!, receipt)
case ActionType.REALLOCATE:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return await this.confirmReallocate(action.id, action.allocationID!, receipt)
}
}
async prepareTransactions(actions: Action[]): Promise<PopulateTransactionResult[]> {
return await pMap(actions, async (action) => await this.prepareTransaction(action), {
stopOnError: false,
})
}
async prepareTransaction(action: Action): Promise<PopulateTransactionResult> {
const logger = this.logger.child({ action: action.id })
logger.trace('Preparing transaction', {
action,
})
try {
switch (action.type) {
case ActionType.ALLOCATE:
return await this.prepareAllocate(
logger,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
new SubgraphDeploymentID(action.deploymentID!),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
parseGRT(action.amount!),
undefined,
)
case ActionType.UNALLOCATE:
return await this.prepareUnallocate(
logger,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
action.allocationID!,
action.poi === null ? undefined : action.poi,
action.force === null ? false : action.force,
)
case ActionType.REALLOCATE:
return await this.prepareReallocate(
logger,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
action.allocationID!,
action.poi === null ? undefined : action.poi,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
parseGRT(action.amount!),
action.force === null ? false : action.force,
)
}
} catch (error) {
logger.error(`Failed to prepare tx call data: ${error}`)
return {
actionID: action.id,
failureReason:
error instanceof IndexerError ? error.code : `Failed to prepare tx call data`,
}
}
}
async prepareAllocateParams(
logger: Logger,
deployment: SubgraphDeploymentID,
amount: BigNumber,
indexNode: string | undefined,
): Promise<AllocateTransactionParams> {
logger.info('Preparing to allocate', {
deployment: deployment.ipfsHash,
amount: amount.toString(),
})
const activeAllocations = await this.networkMonitor.allocations(
AllocationStatus.ACTIVE,
)
const allocation = activeAllocations.find(
(allocation) =>
allocation.subgraphDeployment.id.toString() === deployment.toString(),
)
if (allocation) {
logger.warn('Already allocated to deployment', {
deployment: allocation.subgraphDeployment.id.ipfsHash,
activeAllocation: allocation.id,
})
throw indexerError(
IndexerErrorCode.IE060,
`Allocation failed. An active allocation already exists for deployment '${allocation.subgraphDeployment.id.ipfsHash}'`,
)
}
if (amount.lt('0')) {
logger.warn('Cannot allocate a negative amount of GRT', {
amount: amount.toString(),
})
throw indexerError(
IndexerErrorCode.IE061,
`Invalid allocation amount provided (${amount.toString()}). Must use positive allocation amount`,
)
}
const currentEpoch = await this.contracts.epochManager.currentEpoch()
// Identify how many GRT the indexer has staked
const freeStake = await this.contracts.staking.getIndexerCapacity(this.indexer)
// If there isn't enough left for allocating, abort
if (freeStake.lt(amount)) {
logger.error(
`Allocation of ${formatGRT(
amount,
)} GRT cancelled: indexer only has a free stake amount of ${formatGRT(
freeStake,
)} GRT`,
)
throw indexerError(
IndexerErrorCode.IE013,
`Allocation of ${formatGRT(
amount,
)} GRT cancelled: indexer only has a free stake amount of ${formatGRT(
freeStake,
)} GRT`,
)
}
// Ensure subgraph is deployed before allocating
await this.subgraphManager.ensure(
logger,
this.models,
`${deployment.ipfsHash.slice(0, 23)}/${deployment.ipfsHash.slice(23)}`,
deployment,
indexNode,
)
logger.debug('Obtain a unique Allocation ID')
// Obtain a unique allocation ID
const { allocationSigner, allocationId } = uniqueAllocationID(
this.transactionManager.wallet.mnemonic.phrase,
currentEpoch.toNumber(),
deployment,
activeAllocations.map((allocation) => allocation.id),
)
// Double-check whether the allocationID already exists on chain, to
// avoid unnecessary transactions.
// Note: We're checking the allocation state here, which is defined as
//
// enum AllocationState { Null, Active, Closed, Finalized, Claimed }
//
// in the contracts.
const state = await this.contracts.staking.getAllocationState(allocationId)
if (state !== 0) {
logger.debug(`Skipping allocation as it already exists onchain`, {
indexer: this.indexer,
allocation: allocationId,
state,
})
throw indexerError(
IndexerErrorCode.IE066,
`Allocation '${allocationId}' already exists onchain`,
)
}
logger.debug('Generating new allocation ID proof', {
newAllocationSigner: allocationSigner,
newAllocationID: allocationId,
indexerAddress: this.indexer,
})
const proof = await allocationIdProof(allocationSigner, this.indexer, allocationId)
logger.debug('Successfully generated allocation ID proof', {
allocationIDProof: proof,
})
return {
indexer: this.indexer,
subgraphDeploymentID: deployment.bytes32,
tokens: amount,
allocationID: allocationId,
metadata: utils.hexlify(Array(32).fill(0)),
proof,
}
}
async confirmAllocate(
actionID: number,
deployment: string,
amount: string,
receipt: ContractReceipt | 'paused' | 'unauthorized',
): Promise<CreateAllocationResult> {
const logger = this.logger.child({ action: actionID })
const subgraphDeployment = new SubgraphDeploymentID(deployment)
logger.info(`Confirming 'allocateFrom' transaction`)
if (receipt === 'paused' || receipt === 'unauthorized') {
throw indexerError(
IndexerErrorCode.IE062,
`Allocation not created. ${
receipt === 'paused' ? 'Network paused' : 'Operator not authorized'
}`,
)
}
const createAllocationEventLogs = this.findEvent(
'AllocationCreated',
this.contracts.staking.interface,
'subgraphDeploymentID',
subgraphDeployment.bytes32,
receipt,
)
if (!createAllocationEventLogs) {
throw indexerError(IndexerErrorCode.IE014, `Allocation was never mined`)
}
logger.info(`Successfully allocated to subgraph deployment`, {
amountGRT: formatGRT(createAllocationEventLogs.tokens),
allocation: createAllocationEventLogs.allocationID,
deployment: createAllocationEventLogs.subgraphDeploymentID,
epoch: createAllocationEventLogs.epoch.toString(),
})
// Remember allocation
await this.receiptCollector.rememberAllocations(actionID, [
createAllocationEventLogs.allocationID,
])
const subgraphDeploymentID = new SubgraphDeploymentID(deployment)
// If there is not yet an indexingRule that deems this deployment worth allocating to, make one
if (!(await this.matchingRuleExists(logger, subgraphDeploymentID))) {
logger.debug(
`No matching indexing rule found; updating indexing rules so indexer-agent will now manage the active allocation`,
)
const indexingRule = {
identifier: deployment,
allocationAmount: amount,
identifierType: SubgraphIdentifierType.DEPLOYMENT,
decisionBasis: IndexingDecisionBasis.ALWAYS,
} as Partial<IndexingRuleAttributes>
await upsertIndexingRule(logger, this.models, indexingRule)
}
return {
actionID,
type: 'allocate',
transactionID: receipt.transactionHash,
deployment: deployment,
allocation: createAllocationEventLogs.allocationID,
allocatedTokens: amount,
}
}
async prepareAllocate(
logger: Logger,
deployment: SubgraphDeploymentID,
amount: BigNumber,
indexNode: string | undefined,
): Promise<PopulatedTransaction> {
const params = await this.prepareAllocateParams(logger, deployment, amount, indexNode)
logger.debug(`Populating allocateFrom transaction`, {
indexer: params.indexer,
subgraphDeployment: params.subgraphDeploymentID,
amount: formatGRT(params.tokens),
allocation: params.allocationID,
proof: params.proof,
})
return await this.contracts.staking.populateTransaction.allocateFrom(
params.indexer,
params.subgraphDeploymentID,
params.tokens,
params.allocationID,
params.metadata,
params.proof,
)
}
async allocate(
deployment: SubgraphDeploymentID,
amount: BigNumber,
indexNode: string | undefined,
): Promise<CreateAllocationResult> {
try {
const params = await this.prepareAllocateParams(
this.logger,
deployment,
amount,
indexNode,
)
this.logger.debug(`Sending allocateFrom transaction`, {
indexer: params.indexer,
subgraphDeployment: deployment.ipfsHash,
amount: formatGRT(params.tokens),
allocation: params.allocationID,
proof: params.proof,
})
const receipt = await this.transactionManager.executeTransaction(
async () =>
this.contracts.staking.estimateGas.allocateFrom(
params.indexer,
params.subgraphDeploymentID,
params.tokens,
params.allocationID,
params.metadata,
params.proof,
),
async (gasLimit) =>
this.contracts.staking.allocateFrom(
params.indexer,
params.subgraphDeploymentID,
params.tokens,
params.allocationID,
params.metadata,
params.proof,
{ gasLimit },
),
this.logger.child({ function: 'staking.allocate' }),
)
return await this.confirmAllocate(
0,
deployment.ipfsHash,
amount.toString(),
receipt,
)
} catch (error) {
this.logger.error(`Failed to allocate`, {
amount: formatGRT(amount),
error,
})
throw error
}
}
async prepareUnallocateParams(
logger: Logger,
allocationID: string,
poi: string | undefined,
force: boolean,
): Promise<UnallocateTransactionParams> {
logger.info('Preparing to close allocation (unallocate)', {
allocationID: allocationID,
poi: poi || 'none provided',
})
const allocation = await this.networkMonitor.allocation(allocationID)
if (!allocation) {
logger.warn('Allocation does not exist', {
allocationID,
})
throw indexerError(
IndexerErrorCode.IE063,
`Unallocate failed: No active allocation with id '${allocationID}' found`,
)
}
// Ensure allocation is old enough to close
const currentEpoch = await this.contracts.epochManager.currentEpoch()
if (BigNumber.from(allocation.createdAtEpoch).eq(currentEpoch)) {
throw indexerError(
IndexerErrorCode.IE064,
`Allocation '${allocation.id}' cannot be closed until epoch ${currentEpoch.add(
1,
)}. (Allocations cannot be closed in the same epoch they were created)`,
)
}
poi = await this.networkMonitor.resolvePOI(allocation, poi, force)
// Double-check whether the allocation is still active on chain, to
// avoid unnecessary transactions.
// Note: We're checking the allocation state here, which is defined as
//
// enum AllocationState { Null, Active, Closed, Finalized, Claimed }
//
// in the contracts.
const state = await this.contracts.staking.getAllocationState(allocation.id)
if (state !== 1) {
throw indexerError(IndexerErrorCode.IE065)
}
return {
allocationID: allocation.id,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
poi: poi!,
}
}
async confirmUnallocate(
actionID: number,
allocationID: string,
receipt: ContractReceipt | 'paused' | 'unauthorized',
): Promise<CloseAllocationResult> {
const logger = this.logger.child({ action: actionID })
logger.info(`Confirming 'closeAllocation' transaction`)
if (receipt === 'paused' || receipt === 'unauthorized') {
throw indexerError(
IndexerErrorCode.IE062,
`Allocation '${allocationID}' could not be closed: ${receipt}`,
)
}
const closeAllocationEventLogs = this.findEvent(
'AllocationClosed',
this.contracts.staking.interface,
'allocationID',
allocationID,
receipt,
)
if (!closeAllocationEventLogs) {
throw indexerError(
IndexerErrorCode.IE015,
`Allocation close transaction was never successfully mined`,
)
}
const rewardsEventLogs = this.findEvent(
'RewardsAssigned',
this.contracts.rewardsManager.interface,
'allocationID',
allocationID,
receipt,
)
const rewardsAssigned = rewardsEventLogs ? rewardsEventLogs.amount : 0
if (rewardsAssigned == 0) {
logger.warn('No rewards were distributed upon closing the allocation')
}
const subgraphDeploymentID = new SubgraphDeploymentID(
closeAllocationEventLogs.subgraphDeploymentID,
)
logger.info(`Successfully closed allocation`, {
deployment: subgraphDeploymentID.display,
allocation: closeAllocationEventLogs.allocationID,
indexer: closeAllocationEventLogs.indexer,
amountGRT: formatGRT(closeAllocationEventLogs.tokens),
effectiveAllocation: closeAllocationEventLogs.effectiveAllocation.toString(),
poi: closeAllocationEventLogs.poi,
epoch: closeAllocationEventLogs.epoch.toString(),
transaction: receipt.transactionHash,
indexingRewards: rewardsAssigned,
})
logger.info('Identifying receipts worth collecting', {
allocation: closeAllocationEventLogs.allocationID,
})
const allocation = await this.networkMonitor.allocation(allocationID)
if (!allocation) {
throw indexerError(
IndexerErrorCode.IE063,
`Unallocate failed: No active allocation with id '${allocationID}' found`,
)
}
// Collect query fees for this allocation
const isCollectingQueryFees = await this.receiptCollector.collectReceipts(
actionID,
allocation,
)
// If there is not yet an indexingRule that deems this deployment worth allocating to, make one
if (!(await this.matchingRuleExists(logger, subgraphDeploymentID))) {
logger.debug(
`No matching indexing rule found; updating indexing rules so indexer-agent keeps the deployment synced but doesn't reallocate to it`,
)
const offchainIndexingRule = {
identifier: allocation.subgraphDeployment.id.ipfsHash,
identifierType: SubgraphIdentifierType.DEPLOYMENT,
decisionBasis: IndexingDecisionBasis.OFFCHAIN,
} as Partial<IndexingRuleAttributes>
await upsertIndexingRule(logger, this.models, offchainIndexingRule)
}
return {
actionID,
type: 'unallocate',
transactionID: receipt.transactionHash,
allocation: closeAllocationEventLogs.allocationID,
allocatedTokens: formatGRT(closeAllocationEventLogs.tokens),
indexingRewards: formatGRT(rewardsAssigned),
receiptsWorthCollecting: isCollectingQueryFees,
}
}
async populateUnallocateTransaction(
logger: Logger,
params: UnallocateTransactionParams,
): Promise<PopulatedTransaction> {
logger.debug(`Populating closeAllocation transaction`, {
allocationID: params.allocationID,
POI: params.poi,
})
return await this.contracts.staking.populateTransaction.closeAllocation(
params.allocationID,
params.poi,
)
}
async prepareUnallocate(
logger: Logger,
allocationID: string,
poi: string | undefined,
force: boolean,
): Promise<PopulatedTransaction> {
const params = await this.prepareUnallocateParams(logger, allocationID, poi, force)
return await this.populateUnallocateTransaction(logger, params)
}
async unallocate(
allocationID: string,
poi: string | undefined,
force: boolean,
): Promise<CloseAllocationResult> {
try {
const params = await this.prepareUnallocateParams(
this.logger,
allocationID,
poi,
force,
)
const allocation = await this.networkMonitor.allocation(allocationID)
if (!allocation) {
this.logger.warn('Allocation does not exist', {
allocationID,
})
throw indexerError(
IndexerErrorCode.IE063,
`Unallocate failed. No active allocation with id '${allocationID}' found`,
)
}
this.logger.debug('Sending closeAllocation transaction')
const receipt = await this.transactionManager.executeTransaction(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
() =>
this.contracts.staking.estimateGas.closeAllocation(
params.allocationID,
params.poi,
),
(gasLimit) =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.contracts.staking.closeAllocation(params.allocationID, params.poi, {
gasLimit,
}),
this.logger.child({ function: 'staking.closeAllocation' }),
)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return await this.confirmUnallocate(0, allocation.id!, receipt)
} catch (error) {
const err = indexerError(IndexerErrorCode.IE015, error)
this.logger.warn(`Failed to close allocation`, {
err,
})
throw err
}
}
async prepareReallocateParams(
logger: Logger,
allocationID: string,
poi: string | undefined,
amount: BigNumber,
force: boolean,
): Promise<ReallocateTransactionParams> {
logger.info('Preparing to reallocate', {
allocation: allocationID,
poi: poi || 'none provided',
amount: amount.toString(),
force,
})
const activeAllocations = await this.networkMonitor.allocations(
AllocationStatus.ACTIVE,
)
const allocationAddress = toAddress(allocationID)
const allocation = activeAllocations.find((allocation) => {
return allocation.id === allocationAddress
})
if (!allocation) {
logger.error(`No existing allocation`)
throw indexerError(
IndexerErrorCode.IE063,
`Reallocation failed: No active allocation with id '${allocationID}' found`,
)
}
// Ensure allocation is old enough to close
const currentEpoch = await this.contracts.epochManager.currentEpoch()
if (BigNumber.from(allocation.createdAtEpoch).eq(currentEpoch)) {
throw indexerError(
IndexerErrorCode.IE064,
`Allocation '${allocation.id}' cannot be closed until epoch ${currentEpoch.add(
1,
)}. (Allocations cannot be closed in the same epoch they were created)`,
)
}
logger.debug('Resolving POI')
const allocationPOI = await this.networkMonitor.resolvePOI(allocation, poi, force)
logger.debug('POI resolved', {
userProvidedPOI: poi,
poi: allocationPOI,
})
// Double-check whether the allocation is still active on chain, to
// avoid unnecessary transactions.
// Note: We're checking the allocation state here, which is defined as
//
// enum AllocationState { Null, Active, Closed, Finalized, Claimed }
//
// in the this.contracts.
const state = await this.contracts.staking.getAllocationState(allocation.id)
if (state !== 1) {
logger.warn(`Allocation has already been closed`)
throw indexerError(IndexerErrorCode.IE065, `Allocation has already been closed`)
}
if (amount.lt('0')) {
logger.warn('Cannot reallocate a negative amount of GRT', {
amount: amount.toString(),
})
throw indexerError(
IndexerErrorCode.IE061,
'Cannot reallocate a negative amount of GRT',
)
}
// Identify how many GRT the indexer has staked
const freeStake = await this.contracts.staking.getIndexerCapacity(this.indexer)
// When reallocating, we will first close the old allocation and free up the GRT in that allocation
// This GRT will be available in addition to freeStake for the new allocation
const postCloseFreeStake = freeStake.add(allocation.allocatedTokens)
// If there isn't enough left for allocating, abort
if (postCloseFreeStake.lt(amount)) {
throw indexerError(
IndexerErrorCode.IE013,
`Unable to allocate ${formatGRT(
amount,
)} GRT: indexer only has a free stake amount of ${formatGRT(
freeStake,
)} GRT, plus ${formatGRT(
allocation.allocatedTokens,
)} GRT from the existing allocation`,
)
}
logger.debug('Generating a new unique Allocation ID')
const { allocationSigner, allocationId: newAllocationId } = uniqueAllocationID(
this.transactionManager.wallet.mnemonic.phrase,
currentEpoch.toNumber(),
allocation.subgraphDeployment.id,
activeAllocations.map((allocation) => allocation.id),
)
logger.debug('New unique Allocation ID generated', {
newAllocationID: newAllocationId,
newAllocationSigner: allocationSigner,
})
// Double-check whether the allocationID already exists on chain, to
// avoid unnecessary transactions.
// Note: We're checking the allocation state here, which is defined as
//
// enum AllocationState { Null, Active, Closed, Finalized, Claimed }
//
// in the this.contracts.
const newAllocationState = await this.contracts.staking.getAllocationState(
newAllocationId,
)
if (newAllocationState !== 0) {
logger.warn(`Skipping Allocation as it already exists onchain`, {
indexer: this.indexer,
allocation: newAllocationId,
newAllocationState,
})
throw indexerError(IndexerErrorCode.IE066, 'AllocationID already exists')
}
logger.debug('Generating new allocation ID proof', {
newAllocationSigner: allocationSigner,
newAllocationID: newAllocationId,
indexerAddress: this.indexer,
})
const proof = await allocationIdProof(allocationSigner, this.indexer, newAllocationId)
logger.debug('Successfully generated allocation ID proof', {
allocationIDProof: proof,
})
logger.info(`Prepared closeAndAllocate transaction`, {
indexer: this.indexer,
oldAllocationAmount: formatGRT(allocation.allocatedTokens),
oldAllocation: allocation.id,
newAllocation: newAllocationId,
newAllocationAmount: formatGRT(amount),
deployment: allocation.subgraphDeployment.id.toString(),
poi: allocationPOI,
proof,
epoch: currentEpoch.toString(),
})
return {
closingAllocationID: allocation.id,
poi: allocationPOI,
indexer: this.indexer,
subgraphDeploymentID: allocation.subgraphDeployment.id.bytes32,
tokens: amount,
newAllocationID: newAllocationId,
metadata: utils.hexlify(Array(32).fill(0)),
proof,
}
}
async confirmReallocate(
actionID: number,
allocationID: string,
receipt: ContractReceipt | 'paused' | 'unauthorized',
): Promise<ReallocateAllocationResult> {
const logger = this.logger.child({ action: actionID })
logger.info(`Confirming 'closeAndAllocate' transaction`, {
allocationID,
})
if (receipt === 'paused' || receipt === 'unauthorized') {
throw indexerError(
IndexerErrorCode.IE062,
`Allocation '${allocationID}' could not be closed: ${receipt}`,
)
}
const closeAllocationEventLogs = this.findEvent(
'AllocationClosed',
this.contracts.staking.interface,
'allocationID',
allocationID,
receipt,
)
if (!closeAllocationEventLogs) {
throw indexerError(
IndexerErrorCode.IE015,
`Allocation close transaction was never successfully mined`,
)
}
const createAllocationEventLogs = this.findEvent(
'AllocationCreated',
this.contracts.staking.interface,
'subgraphDeploymentID',
closeAllocationEventLogs.subgraphDeploymentID,
receipt,
)
if (!createAllocationEventLogs) {
throw indexerError(
IndexerErrorCode.IE014,
`Allocation create transaction was never mined`,
)
}
const rewardsEventLogs = this.findEvent(
'RewardsAssigned',
this.contracts.rewardsManager.interface,
'allocationID',
allocationID,
receipt,
)
const rewardsAssigned = rewardsEventLogs ? rewardsEventLogs.amount : 0
if (rewardsAssigned == 0) {
logger.warn('No rewards were distributed upon closing the allocation')
}
const subgraphDeploymentID = new SubgraphDeploymentID(
closeAllocationEventLogs.subgraphDeploymentID,
)
logger.info(`Successfully reallocated to deployment`, {
deployment: subgraphDeploymentID.display,
closedAllocation: closeAllocationEventLogs.allocationID,
closedAllocationStakeGRT: formatGRT(closeAllocationEventLogs.tokens),
closedAllocationPOI: closeAllocationEventLogs.poi,
closedAllocationEpoch: closeAllocationEventLogs.epoch.toString(),
indexingRewardsCollected: formatGRT(rewardsAssigned),
createdAllocation: createAllocationEventLogs.allocationID,
createdAllocationStakeGRT: formatGRT(createAllocationEventLogs.tokens),
indexer: createAllocationEventLogs.indexer,
epoch: createAllocationEventLogs.epoch.toString(),
transaction: receipt.transactionHash,
})
logger.info('Identifying receipts worth collecting', {
allocation: closeAllocationEventLogs.allocationID,
})
const allocation = await this.networkMonitor.allocation(allocationID)