-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsubtasks.ts
2483 lines (2378 loc) · 86.3 KB
/
subtasks.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
/* eslint-disable no-await-in-loop, import/no-extraneous-dependencies */
import { DeploymentsExtension } from 'hardhat-deploy/dist/types';
import { fromWei, numberToHex, toChecksumAddress, toWei } from 'web3-utils';
import {
deleteJob,
getChainlinkAccounts,
getChainlinkBridges,
getChainlinkJobs,
postChainlinkBridge,
postChainlinkJob,
} from './chainlink-utils';
import { subtask } from 'hardhat/config';
import { ChainlinkNodeConfiguration } from './types';
import {
ERC20__factory,
ERC20PresetMinterPauser,
IMessenger,
IMessenger__factory,
MessengerRegistry,
MessengerRegistry__factory,
Oracle__factory,
Ownable__factory,
PeriodRegistry,
PeriodRegistry__factory,
PreCoordinator,
PreCoordinator__factory,
SLA,
SLA__factory,
SLARegistry,
SLARegistry__factory,
StakeRegistry,
StakeRegistry__factory,
} from './typechain';
import {
CONTRACT_NAMES,
GRAPH_NETWORKS,
NETWORKS,
PERIOD_STATUS,
PERIOD_TYPE,
TOKEN_NAMES,
} from './constants';
import {
bootstrapStrings,
generateBootstrapPeriods,
getIPFSHash,
getPreCoordinatorConfiguration,
printSeparator,
} from './utils';
import axios from 'axios';
import { HardhatRuntimeEnvironment } from 'hardhat/types';
import { formatBytes32String } from 'ethers/lib/utils';
const prettier = require('prettier');
const appRoot = require('app-root-path');
const fs = require('fs-extra');
const path = require('path');
const yaml = require('js-yaml');
const compose = require('docker-compose');
const moment = require('moment');
const consola = require('consola');
const Mustache = require('mustache');
export enum SUB_TASK_NAMES {
PREPARE_CHAINLINK_NODES = 'PREPARE_CHAINLINK_NODES',
SETUP_DOCKER_COMPOSE = 'SETUP_DOCKER_COMPOSE',
STOP_LOCAL_CHAINLINK_NODES = 'STOP_LOCAL_CHAINLINK_NODES',
START_LOCAL_CHAINLINK_NODES = 'START_LOCAL_CHAINLINK_NODES',
STOP_LOCAL_IPFS = 'STOP_LOCAL_IPFS',
START_LOCAL_IPFS = 'START_LOCAL_IPFS',
STOP_LOCAL_GANACHE = 'STOP_LOCAL_GANACHE',
START_LOCAL_GANACHE = 'START_LOCAL_GANACHE',
STOP_LOCAL_GRAPH_NODE = 'STOP_LOCAL_GRAPH_NODE',
START_LOCAL_GRAPH_NODE = 'START_LOCAL_GRAPH_NODE',
INITIALIZE_DEFAULT_ADDRESSES = 'INITIALIZE_DEFAULT_ADDRESSES',
EXPORT_NETWORKS = 'EXPORT_NETWORKS',
EXPORT_SUBGRAPH_DATA = 'EXPORT_SUBGRAPH_DATA',
EXPORT_TO_FRONT_END = 'EXPORT_TO_FRONT_END',
SETUP_GRAPH_MANIFESTOS = 'SETUP_GRAPH_MANIFESTOS',
DEPLOY_SLA = 'DEPLOY_SLA',
BOOTSTRAP_MESSENGER_REGISTRY = 'BOOTSTRAP_MESSENGER_REGISTRY',
BOOTSTRAP_PERIOD_REGISTRY = 'BOOTSTRAP_PERIOD_REGISTRY',
BOOTSTRAP_STAKE_REGISTRY = 'BOOTSTRAP_STAKE_REGISTRY',
SET_CONTRACTS_ALLOWANCE = 'SET_CONTRACTS_ALLOWANCE',
REQUEST_SLI = 'REQUEST_SLI',
GET_PRECOORDINATOR = 'GET_PRECOORDINATOR',
SET_PRECOORDINATOR = 'SET_PRECOORDINATOR',
DEPLOY_LOCAL_CHAINLINK_NODES = 'DEPLOY_LOCAL_CHAINLINK_NODES',
DEPLOY_CHAINLINK_CONTRACTS = 'DEPLOY_CHAINLINK_CONTRACTS',
UPDATE_PRECOORDINATOR = 'UPDATE_PRECOORDINATOR',
FULFILL_SLI = 'FULFILL_SLI',
CHECK_CONTRACTS_ALLOWANCE = 'CHECK_CONTRACTS_ALLOWANCE',
REGISTRIES_CONFIGURATION = 'REGISTRIES_CONFIGURATION',
GET_VALID_SLAS = 'GET_VALID_SLAS',
GET_REVERT_MESSAGE = 'GET_REVERT_MESSAGE',
DEPLOY_MESSENGER = 'DEPLOY_MESSENGER',
GET_MESSENGER = 'GET_MESSENGER',
TRANSFER_OWNERSHIP = 'TRANSFER_OWNERSHIP',
PROVIDER_WITHDRAW = 'PROVIDER_WITHDRAW',
UNLOCK_TOKENS = 'UNLOCK_TOKENS',
GET_SLA_FROM_TX = 'GET_SLA_FROM_TX',
UPDATE_MESSENGER_SPEC = 'UPDATE_MESSENGER_SPEC',
}
subtask(SUB_TASK_NAMES.GET_SLA_FROM_TX, undefined).setAction(
async (taskArgs, hre: HardhatRuntimeEnvironment) => {
const { ethers } = hre;
const { provider, getContract } = ethers;
const { getTransactionReceipt } = provider;
const { transactionHash } = taskArgs;
const transaction = await getTransactionReceipt(transactionHash);
const slaRegistry: SLARegistry = await getContract(
CONTRACT_NAMES.SLARegistry
);
const filter = slaRegistry.filters.SLACreated(null, transaction.from);
const events = await slaRegistry.queryFilter(filter, transaction.blockHash);
console.log(events);
}
);
subtask(SUB_TASK_NAMES.UPDATE_MESSENGER_SPEC, undefined).setAction(
async (taskArgs, hre: HardhatRuntimeEnvironment) => {
const { network, ethers, getNamedAccounts } = hre;
const { deployer } = await getNamedAccounts();
const { stacktical } = network.config;
const { index } = taskArgs;
const messenger = stacktical.messengers[index];
consola.info('Selected Messenger');
consola.info(messenger);
const messengerContract = <IMessenger>(
await ethers.getContract(messenger.contract)
);
const messengerRegistry = <MessengerRegistry>(
await ethers.getContract(CONTRACT_NAMES.MessengerRegistry)
);
const filter = messengerRegistry.filters.MessengerRegistered(
deployer,
messengerContract.address
);
const events = await messengerRegistry.queryFilter(filter);
const messengerId = events[0].args.id;
const specificationPath = `${appRoot.path}/contracts/messengers/${messenger.useCaseName}/use-case-spec.json`;
const messengerSpec = JSON.parse(fs.readFileSync(specificationPath));
const updatedSpec = {
...messengerSpec,
timestamp: new Date().toISOString(),
};
consola.info('New spec');
consola.info(updatedSpec);
const seMessengerSpecIPFS = await getIPFSHash(updatedSpec, stacktical.ipfs);
const specUrl = `${stacktical.ipfs}/ipfs/${seMessengerSpecIPFS}`;
consola.info('New specification url');
consola.info(specUrl);
const tx = await messengerRegistry.modifyMessenger(specUrl, messengerId);
await tx.wait();
}
);
subtask(SUB_TASK_NAMES.UNLOCK_TOKENS, undefined).setAction(
async (taskArgs, hre: HardhatRuntimeEnvironment) => {
const { ethers, getNamedAccounts } = hre;
const { deployer } = await getNamedAccounts();
const slaRegistry = <SLARegistry>(
await ethers.getContract(CONTRACT_NAMES.SLARegistry)
);
const slaAddress = taskArgs.slaAddress
? ethers.utils.getAddress(taskArgs.slaAddress)
: (await slaRegistry.allSLAs()).slice(-1)[0];
const slaContract = <SLA>(
await ethers.getContractAt(CONTRACT_NAMES.SLA, slaAddress)
);
printSeparator();
consola.info('SLA address:', slaContract.address);
consola.info('Requester address:', deployer);
const tx = await slaRegistry.returnLockedValue(slaAddress);
await tx.wait();
const stakeRegistry = <StakeRegistry>(
await ethers.getContract(CONTRACT_NAMES.StakeRegistry)
);
const filter = stakeRegistry.filters.LockedValueReturned(
slaAddress,
deployer
);
const query = await stakeRegistry.queryFilter(filter);
consola.info('DSLA returned:', fromWei(query[0].args.amount.toString()));
printSeparator();
}
);
subtask(SUB_TASK_NAMES.PROVIDER_WITHDRAW, undefined).setAction(
async (taskArgs, hre: HardhatRuntimeEnvironment) => {
const { ethers, getNamedAccounts } = hre;
const { deployer } = await getNamedAccounts();
const slaRegistry = <SLARegistry>(
await ethers.getContract(CONTRACT_NAMES.SLARegistry)
);
const slaAddress = taskArgs.slaAddress
? ethers.utils.getAddress(taskArgs.slaAddress)
: (await slaRegistry.allSLAs()).slice(-1)[0];
const slaContract = <SLA>(
await ethers.getContractAt(CONTRACT_NAMES.SLA, slaAddress)
);
printSeparator();
consola.info('SLA address:', slaContract.address);
consola.info('Requester address:', deployer);
const LPtokenAddress = await slaContract.dpTokenRegistry(
taskArgs.tokenAddress
);
consola.info('LP token address:', LPtokenAddress);
const lpToken = <ERC20PresetMinterPauser>(
await ethers.getContractAt('ERC20PresetMinterPauser', LPtokenAddress)
);
const lpTokenUserBalance = await lpToken.balanceOf(deployer);
consola.info(
'LP token user balance:',
fromWei(lpTokenUserBalance.toString())
);
// const token = <ERC20PresetMinterPauser>(
// await ethers.getContractAt(
// 'ERC20PresetMinterPauser',
// taskArgs.tokenAddress
// )
// );
const supply = await lpToken.totalSupply();
consola.info('LP token total supply:', fromWei(supply.toString()));
const slaProviderPool = await slaContract.providerPool(
taskArgs.tokenAddress
);
const slaUserPool = await slaContract.usersPool(taskArgs.tokenAddress);
consola.info(
'SLA provider pool balance:',
fromWei(slaProviderPool.toString())
);
const poolPercentage = lpTokenUserBalance.div(supply).mul(100);
consola.info('Accrued pool percentage:', poolPercentage.toString() + '%');
const leverage = await slaContract.leverage();
consola.info('SLA leverage:', leverage.toString() + 'x');
const poolSpread = slaProviderPool.sub(slaUserPool.mul(leverage));
consola.info(
'Provider pool allowed withdraw amount:',
fromWei(poolSpread.toString())
);
await lpToken.approve(slaAddress, lpTokenUserBalance);
const accruedBalance = lpTokenUserBalance.mul(slaProviderPool).div(supply);
const allowedWithdraw = accruedBalance.gt(poolSpread)
? poolSpread
: accruedBalance;
if (allowedWithdraw.gt(0)) {
consola.info(
'User allowed withdraw amount:',
fromWei(allowedWithdraw.toString())
);
await slaContract.withdrawProviderTokens(
allowedWithdraw,
taskArgs.tokenAddress
);
} else {
consola.warn('Allowed withdraw amount is 0');
}
printSeparator();
}
);
subtask(SUB_TASK_NAMES.STOP_LOCAL_CHAINLINK_NODES, undefined).setAction(
async (_, hre: HardhatRuntimeEnvironment) => {
const { stacktical } = hre.network.config;
for (let node of stacktical.chainlink.nodesConfiguration) {
await compose.down({
cwd: path.join(
`${appRoot.path}/services/chainlink-nodes/${hre.network.name}-${node.name}/`
),
log: true,
});
}
}
);
subtask(SUB_TASK_NAMES.START_LOCAL_CHAINLINK_NODES, undefined).setAction(
async (_, hre: HardhatRuntimeEnvironment) => {
const { stacktical } = hre.network.config;
for (let node of stacktical.chainlink.nodesConfiguration) {
await compose.upAll({
cwd: path.join(
`${appRoot.path}/services/chainlink-nodes/${hre.network.name}-${node.name}/`
),
log: true,
});
}
}
);
subtask(SUB_TASK_NAMES.START_LOCAL_GANACHE, undefined).setAction(async () => {
await compose.upAll({
cwd: path.join(`${appRoot.path}/services/ganache/`),
log: true,
});
});
subtask(SUB_TASK_NAMES.STOP_LOCAL_GANACHE, undefined).setAction(async () => {
await compose.down({
cwd: path.join(`${appRoot.path}/services/ganache/`),
log: true,
});
});
subtask(SUB_TASK_NAMES.START_LOCAL_IPFS, undefined).setAction(async () => {
await compose.upAll({
cwd: path.join(`${appRoot.path}/services/ipfs/`),
log: true,
});
});
subtask(SUB_TASK_NAMES.STOP_LOCAL_IPFS, undefined).setAction(async () => {
await compose.down({
cwd: path.join(`${appRoot.path}/services/ipfs/`),
log: true,
});
});
subtask(SUB_TASK_NAMES.START_LOCAL_GRAPH_NODE, undefined).setAction(
async () => {
await compose.upAll({
cwd: path.join(`${appRoot.path}/services/graph-protocol/`),
log: true,
});
}
);
subtask(SUB_TASK_NAMES.STOP_LOCAL_GRAPH_NODE, undefined).setAction(async () => {
await compose.down({
cwd: path.join(`${appRoot.path}/services/graph-protocol/`),
log: true,
});
fs.rmSync(`${appRoot.path}/services/graph-protocol/postgres`, {
recursive: true,
force: true,
});
});
subtask(SUB_TASK_NAMES.SETUP_GRAPH_MANIFESTOS, undefined).setAction(
async () => {
const networks = fs
.readdirSync(`${appRoot}/subgraph/networks`)
.filter((dir) => /.subgraph.json/.test(dir))
.map((dir) => dir.split('.')[0]);
for (let network of networks) {
consola.info('Preparing Graph Protocol manifesto for network ' + network);
const yamlPath = `${appRoot}/subgraph/networks/${network}.subgraph.yaml`;
const jsonPath = `${appRoot}/subgraph/networks/${network}.subgraph.json`;
const specs = JSON.parse(fs.readFileSync(jsonPath));
fs.copyFileSync(`${appRoot}/subgraph/subgraph.template.yaml`, yamlPath);
const template = fs.readFileSync(yamlPath, 'utf8');
const manifesto = Mustache.render(template, specs);
fs.writeFileSync(yamlPath, manifesto);
}
consola.success('Graph Protocol manifestos correctly created');
}
);
subtask(SUB_TASK_NAMES.SETUP_DOCKER_COMPOSE, undefined).setAction(
async (_, hre: HardhatRuntimeEnvironment) => {
const { deployments, network } = hre;
const { get } = deployments;
const { stacktical } = network.config;
const linkToken = await get(CONTRACT_NAMES.LinkToken);
if (stacktical.chainlink.cleanLocalFolder) {
const folders = fs
.readdirSync(`${appRoot.path}/services/chainlink-nodes/`)
.filter((folder) => new RegExp(`${network.name}`).test(folder));
for (let folder of folders) {
fs.rmSync(`${appRoot.path}/services/chainlink-nodes/${folder}`, {
recursive: true,
});
}
}
for (let node of stacktical.chainlink.nodesConfiguration) {
const nodeName = network.name + '-' + node.name;
const fileContents = fs.readFileSync(
`${appRoot.path}/services/docker-compose.yaml`,
'utf8'
);
const data = yaml.load(fileContents);
data.services.chainlink.environment =
data.services.chainlink.environment.map((envVariable) => {
switch (true) {
case /LINK_CONTRACT_ADDRESS/.test(envVariable):
return `LINK_CONTRACT_ADDRESS=${linkToken.address}`;
case /ETH_CHAIN_ID/.test(envVariable):
return `ETH_CHAIN_ID=${network.config.chainId}`;
case /ETH_URL/.test(envVariable):
return `ETH_URL=${stacktical.chainlink.ethWsUrl}`;
case /ETH_HTTP_URL/.test(envVariable):
return `ETH_HTTP_URL=${
stacktical.chainlink.ethHttpUrl || (network.config as any).url
}`;
case /CHAINLINK_PORT/.test(envVariable):
return `CHAINLINK_PORT=${node.restApiPort}`;
default:
return envVariable;
}
});
data.services.postgres.container_name = `postgres-${nodeName}`;
data.services.postgres.networks = [`${nodeName}-network`];
data.services.chainlink.container_name = `chainlink-${nodeName}`;
data.services.chainlink.networks = [`${nodeName}-network`];
data.services.chainlink.ports = [
`${node.restApiPort}:${node.restApiPort}`,
];
data.networks = {
[`${nodeName}-network`]: {
name: `${nodeName}-developer-toolkit-network`,
},
};
const yamlStr = yaml.dump(data);
fs.mkdirSync(`${appRoot.path}/services/chainlink-nodes/${nodeName}/`, {
recursive: true,
});
fs.mkdirSync(
`${appRoot.path}/services/chainlink-nodes/${nodeName}/chainlink`,
{
recursive: true,
}
);
fs.mkdirSync(
`${appRoot.path}/services/chainlink-nodes/${nodeName}/postgres`,
{
recursive: true,
}
);
fs.copyFileSync(
`${appRoot.path}/services/.api`,
`${appRoot.path}/services/chainlink-nodes/${nodeName}/chainlink/.api`
);
fs.copyFileSync(
`${appRoot.path}/services/.password`,
`${appRoot.path}/services/chainlink-nodes/${nodeName}/chainlink/.password`
);
fs.writeFileSync(
`${appRoot.path}/services/chainlink-nodes/${nodeName}/docker-compose.yaml`,
yamlStr,
'utf8'
);
}
}
);
subtask(SUB_TASK_NAMES.PREPARE_CHAINLINK_NODES, undefined).setAction(
async (taskArgs, hre: HardhatRuntimeEnvironment) => {
const { deployments, network, ethers, getNamedAccounts, web3 } = hre;
const { deployer } = await getNamedAccounts();
const { get } = deployments;
const { stacktical } = network.config;
const oracle = await get(CONTRACT_NAMES.Oracle);
function wait(timeout) {
return new Promise((resolve) => {
setTimeout(resolve, timeout);
});
}
const updatedBridge = async (
node: ChainlinkNodeConfiguration,
useCaseName,
externalAdapterUrl
) => {
try {
const bridges = await getChainlinkBridges(node);
const storedBridge = bridges.find(
(bridge) => bridge.attributes.name === useCaseName
);
if (storedBridge) return storedBridge;
const httpRequestJobRes = await postChainlinkBridge(
node,
useCaseName,
externalAdapterUrl
);
return httpRequestJobRes.data;
} catch (error) {
return false;
}
};
const updatedJob = async (node: ChainlinkNodeConfiguration, jobName) => {
try {
const postedJobs = await getChainlinkJobs(node);
const postedJob = postedJobs.find(
(job) =>
job.attributes.tasks.some((task) => task.type === jobName) &&
job.attributes.initiators.some(
(initiator) =>
toChecksumAddress(initiator.params.address) === oracle.address
)
);
if (postedJob) {
if (!stacktical.chainlink.deleteOldJobs) {
console.log('Keeping existing jobId: ' + postedJob.id);
return postedJob;
}
console.log('Deleting existing jobId: ' + postedJob.id);
await deleteJob(node, postedJob.id);
}
const httpRequestJobRes = await postChainlinkJob(
node,
jobName,
oracle.address
);
return httpRequestJobRes.data;
} catch (error) {
return false;
}
};
const updatedAddress = async (node: ChainlinkNodeConfiguration) => {
try {
const addresses = await getChainlinkAccounts(node);
if (addresses.length === 0) return false;
const {
attributes: { address },
} = addresses.find((address) => !address.attributes.isFunding);
return toChecksumAddress(address);
} catch (error) {
return false;
}
};
// Create bridge
console.log('Starting automated configuration for Chainlink nodes...');
for (let node of stacktical.chainlink.nodesConfiguration) {
printSeparator();
console.log('Preparing node: ' + node.name);
const messengers = taskArgs.index
? [stacktical.messengers[taskArgs.index]]
: stacktical.messengers;
for (let messenger of messengers) {
consola.info('Creating use case configuration: ' + messenger.contract);
let bridge = await updatedBridge(
node,
messenger.useCaseName,
messenger.externalAdapterUrl
);
while (!bridge) {
// eslint-disable-next-line no-await-in-loop
await wait(5000);
console.log(
'Bridge creation in Chainlink node failed, reattempting in 5 seconds'
);
// eslint-disable-next-line no-await-in-loop
bridge = await updatedBridge(
node,
messenger.useCaseName,
messenger.externalAdapterUrl
);
}
console.log(`Bridge created! Bridge ID: ${bridge.id}.`);
// Create job
// eslint-disable-next-line global-require
let job = await updatedJob(node, messenger.useCaseName);
while (!job) {
// eslint-disable-next-line no-await-in-loop
await wait(5000);
console.log(
'Job creation in Chainlink node failed, reattempting in 5 seconds'
);
// eslint-disable-next-line no-await-in-loop
job = await updatedJob(node, messenger.useCaseName);
}
console.log(`Job created! Job ID: ${job.id}.`);
}
// Fund node
let chainlinkNodeAddress = await updatedAddress(node);
while (!chainlinkNodeAddress) {
await wait(5000);
console.log(
'Address fetch from Chainlink node failed, reattempting in 5 seconds'
);
chainlinkNodeAddress = await updatedAddress(node);
}
console.log(`Chainlink Node Address: ${chainlinkNodeAddress}`);
const { nodeFunds } = stacktical.chainlink;
const [defaultAccount] = await web3.eth.getAccounts();
let balance = await web3.eth.getBalance(chainlinkNodeAddress);
if (Number(web3.utils.fromWei(balance)) < Number(nodeFunds)) {
await web3.eth.sendTransaction({
from: defaultAccount,
to: chainlinkNodeAddress,
value: web3.utils.toWei(String(nodeFunds), 'ether'),
...(network.config.gas !== 'auto' && {
gasLimit: network.config.gas,
}),
});
}
balance = await web3.eth.getBalance(chainlinkNodeAddress);
console.log(
`Chainlink Node balance: ${web3.utils.fromWei(balance)} ether`
);
// Authorize node
const oracleContract = Oracle__factory.connect(
oracle.address,
await ethers.getSigner(deployer)
);
let permissions = await oracleContract.getAuthorizationStatus(
chainlinkNodeAddress
);
if (!permissions) {
const tx = await oracleContract.setFulfillmentPermission(
chainlinkNodeAddress,
true,
{
...(network.config.gas !== 'auto' && {
gasLimit: network.config.gas,
}),
}
);
await tx.wait();
}
permissions = await oracleContract.getAuthorizationStatus(
chainlinkNodeAddress
);
console.log(`Chainlink Node Fullfillment permissions: ${permissions}`);
console.log('Automated configuration finished for node: ' + node.name);
printSeparator();
}
console.log('Automated configuration finished for all nodes');
}
);
subtask(SUB_TASK_NAMES.DEPLOY_LOCAL_CHAINLINK_NODES, undefined).setAction(
async (_, hre: HardhatRuntimeEnvironment) => {
const localServicesSubtasks = [
SUB_TASK_NAMES.SETUP_DOCKER_COMPOSE,
SUB_TASK_NAMES.STOP_LOCAL_CHAINLINK_NODES,
SUB_TASK_NAMES.START_LOCAL_CHAINLINK_NODES,
SUB_TASK_NAMES.PREPARE_CHAINLINK_NODES,
];
const { run } = hre;
for (let subtask of localServicesSubtasks) {
console.log(subtask);
await run(subtask);
}
}
);
subtask(
SUB_TASK_NAMES.INITIALIZE_DEFAULT_ADDRESSES,
'Saves addresses from stacktical config'
).setAction(async (_, hre: HardhatRuntimeEnvironment) => {
const { deployments, network } = hre;
const { stacktical } = network.config;
const { getArtifact }: DeploymentsExtension = deployments;
for (let contractName of Object.keys(stacktical.addresses)) {
const artifact = await getArtifact(contractName);
await deployments.save(contractName, {
address: stacktical.addresses[contractName],
abi: artifact.abi,
});
}
for (let token of stacktical.tokens) {
if (token.address) {
await deployments.save(token.name, {
address: token.address,
abi: token.factory.abi,
});
}
}
});
subtask(SUB_TASK_NAMES.EXPORT_NETWORKS, undefined).setAction(
async (_, hre: HardhatRuntimeEnvironment) => {
consola.info('Starting export contracts addresses process');
const exportedNetworks = [];
const base_path = `${appRoot}/exported-data`;
const networks = fs.readdirSync(`${appRoot}/deployments/`);
for (let network of networks.filter(
(network) => !['localhost', 'hardhat'].includes(network)
)) {
try {
consola.info('Exporting ' + network + ' data');
const SLORegistry = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/SLORegistry.json`)
);
const SLARegistry = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/SLARegistry.json`)
);
const MessengerRegistry = JSON.parse(
fs.readFileSync(
`${appRoot}/deployments/${network}/MessengerRegistry.json`
)
);
const PeriodRegistry = JSON.parse(
fs.readFileSync(
`${appRoot}/deployments/${network}/PeriodRegistry.json`
)
);
const StakeRegistry = JSON.parse(
fs.readFileSync(
`${appRoot}/deployments/${network}/StakeRegistry.json`
)
);
const PreCoordinator = JSON.parse(
fs.readFileSync(
`${appRoot}/deployments/${network}/PreCoordinator.json`
)
);
const StringUtils = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/StringUtils.json`)
);
const { tokens, messengers } = hre.config.networks[network].stacktical;
const addresses = {
SLORegistry: SLORegistry.address,
SLARegistry: SLARegistry.address,
MessengerRegistry: MessengerRegistry.address,
PeriodRegistry: PeriodRegistry.address,
StakeRegistry: StakeRegistry.address,
PreCoordinator: PreCoordinator.address,
StringUtils: StringUtils.address,
...tokens.reduce(
(r, token) => ({
...r,
[token.name + 'Token']: require(appRoot.path +
'/deployments/' +
network +
'/' +
token.name).address,
}),
{}
),
...messengers.reduce(
(r, messenger) => ({
...r,
[messenger.contract]: require(appRoot.path +
'/deployments/' +
network +
'/' +
messenger.contract).address,
}),
{}
),
};
consola.info('Resulting addresses');
console.log(addresses);
const prettifiedAddresses = prettier.format(
`export const ${network} = ` + JSON.stringify(addresses),
{
useTabs: false,
tabWidth: 2,
singleQuote: true,
parser: 'typescript',
}
);
fs.writeFileSync(
path.resolve(__dirname, `${base_path}/${network}.ts`),
prettifiedAddresses
);
exportedNetworks.push(network);
} catch (error) {
consola.error('Error getting data for ' + network + ' network');
consola.error(error.message);
}
}
const exportLines = exportedNetworks.reduce(
(r, network) => (r += `export {${network}} from './${network}'\n`),
''
);
const prettifiedIndex = prettier.format(`${exportLines}\n`, {
useTabs: false,
tabWidth: 2,
singleQuote: true,
parser: 'typescript',
});
fs.appendFile(
path.resolve(__dirname, `${base_path}/index.ts`),
prettifiedIndex
);
consola.success('Contract addresses exported correctly');
}
);
subtask(SUB_TASK_NAMES.EXPORT_TO_FRONT_END, undefined).setAction(async () => {
consola.info('Exporting contracts addresses to frontend apps');
if (fs.existsSync(`${appRoot}/../stacktical-dsla-frontend`)) {
printSeparator();
let srcPath = `${appRoot}/exported-data`;
consola.info('Exporting to Stacktical dApp frontend');
let destPath = `${appRoot}/../stacktical-dsla-frontend/src/addresses`;
fs.copySync(srcPath, destPath, { overwrite: true });
consola.success('Contract address export to Stacktical dApp finished');
consola.info('Exporting typechain to Stacktical dApp');
srcPath = `${appRoot}/typechain`;
destPath = `${appRoot}/../stacktical-dsla-frontend/src/typechain`;
fs.copySync(srcPath, destPath, { overwrite: true });
consola.success('Typechain export to Stacktical dApp finished');
} else {
printSeparator();
consola.warn('Stacktical dApp frontend folder not found');
}
if (fs.existsSync(`${appRoot}/../dsla-protocol-app`)) {
printSeparator();
let srcPath = `${appRoot}/exported-data`;
consola.info('Exporting to DSLA protocol dApp frontend');
let destPath = `${appRoot}/../dsla-protocol-app/src/addresses`;
fs.copySync(srcPath, destPath, { overwrite: true });
consola.success('Contract address export DSLA protocol dApp finished');
consola.info('Exporting typechain DSLA protocol dApp');
srcPath = `${appRoot}/typechain`;
destPath = `${appRoot}/../dsla-protocol-app/src/typechain`;
fs.copySync(srcPath, destPath, { overwrite: true });
consola.success('Typechain export DSLA protocol dApp finished');
} else {
printSeparator();
consola.warn(' DSLA protocol dApp folder not found');
}
printSeparator();
});
// subtask(SUB_TASK_NAMES.EXPORT_NETWORKS, undefined).setAction(
// async (_, hre: HardhatRuntimeEnvironment) => {
// const { network, deployments } = hre;
// const { get } = deployments;
// const { stacktical } = network.config;
//
// consola.info('Starting export contracts addresses process');
// const SLORegistry = await get(CONTRACT_NAMES.SLORegistry);
// const SLARegistry = await get(CONTRACT_NAMES.SLARegistry);
// const MessengerRegistry = await get(CONTRACT_NAMES.MessengerRegistry);
// const PeriodRegistry = await get(CONTRACT_NAMES.PeriodRegistry);
// const StakeRegistry = await get(CONTRACT_NAMES.StakeRegistry);
// const Details = await get(CONTRACT_NAMES.Details);
// const PreCoordinator = await get(CONTRACT_NAMES.PreCoordinator);
// const StringUtils = await get(CONTRACT_NAMES.StringUtils);
//
// const addresses = {
// SLORegistry: SLORegistry.address,
// SLARegistry: SLARegistry.address,
// MessengerRegistry: MessengerRegistry.address,
// PeriodRegistry: PeriodRegistry.address,
// StakeRegistry: StakeRegistry.address,
// Details: Details.address,
// PreCoordinator: PreCoordinator.address,
// StringUtils: StringUtils.address,
// ...stacktical.tokens.reduce(
// (r, token) => ({
// ...r,
// [token.name + 'Token']: require(appRoot.path +
// '/deployments/' +
// network.name +
// '/' +
// token.name).address,
// }),
// {}
// ),
// ...stacktical.messengers.reduce(
// (r, messenger) => ({
// ...r,
// [messenger.contract]: require(appRoot.path +
// '/deployments/' +
// network.name +
// '/' +
// messenger.contract).address,
// }),
// {}
// ),
// };
// consola.info('Resulting addresses');
// console.log(addresses);
// const base_path = `${appRoot}/exported-data`;
// const prettifiedAddresses = prettier.format(
// `export const ${network.name} = ` + JSON.stringify(addresses),
// {
// useTabs: false,
// tabWidth: 2,
// singleQuote: true,
// parser: 'typescript',
// }
// );
// fs.writeFileSync(
// path.resolve(__dirname, `${base_path}/${network.name}.ts`),
// prettifiedAddresses
// );
//
// const exportLines = networks
// .filter((network) => network.exportable)
// .reduce(
// (r, network) =>
// (r += `export {${network.name}} from './${network.name}'\n`),
// ''
// );
// const prettifiedIndex = prettier.format(`${exportLines}\n`, {
// useTabs: false,
// tabWidth: 2,
// singleQuote: true,
// parser: 'typescript',
// });
// fs.writeFileSync(
// path.resolve(__dirname, `${base_path}/index.ts`),
// prettifiedIndex
// );
// consola.success('Contract addresses exported correctly');
// }
// );
subtask(SUB_TASK_NAMES.EXPORT_SUBGRAPH_DATA, undefined).setAction(async () => {
consola.info('Starting subgraph json data file creation process');
const networks = fs.readdirSync(`${appRoot}/deployments/`);
for (let network of networks.filter(
(network) => !['localhost', 'hardhat'].includes(network)
)) {
consola.info('Exporting ' + network + ' data');
try {
const SLORegistry = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/SLORegistry.json`)
);
const SLARegistry = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/SLARegistry.json`)
);
const StakeRegistry = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/StakeRegistry.json`)
);
const MessengerRegistry = JSON.parse(
fs.readFileSync(
`${appRoot}/deployments/${network}/MessengerRegistry.json`
)
);
const PeriodRegistry = JSON.parse(
fs.readFileSync(`${appRoot}/deployments/${network}/PeriodRegistry.json`)
);
const data = {
slaRegistryAddress: SLARegistry.address,
slaRegistryStartBlock: SLARegistry.receipt.blockNumber,
sloRegistryAddress: SLORegistry.address,
sloRegistryStartBlock: SLORegistry.receipt.blockNumber,
stakeRegistryAddress: StakeRegistry.address,
stakeRegistryStartBlock: StakeRegistry.receipt.blockNumber,
messengerRegistryAddress: MessengerRegistry.address,
messengerRegistryStartBlock: MessengerRegistry.receipt.blockNumber,
periodRegistryAddress: PeriodRegistry.address,
periodRegistryStartBlock: PeriodRegistry.receipt.blockNumber,
graphNetwork: GRAPH_NETWORKS[network],
};
consola.info('Resulting data');
consola.info(data);
const base_path = `${appRoot}/subgraph/networks`;
const prettifiedAddresses = prettier.format(JSON.stringify(data), {
useTabs: false,
tabWidth: 2,
singleQuote: true,
parser: 'json',
});
fs.writeFileSync(
path.resolve(__dirname, `${base_path}/${network}.subgraph.json`),
prettifiedAddresses
);
} catch (error) {
consola.error('Error getting data for ' + network + ' network');
consola.error(error.message);
}
}
consola.success('Subgraph json data file creation process finished');
});
subtask(SUB_TASK_NAMES.BOOTSTRAP_STAKE_REGISTRY, undefined).setAction(
async (_, hre: HardhatRuntimeEnvironment) => {
const {
stacktical: { bootstrap, tokens },
} = hre.network.config;
const {
registry: {
stake: { stakingParameters },
},
} = bootstrap;
const { deployments, ethers, getNamedAccounts, network } = hre;
const { deployer } = await getNamedAccounts();
const signer = await ethers.getSigner(deployer);
const { get } = deployments;
const [startBootstrap, finishBootstrap] = bootstrapStrings(
CONTRACT_NAMES.StakeRegistry
);
console.log(startBootstrap);