-
Notifications
You must be signed in to change notification settings - Fork 13
/
2keyBuilder.js
749 lines (653 loc) Β· 28.6 KB
/
2keyBuilder.js
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
const fs = require('fs');
const path = require('path');
const util = require('util');
const tar = require('tar');
const sha256 = require('js-sha256');
const { networks: truffleNetworks } = require('./truffle');
const simpleGit = require('simple-git/promise');
const moment = require('moment');
const whitelist = require('./ContractDeploymentWhiteList.json');
const readline = require('readline');
const readdir = util.promisify(fs.readdir);
const buildPath = path.join(__dirname, 'build');
const contractsBuildPath = path.join(__dirname, 'build', 'contracts');
const twoKeyProtocolDir = path.join(__dirname, '2key-protocol', 'src');
const twoKeyProtocolDist = path.join(__dirname, '2key-protocol', 'dist');
const twoKeyProtocolLibDir = path.join(__dirname, '2key-protocol', 'dist');
const twoKeyProtocolSubmodulesDir = path.join(__dirname, '2key-protocol', 'dist', 'submodules');
const contractsGit = simpleGit();
const twoKeyProtocolLibGit = simpleGit(twoKeyProtocolLibDir);
const twoKeyProtocolSrcGit = simpleGit(twoKeyProtocolDir);
const tenderlyDir = path.join(__dirname, 'tenderlyConfigurations');
const buildArchPath = path.join(twoKeyProtocolDir, 'contracts{branch}.tar.gz');
let deployment = process.env.FORCE_DEPLOYMENT || false;
const {
runProcess,
runDeployTokenSellCampaignMigration,
runDeployDonationCampaignMigration,
runUpdateMigration,
rmDir,
getGitBranch,
slack_message,
sortMechanism,
ipfsAdd,
ipfsGet,
runDeployCPCCampaignMigration,
runTruffleCompile,
runDeployCPCNoRewardsMigration,
runDeployPlasmaParticipationsMining
} = require('./helpers');
const branch_to_env = {
"develop": "test",
"staging": "staging",
"master": "prod"
};
const deployedTo = {};
let contractsStatus;
/**
* Function which will get the difference between the latest tags depending on current branch we're using. Either on merge requests or on current branch.
* @returns {Promise<void>}
*/
const getDiffBetweenLatestTags = async () => {
const tagsDevelop = (await contractsGit.tags()).all.filter(item => item.endsWith('-develop')).sort(sortMechanism);
let latestTagDev = tagsDevelop[tagsDevelop.length-1];
const tagsStaging = (await contractsGit.tags()).all.filter(item => item.endsWith('-staging')).sort(sortMechanism);
let latestTagStaging = tagsStaging[tagsStaging.length-1];
const tagsMaster = (await contractsGit.tags()).all.filter(item => item.endsWith('-master')).sort(sortMechanism);
let latestTagMaster = tagsMaster[tagsMaster.length-1];
let status = await contractsGit.status();
let diffParams;
if (status.current === 'staging') {
diffParams = latestTagStaging;
} else if (status.current === 'develop') {
diffParams = latestTagDev;
} else if (status.current === 'master') {
diffParams = latestTagMaster;
}
let diffAllContracts = (await contractsGit.diffSummary(diffParams)).files.filter(item => item.file.endsWith('.sol')).map(item => item.file);
let singletonsChanged = diffAllContracts.filter(item => item.includes('/singleton-contracts/') || item.includes('/token-pools')).map(item => item.split('/').pop().replace(".sol",""));
let tokenSellCampaignChanged = diffAllContracts.filter(item => item.includes('/acquisition-campaign-contracts/')|| item.includes('/campaign-mutual-contracts/')).map(item => item.split('/').pop().replace(".sol",""));
let donationCampaignChanged = diffAllContracts.filter(item => item.includes('/campaign-mutual-contracts/') || item.includes('/donation-campaign-contracts/')).map(item => item.split('/').pop().replace(".sol",""));
let cpcChanged = diffAllContracts.filter(item => item.includes('/cpc-campaign-contracts/')).map(item => item.split('/').pop().replace(".sol",""));
let cpcNoRewardsChanged = diffAllContracts.filter(item => item.includes('/cpc-campaign-no-rewards/')).map(item => item.split('/').pop().replace(".sol",""));
//Restore from archive the latest build so we can check which contracts are new
restoreFromArchive();
//Check the files which have never been deployed and exclude them from script
for(let i=0; i<singletonsChanged.length; i++) {
if(!checkIfContractDeployedEver(singletonsChanged[i])) {
singletonsChanged.splice(i,1);
i = i-1; //catch when 2 contracts we're removing are one next to another
}
}
return [
singletonsChanged,
tokenSellCampaignChanged.length > 0,
donationCampaignChanged.length > 0,
cpcChanged.length > 0,
cpcNoRewardsChanged.length > 0
];
};
const checkIfContractDeployedEver = (contractName) => {
let artifactPath = `./build/contracts/${contractName}.json`
let build = {};
if (fs.existsSync(artifactPath)) {
build = JSON.parse(fs.readFileSync(artifactPath, { encoding: 'utf-8' }));
return Object.keys(build.networks).length > 0;
} else {
return false;
}
}
const generateChangelog = async () => {
await runProcess('git-chglog',['-o','CHANGELOG.md'])
};
const getBuildArchPath = () => {
if(contractsStatus && contractsStatus.current) {
return buildArchPath.replace('{branch}',`-${contractsStatus.current}`);
}
return buildArchPath;
};
const pullTenderlyConfiguration = async () => {
let branch = await getGitBranch();
let origin = `${tenderlyDir}/tenderly-${branch}.yaml`;
let destination = 'tenderly.yaml';
console.log(`${origin} will be copied to ${destination}`);
fs.copyFile(origin, 'tenderly.yaml' , (err) => {
if (err) throw err;
});
};
const tenderlyPush = async (npmVersionTag) => {
try {
await runProcess('tenderly', ['push', '--tag', npmVersionTag]);
} catch (e) {
console.log('Error caught during tenderly push.');
}
}
const getContractsDeployedPath = () => {
const result = path.join(twoKeyProtocolDir,'contracts_deployed{branch}.json');
if(contractsStatus && contractsStatus.current) {
return result.replace('{branch}',`-${contractsStatus.current}`);
}
return result;
};
const getContractsDeployedDistPath = () => {
const result = path.join(twoKeyProtocolDist,'contracts_deployed{branch}.json');
if(contractsStatus && contractsStatus.current) {
return result.replace('{branch}',`-${contractsStatus.current}`);
}
return result;
};
const getVersionsPath = (branch = true) => {
const result = path.join(twoKeyProtocolDir,'versions{branch}.json');
if (branch) {
if(contractsStatus && contractsStatus.current) {
return result.replace('{branch}',`-${contractsStatus.current}`);
}
return result;
}
return result.replace('{branch}', '');
};
const archiveBuild = () => tar.c({ gzip: true, file: getBuildArchPath(), cwd: __dirname }, ['build']);
const restoreFromArchive = () => {
// Restore file only if exists
if(fs.existsSync(getBuildArchPath())) {
return tar.x({file: getBuildArchPath(), gzip: true, cwd: __dirname});
}
};
const generateSOLInterface = () => new Promise((resolve, reject) => {
if (fs.existsSync(buildPath)) {
let contracts = {
'contracts': {},
};
let singletonAddresses = [];
const proxyFile = path.join(buildPath, 'proxyAddresses.json');
let json = {};
let data = {};
let proxyAddresses = {};
if (fs.existsSync(proxyFile)) {
proxyAddresses = JSON.parse(fs.readFileSync(proxyFile, { encoding: 'utf-8' }));
}
readdir(contractsBuildPath).then((files) => {
try {
files.forEach((file) => {
const {
networks, contractName, bytecode, abi
} = JSON.parse(fs.readFileSync(path.join(contractsBuildPath, file), { encoding: 'utf-8' }));
if (whitelist[contractName]) {
const whiteListedContract = whitelist[contractName];
const proxyNetworks = proxyAddresses[contractName] || {};
const mergedNetworks = {};
Object.keys(networks).forEach(key => {
mergedNetworks[key] = { ...networks[key], ...proxyNetworks[key] };
if(proxyNetworks[key]) {
singletonAddresses.push(proxyNetworks[key].address);
singletonAddresses.push(proxyNetworks[key].implementationAddressStorage);
}
});
if (!contracts.contracts[whiteListedContract.file]) {
contracts.contracts[whiteListedContract.file] = {};
}
contracts.contracts[whiteListedContract.file][contractName] = { abi, name: contractName };
if (whiteListedContract.networks) {
contracts.contracts[whiteListedContract.file][contractName].networks = mergedNetworks;
}
if (whiteListedContract.bytecode) {
contracts.contracts[whiteListedContract.file][contractName].bytecode = bytecode;
}
json[contractName] = whitelist[contractName].singleton
? {networks: mergedNetworks, abi, name: contractName} : {bytecode, abi, name: contractName};
let networkKeys = Object.keys(networks);
networkKeys.forEach((key) => {
if (Array.isArray(data[key.toString()])) {
data[key.toString()].push({
contract : contractName,
address : networks[key].address});
} else {
data[key.toString()] = [{
contract : contractName,
address : networks[key].address}];
}
});
}
});
const nonSingletonsBytecodes = [];
Object.keys(contracts.contracts).forEach(submodule => {
if (submodule !== 'singletons') {
Object.values(contracts.contracts[submodule]).forEach(({ bytecode, abi }) => {
nonSingletonsBytecodes.push(bytecode || JSON.stringify(abi));
});
}
});
const nonSingletonsHash = sha256(nonSingletonsBytecodes.join(''));
const singletonsHash = sha256(singletonAddresses.join(''));
Object.keys(contracts.contracts).forEach(key => {
contracts.contracts[key]['NonSingletonsHash'] = nonSingletonsHash;
contracts.contracts[key]['SingletonsHash'] = singletonsHash;
});
let obj = {
'NonSingletonsHash': nonSingletonsHash,
'SingletonsHash': singletonsHash,
};
contracts.contracts.singletons = Object.assign(obj, contracts.contracts.singletons);
if(!fs.existsSync(path.join(twoKeyProtocolDir, 'contracts'))) {
fs.mkdirSync(path.join(twoKeyProtocolDir, 'contracts'));
}
Object.keys(contracts.contracts).forEach(file => {
fs.writeFileSync(path.join(twoKeyProtocolDir, 'contracts', `${file}.ts`), `export default ${util.inspect(contracts.contracts[file], {depth: 10})}`)
});
json = Object.assign(obj,json);
fs.writeFileSync(getContractsDeployedPath(), JSON.stringify(json, null, 2));
if (deployment) {
fs.copyFileSync(getContractsDeployedPath(),getContractsDeployedDistPath());
}
resolve(contracts);
} catch (err) {
reject(err);
}
});
}
});
const updateIPFSHashes = async(contracts) => {
const nonSingletonHash = contracts.contracts.singletons.NonSingletonsHash;
let versionsList = {};
let existingVersionHandlerFile = {};
// if(!process.argv.includes('--reset')) {
try {
existingVersionHandlerFile = JSON.parse(fs.readFileSync(getVersionsPath()), { encoding: 'utf8' });
} catch (e) {
console.log('VERSIONS ERROR', e);
}
const { TwoKeyVersionHandler: currentVersionHandler } = existingVersionHandlerFile;
if (currentVersionHandler) {
versionsList = JSON.parse((await ipfsGet(currentVersionHandler)).toString());
}
// }
versionsList[nonSingletonHash] = {};
const files = (await readdir(twoKeyProtocolSubmodulesDir)).filter(file => file.endsWith('.js'));
for (let i = 0, l = files.length; i < l; i++) {
const js = fs.readFileSync(path.join(twoKeyProtocolSubmodulesDir, files[i]), { encoding: 'utf-8' });
console.time('Upload');
const [{ hash }] = await ipfsAdd(js, deployment);
console.timeEnd('Upload');
versionsList[nonSingletonHash][files[i].replace('.js', '')] = hash;
}
const [{ hash: newTwoKeyVersionHandler }] = await ipfsAdd(JSON.stringify(versionsList), deployment);
fs.writeFileSync(getVersionsPath(), JSON.stringify({ TwoKeyVersionHandler: newTwoKeyVersionHandler }, null, 4));
fs.writeFileSync(getVersionsPath(false), JSON.stringify({ TwoKeyVersionHandler: newTwoKeyVersionHandler }, null, 4));
};
/**
*
* @param commitMessage
* @returns {Promise<void>}
*/
const commitAndPushContractsFolder = async(commitMessage) => {
const contractsStatus = await contractsGit.status();
await contractsGit.add(contractsStatus.files.map(item => item.path));
await contractsGit.commit(commitMessage);
await contractsGit.push('origin', contractsStatus.current);
};
/**
*
* @param commitMessage
* @returns {Promise<void>}
*/
const commitAndPush2KeyProtocolSrc = async(commitMessage) => {
const status = await twoKeyProtocolSrcGit.status();
await twoKeyProtocolSrcGit.add(status.files.map(item => item.path));
await twoKeyProtocolSrcGit.commit(commitMessage);
await twoKeyProtocolSrcGit.push('origin', status.current);
};
/**
*
* @param commitMessage
* @returns {Promise<void>}
*/
const commitAndPush2keyProtocolLibGit = async(commitMessage) => {
const status = await twoKeyProtocolLibGit.status();
await twoKeyProtocolLibGit.add(status.files.map(item => item.path));
await twoKeyProtocolLibGit.commit(commitMessage);
await twoKeyProtocolLibGit.push('origin', status.current);
};
/**
*
* @type {function(*)}
*/
const pushTagsToGithub = (async (npmVersionTag) => {
await contractsGit.addTag('v'+npmVersionTag.toString());
await contractsGit.pushTags('origin');
await twoKeyProtocolLibGit.pushTags('origin');
await twoKeyProtocolSrcGit.addTag('v'+npmVersionTag.toString());
await twoKeyProtocolSrcGit.pushTags('origin');
});
const checkIfContractIsPlasma = (contractName) => {
return !!contractName.includes('Plasma');
};
const getContractsFromFile = () => {
return JSON.parse(fs.readFileSync('./scripts/deployments/manualDeploy.json', 'utf8'));
};
/**
* TODO: Improve and change this script to handle following by hierarchy:
* - if deployment is protocol only or there're contracts to be deployed.
* - if protocol deployment, skip whole contracts process, and proceed to submodule generation
* - if contracts deployment, check if we're deploying contracts by getting diff between latest tags,
* - or we're deplpoying them by specifying in file which contracts we want to deploy
*
* TODO: Improvement for fetching contracts to be deployed:
* - if singletons, we need list of contracts
* - if campaign contracts, we only need flag with campaign type and if it has to be deployed
*
*/
async function deployUpgrade(networks) {
const l = networks.length;
await runTruffleCompile();
let deployment = {};
// Deploy from file
if(process.argv.includes('deploy-from-file')) {
let contracts = getContractsFromFile();
deployment.singletons = contracts.singletons;
deployment.tokenSell = contracts.tokenSell;
deployment.donation = contracts.donation;
deployment.ppc = contracts.ppc;
deployment.cpcNoRewards = contracts.cpcNoRewards;
} else {
[
deployment.singletons,
deployment.tokenSell,
deployment.donation,
deployment.ppc,
deployment.cpcNoRewards
] = await getDiffBetweenLatestTags();
}
for (let i = 0; i < l; i += 1) {
/* eslint-disable no-await-in-loop */
// Deploy the CPC contracts
if (process.argv.includes('plasma-participation')) {
await runDeployPlasmaParticipationsMining(networks[i]);
}
if (deployment.singletons.length > 0) {
for (let j = 0; j < deployment.singletons.length; j++) {
/* eslint-disable no-await-in-loop */
if (checkIfContractIsPlasma(deployment.singletons[j])) {
if (networks[i].includes('private') || networks[i].includes('plasma')) {
await runUpdateMigration(networks[i], deployment.singletons[j]);
}
} else {
if(networks[i].includes('public')) {
await runUpdateMigration(networks[i], deployment.singletons[j]);
}
}
}
}
if(deployment.tokenSell) {
if(networks[i].includes('public')) {
await runDeployTokenSellCampaignMigration(networks[i]);
}
}
if(deployment.donation) {
if(networks[i].includes('public')) {
await runDeployDonationCampaignMigration(networks[i]);
}
}
if(deployment.ppc) {
await runDeployCPCCampaignMigration(networks[i]);
}
if(deployment.cpcNoRewards) {
await runDeployCPCNoRewardsMigration(networks[i]);
}
/* eslint-enable no-await-in-loop */
}
await archiveBuild();
}
async function deploy() {
try {
deployment = true;
//Removing truffle build, the whole folder will be deleted
await rmDir(buildPath);
// Load tenderly configuration
await pullTenderlyConfiguration();
await contractsGit.fetch();
await contractsGit.submoduleUpdate();
let twoKeyProtocolStatus = await twoKeyProtocolLibGit.status();
if (twoKeyProtocolStatus.current !== contractsStatus.current) {
const twoKeyProtocolBranches = await twoKeyProtocolLibGit.branch();
if (twoKeyProtocolBranches.all.find(item => item.includes(contractsStatus.current))) {
await twoKeyProtocolLibGit.checkout(contractsStatus.current);
} else {
await twoKeyProtocolLibGit.checkoutLocalBranch(contractsStatus.current);
}
}
await contractsGit.submoduleUpdate();
await twoKeyProtocolLibGit.reset('hard');
const localChanges = contractsStatus.files.filter(item => !(item.path.includes('dist') || item.path.includes('contracts.ts') || item.path.includes('contracts_deployed')
|| (process.env.NODE_ENV === 'development' && item.path.includes(process.argv[1].split('/').pop()))));
if (contractsStatus.behind || localChanges.length) {
console.log('You have unsynced changes!', localChanges);
process.exit(1);
}
const local = process.argv[2].includes('local'); //If we're deploying to local network
const isHardReset = process.argv.includes('--reset');
//If reset rm -rf build folder and rm -rf tar.gz
if(isHardReset) {
await rmDir(buildPath);
await rmDir(buildArchPath);
} else {
await restoreFromArchive();
}
const networks = process.argv[2].split(',');
const network = networks.join('/');
const now = moment();
const commit = `SOL Deployed to ${network} ${now.format('lll')}`;
if(!process.argv.includes('protocol-only')) {
if(process.argv.includes('update')) {
await deployUpgrade(networks);
}
if(process.argv.includes('--reset')) {
await deployContracts(networks, true);
}
}
await archiveBuild();
const contracts = await generateSOLInterface();
await commitAndPushContractsFolder(`Contracts deployed to ${network} ${now.format('lll')}`);
await commitAndPush2KeyProtocolSrc(`Contracts deployed to ${network} ${now.format('lll')}`);
await buildSubmodules(contracts);
if (!local) {
await runProcess(path.join(__dirname, 'node_modules/.bin/webpack'));
}
contractsStatus = await contractsGit.status();
await commitAndPushContractsFolder(commit);
await commitAndPush2KeyProtocolSrc(commit);
await commitAndPush2keyProtocolLibGit(commit);
/**
* Npm patch & public
* Get version of package
* put the tag
*/
if(!local || process.env.FORCE_NPM) {
process.chdir(twoKeyProtocolDist);
const oldVersion = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
if (process.env.NODE_ENV === 'production') {
await runProcess('npm', ['version', 'patch']);
} else {
const { version } = JSON.parse(fs.readFileSync(path.join(twoKeyProtocolDist, 'package.json'), 'utf8'));
const versionArray = version.split('-')[0].split('.');
let patch;
let minor;
if(isHardReset) {
//Take the last one, that's patch
versionArray.pop();
// Reset it to be 0
patch = 0;
//Take the middle version and increment by 1
minor = parseInt(versionArray.pop(), 10) + 1;
//Push minor
versionArray.push(minor);
//Push new patch
versionArray.push(patch);
} else {
// In case this is just a patch, increment patch number
patch = parseInt(versionArray.pop(), 10) + 1;
// Push new patch
versionArray.push(patch);
}
const newVersion = `${versionArray.join('.')}-${contractsStatus.current}`;
await runProcess('npm', ['version', newVersion])
}
const json = JSON.parse(fs.readFileSync('package.json', 'utf8'));
let npmVersionTag = json.version;
process.chdir('../../');
// Push tags
await pushTagsToGithub(npmVersionTag);
process.chdir(twoKeyProtocolDist);
if (process.env.NODE_ENV === 'production' || contractsStatus.current === 'master') {
await runProcess('npm', ['publish']);
} else {
await runProcess('npm', ['publish', '--tag', contractsStatus.current]);
}
await twoKeyProtocolLibGit.push('origin', contractsStatus.current);
process.chdir('../../');
//Run slack message
await slack_message('v'+npmVersionTag.toString(), 'v'+oldVersion.toString(), branch_to_env[contractsStatus.current]);
if(!process.argv.includes('skip-tenderly')) {
// Add tenderly to CI/CD only in case there have been contracts updated.
await tenderlyPush(npmVersionTag);
}
// Generate the latest changelog for contracts repo
await generateChangelog();
// Go to 2key-protocol/src
process.chdir(twoKeyProtocolDir);
// Generate the changelog for this repository
await generateChangelog();
// Push final commit for the deployment
await commitAndPush2KeyProtocolSrc(`Version: ${npmVersionTag}. Deployment finished, changelog generated, submodules synced.`);
await commitAndPushContractsFolder(`Version: ${npmVersionTag}. Deployment finished, changelog generated, submodules synced.`);
} else {
process.exit(0);
}
} catch (e) {
if (e.output) {
e.output.forEach((buff) => {
if (buff && buff.toString) {
console.log(buff.toString('utf8'));
}
});
} else {
console.warn('Error', e);
}
await contractsGit.reset('hard');
}
}
const buildSubmodules = async(contracts) => {
await runProcess(path.join(__dirname, 'node_modules/.bin/webpack'), ['--config', './webpack.config.submodules.js', '--mode production', '--colors']);
await updateIPFSHashes(contracts);
};
const getMigrationsList = () => {
const migrationDir = path.join(__dirname, 'migrations');
return fs.readdirSync(migrationDir);
};
const runMigration = async (index, network, updateArchive) => {
await runProcess(
path.join(__dirname, 'node_modules/.bin/truffle'),
['migrate', '--f', index, '--to', index, '--network', network].concat(process.argv.slice(4))
);
if (updateArchive) {
await archiveBuild();
let deploy = {};
try {
deploy = JSON.parse(fs.readFileSync(path.join(__dirname, 'deploy.json'), { encoding: 'utf-8' }))
} catch (e) {
}
deploy[network] = index;
fs.writeFileSync(path.join(__dirname, 'deploy.json'), JSON.stringify(deploy), { encoding: 'utf-8' });
await restoreFromArchive();
}
};
const getStartMigration = (network) => {
let deploy = {};
if (process.argv.includes('--reset')) {
return 1;
}
try {
deploy = JSON.parse(fs.readFileSync(path.join(__dirname, 'deploy.json'), { encoding: 'utf-8' }))
} catch (e) {
}
return deploy[network] ? deploy[network] + 1 : 1;
};
const deployContracts = async (networks, updateArchive) => {
const l = networks.length;
for (let i = 0; i < l; i += 1) {
for (let j = getStartMigration(networks[i]), m = getMigrationsList().length; j <= m; j += 1) {
/* eslint-disable no-await-in-loop */
await runMigration(j, networks[i], updateArchive);
/* eslint-enable no-await-in-loop */
}
deployedTo[truffleNetworks[networks[i]].network_id.toString()] = truffleNetworks[networks[i]].network_id;
}
};
async function main() {
contractsStatus = await contractsGit.status(); // Fetching branch
const mode = process.argv[2];
switch (mode) {
case '--migrate':
try {
const networks = process.argv[3].split(',');
await deployContracts(networks, false);
await generateSOLInterface();
process.exit(0);
} catch (err) {
process.exit(1);
}
break;
case '--generate':
await generateSOLInterface();
process.exit(0);
break;
case '--archive':
await archiveBuild();
process.exit(0);
break;
case '--extract':
await restoreFromArchive();
process.exit(0);
break;
case '--submodules':
const contracts = await generateSOLInterface();
await buildSubmodules(contracts);
process.exit(0);
break;
case '--diff':
console.log(await getDiffBetweenLatestTags());
process.exit(0);
break;
case '--tenderly':
await pullTenderlyConfiguration();
process.exit(0);
break;
case '--tenderlyPush':
let tag = process.argv[3].toString();
await tenderlyPush(tag);
process.exit(0);
break;
default:
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const answer = await new Promise(resolve => {
rl.question("This will start deployment process. Proceed? [Y/N] ", answer => resolve(answer))
})
rl.close();
if(answer.toUpperCase() === 'Y' || answer.toUpperCase() === 'YES') {
await deploy();
process.exit(0);
} else if(answer.toUpperCase() === 'N' || answer.toUpperCase() === 'NO') {
console.log('Bye bye ππ')
} else {
console.log('Wrong answer! Bye bye ππ');
}
process.exit(0);
break;
}
}
main().catch((e) => {
console.log(e);
process.exit(1);
});