-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmethods.ts
More file actions
1386 lines (1308 loc) · 48.6 KB
/
methods.ts
File metadata and controls
1386 lines (1308 loc) · 48.6 KB
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 AggregatorV3Interface from "@chainlink/contracts/abi/v0.8/AggregatorV3Interface.json";
import type { ContractTransaction } from "@ethersproject/contracts";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import { BigNumber, ethers } from "ethers";
import { readFileSync } from "fs";
import type { HardhatRuntimeEnvironment, TaskArguments } from "hardhat/types";
import { BetterSet } from "../../libs/better-set";
import type { DRCoordinator } from "../../src/types";
import {
convertJobIdToBytes32,
getLinkBalanceOf,
getNetworkLinkAddress,
getNetworkLinkAddressDeployingOnHardhat,
getNetworkLinkTknFeedAddress,
} from "../../utils/chainlink";
import { LINK_TOTAL_SUPPLY, MIN_CONSUMER_GAS_LIMIT, chainIdL2SequencerFeed } from "../../utils/chainlink-constants";
import { ChainId } from "../../utils/constants";
import { getNumberOfConfirmations, getOverrides, isAddressAContract } from "../../utils/deployment";
import { formatNumericEnumValuesPretty } from "../../utils/enums";
import { impersonateAccount, setAddressCode } from "../../utils/hre";
import { logger } from "../../utils/logger";
import { reSemVer, reUUID } from "../../utils/regex";
import type { Overrides } from "../../utils/types";
import { setChainVerifyApiKeyEnv } from "../../utils/verification";
import {
ChainlinkNodeId,
DUMMY_SET_CODE_BYTES,
ExternalAdapterId,
FeeType,
MAX_PERMYRIAD_FEE,
PERMYRIAD,
PaymentType,
TaskExecutionMode,
TaskName,
} from "./constants";
import {
Configuration,
ConfigurationConverted,
ConsumersConverted,
DRCoordinatorLogConfig,
DeployData,
Description,
ExternalAdapter,
SpecAuthorizedConsumersConverted,
SpecConverted,
SpecItem,
SpecItemConverted,
} from "./types";
export async function addFunds(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
consumer: string,
amount: BigNumber,
overrides?: Overrides,
): Promise<void> {
const logObj = { consumer, amount: amount.toString() };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).addFunds(consumer, amount, overrides);
logger.info(logObj, `addFunds() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `addFunds() failed due to:`);
throw error;
}
}
export async function addSpecAuthorizedConsumers(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
key: string,
specAuthorizedConsumers: SpecAuthorizedConsumersConverted,
overrides: Overrides,
specToIndexMap?: Map<string, number>,
): Promise<void> {
const indexToKey: Record<number, string> = {};
if (specToIndexMap) {
indexToKey[specToIndexMap.get(key) as number] = key;
}
const logObj = { "file indeces": indexToKey, key, specAuthorizedConsumers };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).addSpecAuthorizedConsumers(key, specAuthorizedConsumers, overrides);
logger.info(logObj, `addSpecAuthorizedConsumers() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `addSpecAuthorizedConsumers() failed due to:`);
throw error;
}
}
export async function addSpecs(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
fileSpecMap: Map<string, SpecItemConverted>,
keysToAddSet: Set<string>,
isBatchMode: boolean,
overrides: Overrides,
batchSize?: number,
): Promise<void> {
logger.info(`${keysToAddSet.size ? `adding specs into DRCoordinator ...` : `no specs to add into DRCoordinator`}`);
if (!keysToAddSet.size) return;
const specToIndexMap = new Map(Array.from([...fileSpecMap.keys()].entries()).map(([idx, key]) => [key, idx]));
if (isBatchMode) {
const keys = [...keysToAddSet];
const fileSpecs = keys.map(key => (fileSpecMap.get(key) as SpecItemConverted).specConverted);
const chunkSize = batchSize || keys.length;
for (let i = 0; i < keys.length; i += chunkSize) {
await setSpecs(
drCoordinator,
signer,
keys.slice(i, i + chunkSize),
fileSpecs.slice(i, i + chunkSize),
overrides,
`Added in batch (${i}, ${i + chunkSize - 1})`,
specToIndexMap,
);
}
} else {
for (const key of keysToAddSet) {
const fileSpec = fileSpecMap.get(key) as SpecItemConverted;
await setSpec(drCoordinator, signer, key, fileSpec.specConverted, overrides, "Added", specToIndexMap);
}
}
}
export async function addSpecsAuthorizedConsumers(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keys: string[],
specsAuthorizedConsumers: SpecAuthorizedConsumersConverted[],
overrides: Overrides,
specToIndexMap?: Map<string, number>,
): Promise<void> {
const indexToKey: Record<number, string> = {};
if (specToIndexMap) {
keys.forEach(key => (indexToKey[specToIndexMap.get(key) as number] = key));
}
const logObj = { "file indeces": indexToKey, keys, specsAuthorizedConsumers };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).addSpecsAuthorizedConsumers(keys, specsAuthorizedConsumers, overrides);
logger.info(logObj, `addSpecsAuthorizedConsumers() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `addSpecsAuthorizedConsumers() failed due to:`);
throw error;
}
}
export function checkSpecsIntegrity(specs: SpecItem[], chainId: ChainId): void {
if (!Array.isArray(specs)) {
throw new Error(`Invalid specs file data format. Expected an array of Spec items`);
}
// Validate specs
const jsonValues = Object.values(specs);
const keySet = new Set<string>();
for (const [idx, { description, configuration, consumers }] of jsonValues.entries()) {
try {
validateDescription(description, chainId);
validateConfiguration(configuration);
validateConsumers(consumers);
} catch (error) {
throw new Error(`Invalid entry at index ${idx}: ${JSON.stringify(specs[idx])}. Reason: ${error}`);
}
const specId = convertJobIdToBytes32(configuration.externalJobId);
const key = generateSpecKey(configuration.operator, specId);
if (keySet.has(key)) {
throw new Error(
`Invalid entry at index ${idx}: ${JSON.stringify(specs[idx])}. ` +
`Reason: there already is a Spec in the file with the same 'externalJobId' and 'oracle'`,
);
}
keySet.add(key);
}
}
export async function deleteSpecs(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keysToRemoveSet: Set<string>,
isBatchMode: boolean,
overrides: Overrides,
batchSize?: number,
): Promise<void> {
logger.info(
`${keysToRemoveSet.size ? `deleting specs from DRCoordinator ...` : `no specs to delete from DRCoordinator`}`,
);
if (!keysToRemoveSet.size) return;
if (isBatchMode) {
const keys = [...keysToRemoveSet];
const chunkSize = batchSize || keys.length;
for (let i = 0; i < keys.length; i += chunkSize) {
await removeSpecs(
drCoordinator,
signer,
keys.slice(i, i + chunkSize),
overrides,
`Removed in batch (${i}, ${i + chunkSize - 1})`,
);
}
} else {
for (const key of keysToRemoveSet) {
await removeSpec(drCoordinator, signer, key, overrides);
}
}
}
export async function deleteSpecsAuthorizedConsumers(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
fileSpecMap: Map<string, SpecItemConverted>,
specAuthorizedConsumerToRemoveMap: Map<string, SpecAuthorizedConsumersConverted>,
keysToRemove: string[],
isBatchMode: boolean,
overrides: Overrides,
batchSize?: number,
): Promise<void> {
// Perform the additions
logger.info(
`${
keysToRemove.length
? `deleting specs' authorized consumers into DRCoordinator ...`
: `no specs' authorized consumers to delete into DRCoordinator`
}`,
);
if (!keysToRemove.length) return;
const specToIndexMap = new Map(Array.from([...fileSpecMap.keys()].entries()).map(([idx, key]) => [key, idx]));
if (isBatchMode) {
const fileConsumers = keysToRemove.map(key => specAuthorizedConsumerToRemoveMap.get(key) as ConsumersConverted);
const chunkSize = batchSize || keysToRemove.length;
for (let i = 0; i < keysToRemove.length; i += chunkSize) {
await removeSpecsAuthorizedConsumers(
drCoordinator,
signer,
keysToRemove.slice(i, i + chunkSize),
fileConsumers.slice(i, i + chunkSize),
overrides,
specToIndexMap,
);
}
} else {
for (const key of keysToRemove) {
const fileAuthorizedConsumers = specAuthorizedConsumerToRemoveMap.get(key) as SpecAuthorizedConsumersConverted;
await removeSpecAuthorizedConsumers(
drCoordinator,
signer,
key,
fileAuthorizedConsumers,
overrides,
specToIndexMap,
);
}
}
}
export async function deployDRCoordinator(
hre: HardhatRuntimeEnvironment,
signer: ethers.Wallet | SignerWithAddress,
description: string,
fallbackWeiPerUnitLink: BigNumber,
stalenessSeconds: BigNumber,
isMultiPriceFeedDependant: boolean,
priceFeed1?: string,
priceFeed2?: string,
l2SequencerGracePeriod?: BigNumber,
overrides?: Overrides,
numberOfConfirmations?: number,
): Promise<DeployData> {
let addressLink: string;
let addressPriceFeed1: string;
let addressPriceFeed2: string;
let isL2SequencerDependant: boolean;
let addressL2SequencerFeed: string;
let l2SequencerGracePeriodSeconds: BigNumber;
const chainId = hre.network.config.chainId as number;
if (isMultiPriceFeedDependant) {
addressPriceFeed1 = priceFeed1 as string;
addressPriceFeed2 = priceFeed2 as string;
} else {
addressPriceFeed1 =
chainId === ChainId.HARDHAT
? "0x3Af8C569ab77af5230596Acf0E8c2F9351d24C38" // LINK / ETH on Ethereum
: getNetworkLinkTknFeedAddress(hre.network);
addressPriceFeed2 = ethers.constants.AddressZero;
}
if (chainId === ChainId.HARDHAT) {
overrides = {};
// NB: dry-run mode for the Hardhat network
addressLink = await getNetworkLinkAddressDeployingOnHardhat(hre); // ethers.constants.AddressZero;
await setAddressCode(hre, addressPriceFeed1, DUMMY_SET_CODE_BYTES); // NB: bypass constructor checks
if (isMultiPriceFeedDependant) {
await setAddressCode(hre, addressPriceFeed2, DUMMY_SET_CODE_BYTES); // NB: bypass constructor checks
}
isL2SequencerDependant = false;
addressL2SequencerFeed = ethers.constants.AddressZero;
l2SequencerGracePeriodSeconds = BigNumber.from("0");
} else {
addressLink = getNetworkLinkAddress(hre.network);
}
const isL2WithSequencerChain = chainIdL2SequencerFeed.has(chainId);
if (isL2WithSequencerChain) {
isL2SequencerDependant = true;
addressL2SequencerFeed = chainIdL2SequencerFeed.get(chainId) as string;
l2SequencerGracePeriodSeconds = l2SequencerGracePeriod as BigNumber;
} else {
isL2SequencerDependant = false;
addressL2SequencerFeed = ethers.constants.AddressZero;
l2SequencerGracePeriodSeconds = BigNumber.from("0");
}
// Deploy
const logObj = {
addressLink,
isMultiPriceFeedDependant,
addressPriceFeed1,
addressPriceFeed2,
description,
fallbackWeiPerUnitLink,
stalenessSeconds,
isL2SequencerDependant,
addressL2SequencerFeed,
l2SequencerGracePeriodSeconds,
};
const drCoordinatorFactory = await hre.ethers.getContractFactory("DRCoordinator");
const drCoordinator = (await drCoordinatorFactory
.connect(signer)
.deploy(
addressLink,
isMultiPriceFeedDependant,
addressPriceFeed1,
addressPriceFeed2,
description,
fallbackWeiPerUnitLink,
stalenessSeconds,
isL2SequencerDependant,
addressL2SequencerFeed,
l2SequencerGracePeriodSeconds,
overrides,
)) as DRCoordinator;
logger.info(
logObj,
`DRCoordinator deployed to: ${drCoordinator.address} | Tx hash: ${drCoordinator.deployTransaction.hash}`,
);
await drCoordinator
.connect(signer)
.deployTransaction.wait(getNumberOfConfirmations(hre.network.config.chainId, numberOfConfirmations));
return {
drCoordinator,
addressLink,
isMultiPriceFeedDependant,
addressPriceFeed1,
addressPriceFeed2,
description,
fallbackWeiPerUnitLink,
stalenessSeconds,
isL2SequencerDependant,
addressL2SequencerFeed,
l2SequencerGracePeriodSeconds,
};
}
export function generateSpecKey(operatorAddr: string, specId: string): string {
return ethers.utils.keccak256(ethers.utils.solidityPack(["address", "bytes32"], [operatorAddr, specId]));
}
export async function getDRCoordinator(
hre: HardhatRuntimeEnvironment,
address: string,
mode: TaskExecutionMode,
signer?: ethers.Wallet | SignerWithAddress,
overrides?: Overrides,
): Promise<DRCoordinator> {
let drCoordinator: DRCoordinator;
if (mode === TaskExecutionMode.DRYRUN) {
if (!signer || !overrides) {
throw new Error(
`Missing 'signer' and/or 'overrides' on mode: ${mode}. Signer: ${JSON.stringify(
signer,
)} | Overrides: ${JSON.stringify(overrides)}`,
);
}
const deployData = await deployDRCoordinator(
hre,
signer,
"DRCoordinator for dry run mode on hardhat", // description
BigNumber.from("8000000000000000"), // fallbackWeiPerUnitLink
BigNumber.from("86400"), // stalenessSeconds
false,
);
drCoordinator = deployData.drCoordinator;
} else if ([TaskExecutionMode.FORKING, TaskExecutionMode.PROD].includes(mode)) {
// Get DRCoordinator contract at address
const drCoordinatorArtifact = await hre.artifacts.readArtifact("DRCoordinator");
drCoordinator = (await hre.ethers.getContractAt(drCoordinatorArtifact.abi, address)) as DRCoordinator;
// Check if the contract exists at address
if (!isAddressAContract(drCoordinator)) {
throw new Error(
`Unable to find ${drCoordinatorArtifact.contractName} on network '${hre.network.name}' at address ${address}`,
);
}
} else {
throw new Error(`Unsupported 'mode': ${mode}`);
}
return drCoordinator;
}
export async function getSpecAuthorizedConsumersMap(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keys: string[],
): Promise<Map<string, SpecAuthorizedConsumersConverted>> {
const specAuthorizedConsumersConvertedMap: Map<string, SpecAuthorizedConsumersConverted> = new Map([]);
for (const key of keys) {
const authorizedConsumers = await drCoordinator.connect(signer).getSpecAuthorizedConsumers(key);
specAuthorizedConsumersConvertedMap.set(key, authorizedConsumers);
}
return specAuthorizedConsumersConvertedMap;
}
export async function getSpecConfigurationConverted(configuration: Configuration): Promise<ConfigurationConverted> {
const operator = configuration.operator;
const specId = convertJobIdToBytes32(configuration.externalJobId);
const key = generateSpecKey(operator, specId);
return {
fee: BigNumber.from(configuration.fee),
feeType: configuration.feeType,
gasLimit: configuration.gasLimit,
key,
operator,
payment: BigNumber.from(configuration.payment),
paymentType: configuration.paymentType,
specId,
};
}
export async function getSpecItemConvertedMap(specs: SpecItem[]): Promise<Map<string, SpecItemConverted>> {
const specItemConvertedMap: Map<string, SpecItemConverted> = new Map();
for (const [idx, { configuration, consumers }] of specs.entries()) {
// Process the spec configuration
let configurationConverted: ConfigurationConverted;
try {
configurationConverted = await getSpecConfigurationConverted(configuration);
} catch (error) {
logger.error(
`unexpected error converting the 'configuration' of the spec at index ${idx}: ${JSON.stringify(
configuration,
)}. Reason:`,
);
throw error;
}
// Process the spec consumers
specItemConvertedMap.set(configurationConverted.key, {
specConverted: configurationConverted,
specAuthorizedConsumers: consumers,
});
}
return specItemConvertedMap;
}
export async function getSpecMap(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keys: string[],
): Promise<Map<string, SpecConverted>> {
const specConvertedMap: Map<string, SpecConverted> = new Map();
for (const key of keys) {
const { specId, operator, payment, paymentType, fee, feeType, gasLimit } = await drCoordinator
.connect(signer)
.getSpec(key);
const spec = {
fee,
feeType,
gasLimit,
key,
operator,
payment,
paymentType,
specId,
};
specConvertedMap.set(key, spec);
}
return specConvertedMap;
}
export function hasSpecDifferences(fileSpec: SpecConverted, drcSpec: SpecConverted): boolean {
return (
!fileSpec.fee.eq(drcSpec.fee) ||
fileSpec.feeType !== drcSpec.feeType ||
fileSpec.gasLimit !== drcSpec.gasLimit ||
fileSpec.payment !== drcSpec.payment ||
fileSpec.paymentType !== drcSpec.paymentType
);
}
export async function insertSpecsAuthorizedConsumers(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
fileSpecMap: Map<string, SpecItemConverted>,
specAuthorizedConsumerToAddMap: Map<string, SpecAuthorizedConsumersConverted>,
keysToAdd: string[],
isBatchMode: boolean,
overrides: Overrides,
batchSize?: number,
): Promise<void> {
// Perform the additions
logger.info(
`${
keysToAdd.length
? `adding specs' authorized consumers into DRCoordinator ...`
: `no specs' authorized consumers to add into DRCoordinator`
}`,
);
if (!keysToAdd.length) return;
const specToIndexMap = new Map(Array.from([...fileSpecMap.keys()].entries()).map(([idx, key]) => [key, idx]));
if (isBatchMode) {
const fileConsumers = keysToAdd.map(key => specAuthorizedConsumerToAddMap.get(key) as ConsumersConverted);
const chunkSize = batchSize || keysToAdd.length;
for (let i = 0; i < keysToAdd.length; i += chunkSize) {
await addSpecsAuthorizedConsumers(
drCoordinator,
signer,
keysToAdd.slice(i, i + chunkSize),
fileConsumers.slice(i, i + chunkSize),
overrides,
specToIndexMap,
);
}
} else {
for (const key of keysToAdd) {
const fileAuthorizedConsumers = specAuthorizedConsumerToAddMap.get(key) as SpecAuthorizedConsumersConverted;
await addSpecAuthorizedConsumers(drCoordinator, signer, key, fileAuthorizedConsumers, overrides, specToIndexMap);
}
}
}
export async function logDRCoordinatorDetail(
hre: HardhatRuntimeEnvironment,
drCoordinator: DRCoordinator,
logConfig: DRCoordinatorLogConfig,
signer: ethers.Wallet | SignerWithAddress,
): Promise<void> {
const chainId = hre.network.config.chainId as number;
const isHardhatNetwork = chainId === ChainId.HARDHAT;
if (logConfig.detail) {
const address = drCoordinator.connect(signer).address;
const typeAndVersion = await drCoordinator.connect(signer).typeAndVersion();
const description = await drCoordinator.connect(signer).getDescription();
const owner = await drCoordinator.connect(signer).owner();
const paused = await drCoordinator.connect(signer).paused();
const addressLink = await drCoordinator.connect(signer).getLinkToken();
const isMultiPriceFeedDependant = await drCoordinator.connect(signer).getIsMultiPriceFeedDependant();
const addressPriceFeed1 = await drCoordinator.connect(signer).getPriceFeed1();
const addressPriceFeed2 = await drCoordinator.connect(signer).getPriceFeed2();
const isL2SequencerDependant = await drCoordinator.connect(signer).getIsL2SequencerDependant();
const addressL2SequencerFeed = await drCoordinator.connect(signer).getL2SequencerFeed();
const gasAfterPaymentCalculation = await drCoordinator.connect(signer).getGasAfterPaymentCalculation();
const fallbackWeiPerUnitLink = await drCoordinator.connect(signer).getFallbackWeiPerUnitLink();
const permyriadFeeFactor = await drCoordinator.connect(signer).getPermyriadFeeFactor();
const stalenessSeconds = await drCoordinator.connect(signer).getStalenessSeconds();
const l2SequencerGracePeriodSeconds = await drCoordinator.connect(signer).getL2SequencerGracePeriodSeconds();
const linkBalance = await getLinkBalanceOf(hre, signer, drCoordinator.address, addressLink);
const linkProfit = await drCoordinator.connect(signer).availableFunds(drCoordinator.address);
// Get feeds descriptions
let priceFeed1;
let priceFeed2;
let l2SequencerFeed;
try {
priceFeed1 = await hre.ethers.getContractAt(AggregatorV3Interface, addressPriceFeed1);
} catch (error) {
throw new Error(`Unexpected error reading Price Feed 1 at: ${addressPriceFeed1}. Reason: ${error}`);
}
if (isMultiPriceFeedDependant) {
try {
priceFeed2 = await hre.ethers.getContractAt(AggregatorV3Interface, addressPriceFeed2);
} catch (error) {
throw new Error(`Unexpected error reading Price Feed 2 at: ${addressPriceFeed2}. Reason: ${error}`);
}
}
if (isL2SequencerDependant) {
try {
l2SequencerFeed = await hre.ethers.getContractAt(AggregatorV3Interface, addressL2SequencerFeed);
} catch (error) {
throw new Error(
`Unexpected error reading L2 Sequencer Uptime Status Feed at: ${addressL2SequencerFeed}. Reason: ${error}`,
);
}
}
const descriptionPriceFeed1 = isHardhatNetwork ? "N/A (Hardhat)" : await priceFeed1.connect(signer).description();
const descriptionPriceFeed2 = isHardhatNetwork
? "N/A (Hardhat)"
: isMultiPriceFeedDependant
? await (priceFeed2 as ethers.Contract).connect(signer).description()
: "N/A";
const descriptionL2SequencerFeed2 = isHardhatNetwork
? "N/A (Hardhat)"
: isL2SequencerDependant
? await (l2SequencerFeed as ethers.Contract).connect(signer).description()
: "N/A";
logger.info(
{
address: address,
typeAndVersion: typeAndVersion,
description: description,
owner: owner,
paused: paused,
balance: `${ethers.utils.formatUnits(linkBalance)} LINK`,
profit: `${ethers.utils.formatUnits(linkProfit)} LINK`,
LINK: addressLink,
IS_MULTI_PRICE_FEED_DEPENDANT: isMultiPriceFeedDependant,
PRICE_FEED_1: `${addressPriceFeed1} (${descriptionPriceFeed1})`,
PRICE_FEED_2: `${addressPriceFeed2} (${descriptionPriceFeed2})`,
IS_L2_SEQUENCER_DEPENDANT: isL2SequencerDependant,
L2_SEQUENCER_FEEED: `${addressL2SequencerFeed} (${descriptionL2SequencerFeed2})`,
L2_SEQUENCER_GRACE_PERIOD_SECONDS: isL2SequencerDependant
? l2SequencerGracePeriodSeconds
: `${l2SequencerGracePeriodSeconds} (N/A)`,
GAS_AFTER_PAYMENT_CALCULATION: `${gasAfterPaymentCalculation}`,
fallbackWeiPerUnitLink: `${fallbackWeiPerUnitLink}`,
permyriadFeeFactor: `${permyriadFeeFactor}`,
stalenessSeconds: `${stalenessSeconds}`,
},
"detail:",
);
}
if (logConfig.keys) {
const keys = await drCoordinator.connect(signer).getSpecMapKeys();
logger.info(keys, "keys:");
}
if (logConfig.specs) {
const keys = await drCoordinator.connect(signer).getSpecMapKeys();
const specMap = await getSpecMap(drCoordinator, signer, keys);
logger.info([...specMap.values()], `specs:`);
}
if (logConfig.authconsumers) {
const keys = await drCoordinator.connect(signer).getSpecMapKeys();
const specAuthorizedConsumersMap = await getSpecAuthorizedConsumersMap(drCoordinator, signer, keys);
logger.info([...specAuthorizedConsumersMap.values()], `authconsumers:`);
}
}
export async function transferOwnership(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
owner: string,
overrides?: Overrides,
): Promise<void> {
const logObj = { owner };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).transferOwnership(owner, overrides);
logger.info(logObj, `transferOwnership() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `transferOwnership() failed due to:`);
throw error;
}
}
export async function setupDRCoordinatorAfterDeploy(
taskArguments: TaskArguments,
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
overrides: Overrides,
) {
// Transfer ownership
if (taskArguments.owner) {
await transferOwnership(drCoordinator, signer, taskArguments.owner as string, overrides);
}
}
export async function pause(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
overrides: Overrides,
): Promise<void> {
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).pause(overrides);
logger.info(`pause() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.error(error, `pause() failed due to:`);
throw error;
}
}
export function parseAndCheckSpecsFile(filePath: string, chainId: ChainId): SpecItem[] {
// Read and parse the specs JSON file
const specs = parseSpecsFile(filePath);
// Validate specs file
checkSpecsIntegrity(specs, chainId);
return specs;
}
export function parseSpecsFile(filePath: string): SpecItem[] {
let specs: SpecItem[];
try {
specs = JSON.parse(readFileSync(filePath, "utf-8")) as SpecItem[];
} catch (error) {
logger.error(error, `unexpected error reading file: ${filePath}. Make sure the JSON file exists`);
throw error;
}
return specs;
}
export async function removeSpec(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
key: string,
overrides: Overrides,
): Promise<void> {
const logObj = { key };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).removeSpec(key, overrides);
logger.info(logObj, `removeSpec() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `removeSpec() failed due to:`);
throw error;
}
}
export async function removeSpecAuthorizedConsumers(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
key: string,
specAuthorizedConsumers: SpecAuthorizedConsumersConverted,
overrides: Overrides,
specToIndexMap?: Map<string, number>,
): Promise<void> {
const indexToKey: Record<number, string> = {};
if (specToIndexMap) {
indexToKey[specToIndexMap.get(key) as number] = key;
}
const logObj = { "file indeces": indexToKey, key, specAuthorizedConsumers };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).removeSpecAuthorizedConsumers(key, specAuthorizedConsumers, overrides);
logger.info(logObj, `removeSpecAuthorizedConsumers() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `removeSpecAuthorizedConsumers() failed due to:`);
throw error;
}
}
export async function removeSpecs(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keys: string[],
overrides: Overrides,
action = "Removed",
): Promise<void> {
const logObj = { keys };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).removeSpecs(keys, overrides);
logger.info(logObj, `removeSpecs() ${action} specs | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `removeSpecs() failed due to:`);
throw error;
}
}
export async function removeSpecsAuthorizedConsumers(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keys: string[],
specsAuthorizedConsumers: SpecAuthorizedConsumersConverted[],
overrides: Overrides,
specToIndexMap?: Map<string, number>,
): Promise<void> {
const indexToKey: Record<number, string> = {};
if (specToIndexMap) {
keys.forEach(key => (indexToKey[specToIndexMap.get(key) as number] = key));
}
const logObj = { "file indeces": indexToKey, keys, specsAuthorizedConsumers };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).removeSpecsAuthorizedConsumers(keys, specsAuthorizedConsumers, overrides);
logger.info(logObj, `removeSpecsAuthorizedConsumers() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `removeSpecsAuthorizedConsumers() failed due to:`);
throw error;
}
}
export async function setCodeOnSpecContractAddresses(hre: HardhatRuntimeEnvironment, specs: SpecItem[]): Promise<void> {
const configurations = specs.map((spec: SpecItem) => spec.configuration);
let contractAddresses: string[] = [];
configurations.forEach((configuration: Configuration) => {
contractAddresses = contractAddresses.concat([configuration.operator]);
});
for (const address of contractAddresses) {
await setAddressCode(hre, address, DUMMY_SET_CODE_BYTES);
}
}
export async function setDescription(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
description: string,
overrides: Overrides,
): Promise<void> {
const logObj = { description };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setDescription(description, overrides);
logger.info(logObj, `setDescription() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setDescription() failed due to:`);
throw error;
}
}
export async function setFallbackWeiPerUnitLink(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
fallbackWeiPerUnitLink: BigNumber,
overrides: Overrides,
): Promise<void> {
const logObj = { fallbackWeiPerUnitLink };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setFallbackWeiPerUnitLink(fallbackWeiPerUnitLink, overrides);
logger.info(logObj, `setFallbackWeiPerUnitLink() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setFallbackWeiPerUnitLink() failed due to:`);
throw error;
}
}
export async function setL2SequencerGracePeriodSeconds(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
l2SequencerGracePeriodSeconds: BigNumber,
overrides: Overrides,
): Promise<void> {
const logObj = { l2SequencerGracePeriodSeconds };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setL2SequencerGracePeriodSeconds(l2SequencerGracePeriodSeconds, overrides);
logger.info(logObj, `setL2SequencerGracePeriodSeconds() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setL2SequencerGracePeriodSeconds() failed due to:`);
throw error;
}
}
export async function setPermyriadFeeFactor(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
permyriadFeeFactor: BigNumber,
overrides: Overrides,
): Promise<void> {
const logObj = { permyriadFeeFactor };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setPermyriadFeeFactor(permyriadFeeFactor, overrides);
logger.info(logObj, `setPermyriadFeeFactor() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setPermyriadFeeFactor() failed due to:`);
throw error;
}
}
export async function setSpec(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
key: string,
spec: SpecConverted,
overrides: Overrides,
action = "Set",
specToIndexMap?: Map<string, number>,
): Promise<void> {
const indexToKey: Record<number, string> = {};
if (specToIndexMap) {
indexToKey[specToIndexMap.get(key) as number] = key;
}
const logObj = { action, "file indeces": indexToKey, key, spec };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setSpec(key, spec, overrides);
logger.info(logObj, `setSpec() ${action} | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setSpec() failed due to:`);
throw error;
}
}
export async function setSpecs(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
keys: string[],
specs: SpecConverted[],
overrides: Overrides,
action = "Set",
specToIndexMap?: Map<string, number>,
): Promise<void> {
const indexToKey: Record<number, string> = {};
if (specToIndexMap) {
keys.forEach(key => (indexToKey[specToIndexMap.get(key) as number] = key));
}
const logObj = { action, "file indeces": indexToKey, keys, specs };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setSpecs(keys, specs, overrides);
logger.info(logObj, `setSpecs() ${action} | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setSpecs() failed due to:`);
throw error;
}
}
export async function setStalenessSeconds(
drCoordinator: DRCoordinator,
signer: ethers.Wallet | SignerWithAddress,
stalenessSeconds: BigNumber,
overrides: Overrides,
): Promise<void> {
const logObj = { stalenessSeconds };
let tx: ContractTransaction;
try {
tx = await drCoordinator.connect(signer).setStalenessSeconds(stalenessSeconds, overrides);
logger.info(logObj, `setStalenessSeconds() | Tx hash: ${tx.hash}`);
await tx.wait();
} catch (error) {
logger.child(logObj).error(error, `setStalenessSeconds() failed due to:`);
throw error;
}
}
export async function setupDRCoordinatorBeforeTask(
taskArguments: TaskArguments,
hre: HardhatRuntimeEnvironment,
taskName: TaskName,
) {
logger.warn(
`*** Running ${(taskName as string).toUpperCase()} on ${(taskArguments.mode as string).toUpperCase()} mode ***`,
);
// Dryrun mode checks
if (taskArguments.mode === TaskExecutionMode.DRYRUN && hre.network.config.chainId !== ChainId.HARDHAT) {
throw new Error(`Task 'mode' '${taskArguments.mode}' (default) requires the Hardhat Network`);
}
// Forking mode checks
if (taskArguments.mode === TaskExecutionMode.FORKING && !hre.config.networks.hardhat.forking?.enabled) {
throw new Error(
`Task 'mode' '${taskArguments.mode}' requires the Hardhat Network forking-config setup and enabled. ` +
`Please, set HARDHAT_FORKING_ENABLED and your HARDHAT_FORKING_URL in the .env file`,
);
}
if (taskArguments.mode === TaskExecutionMode.FORKING && hre.network.config.chainId !== ChainId.HARDHAT) {
throw new Error(
`Task 'mode' '${taskArguments.mode}' must not pass a network, otherwise it will transact on it. ` +
`Please remove the '--network <network_name>' task argument`,
);
}
if (taskArguments.mode === TaskExecutionMode.FORKING && !taskArguments.apeaddress) {
throw new Error(`Task 'mode' '${taskArguments.mode}' requires the 'apeaddress' task argument`);
}
// Get the contract method overrides
const overrides = await getOverrides(taskArguments, hre);
// Instantiate the signer of the network
let [signer] = await hre.ethers.getSigners();
logger.info(`signer address: ${signer.address}`);
// Open and chec the specs file
let specs: undefined | SpecItem[];
if (taskName === TaskName.IMPORT_FILE) {
// Read and parse the specs JSON file
logger.info(`parsing and checking specs file: ${taskArguments.filename}.json ...`);
const filePath = `./jobs/drcoordinator-specs/${taskArguments.filename}.json`;