-
Notifications
You must be signed in to change notification settings - Fork 601
/
deploy.js
2685 lines (2406 loc) · 79.6 KB
/
deploy.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
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
'use strict';
const path = require('path');
const { gray, green, yellow, redBright, red } = require('chalk');
const w3utils = require('web3-utils');
const Deployer = require('../Deployer');
const NonceManager = require('../NonceManager');
const { loadCompiledFiles, getLatestSolTimestamp } = require('../solidity');
const checkAggregatorPrices = require('../check-aggregator-prices');
const pLimit = require('p-limit');
const {
ensureDeploymentPath,
ensureNetwork,
getDeploymentPathForNetwork,
loadAndCheckRequiredSources,
loadConnections,
confirmAction,
performTransactionalStep,
parameterNotice,
reportDeployedContracts,
} = require('../util');
const {
toBytes32,
fromBytes32,
constants: {
BUILD_FOLDER,
CONFIG_FILENAME,
CONTRACTS_FOLDER,
SYNTHS_FILENAME,
DEPLOYMENT_FILENAME,
ZERO_ADDRESS,
OVM_MAX_GAS_LIMIT,
inflationStartTimestampInSecs,
},
defaults,
nonUpgradeable,
} = require('../../../.');
const DEFAULTS = {
gasPrice: '1',
methodCallGasLimit: 250e3, // 250k
contractDeploymentGasLimit: 6.9e6, // TODO split out into separate limits for different contracts, Proxys, Synths, Synthetix
debtSnapshotMaxDeviation: 0.01, // a 1 percent deviation will trigger a snapshot
network: 'kovan',
buildPath: path.join(__dirname, '..', '..', '..', BUILD_FOLDER),
};
const deploy = async ({
addNewSynths,
gasPrice = DEFAULTS.gasPrice,
methodCallGasLimit = DEFAULTS.methodCallGasLimit,
contractDeploymentGasLimit = DEFAULTS.contractDeploymentGasLimit,
network = DEFAULTS.network,
buildPath = DEFAULTS.buildPath,
deploymentPath,
oracleExrates,
privateKey,
yes,
dryRun = false,
forceUpdateInverseSynthsOnTestnet = false,
useFork,
providerUrl,
useOvm,
freshDeploy,
manageNonces,
ignoreSafetyChecks,
ignoreCustomParameters,
concurrency,
specifyContracts,
} = {}) => {
ensureNetwork(network);
deploymentPath = deploymentPath || getDeploymentPathForNetwork({ network, useOvm });
ensureDeploymentPath(deploymentPath);
// OVM uses a gas price of 0 (unless --gas explicitely defined).
if (useOvm && gasPrice === DEFAULTS.gasPrice) {
gasPrice = w3utils.toBN('0');
}
const limitPromise = pLimit(concurrency);
const {
config,
params,
configFile,
synths,
deployment,
deploymentFile,
ownerActions,
ownerActionsFile,
feeds,
} = loadAndCheckRequiredSources({
deploymentPath,
network,
});
// Mark contracts for deployment specified via an argument
if (specifyContracts) {
// Ignore config.json
Object.keys(config).map(name => {
config[name].deploy = false;
});
// Add specified contracts
specifyContracts.split(',').map(name => {
if (!config[name]) {
config[name] = {
deploy: true,
};
} else {
config[name].deploy = true;
}
});
}
if (freshDeploy) {
deployment.targets = {};
deployment.sources = {};
}
if (!ignoreSafetyChecks) {
// Using Goerli without manageNonces?
if (network.toLowerCase() === 'goerli' && !useOvm && !manageNonces) {
throw new Error(`Deploying on Goerli needs to be performed with --manage-nonces.`);
}
// Cannot re-deploy legacy contracts
if (!freshDeploy) {
// Get list of contracts to be deployed
const contractsToDeploy = [];
Object.keys(config).map(contractName => {
if (config[contractName].deploy) {
contractsToDeploy.push(contractName);
}
});
// Check that no non-deployable is marked for deployment.
// Note: if nonDeployable = 'TokenState', this will match 'TokenStatesUSD'
nonUpgradeable.map(nonUpgradeableContract => {
contractsToDeploy.map(contractName => {
if (contractName.match(new RegExp(`^${nonUpgradeableContract}`, 'g'))) {
throw new Error(
`You are attempting to deploy a contract marked as non-upgradeable: ${contractName}. This action could result in loss of state. Please verify and use --ignore-safety-checks if you really know what you're doing.`
);
}
});
});
}
// Every transaction in Optimism needs to be below 9m gas, to ensure
// there are no deployment out of gas errors during fraud proofs.
if (useOvm) {
const maxOptimismGasLimit = OVM_MAX_GAS_LIMIT;
if (
contractDeploymentGasLimit > maxOptimismGasLimit ||
methodCallGasLimit > maxOptimismGasLimit
) {
throw new Error(
`Maximum transaction gas limit for OVM is ${maxOptimismGasLimit} gas, and specified contractDeploymentGasLimit and/or methodCallGasLimit are over such limit. Please make sure that these values are below the maximum gas limit to guarantee that fraud proofs can be done in L1.`
);
}
}
// Deploying on OVM and not using an OVM deployment path?
const lastPathItem = deploymentPath.split('/').pop();
const isOvmPath = lastPathItem.includes('ovm');
const deploymentPathMismatch = (useOvm && !isOvmPath) || (!useOvm && isOvmPath);
if (deploymentPathMismatch) {
if (useOvm) {
throw new Error(
`You are deploying to a non-ovm path ${deploymentPath}, while --use-ovm is true.`
);
} else {
throw new Error(
`You are deploying to an ovm path ${deploymentPath}, while --use-ovm is false.`
);
}
}
// Fresh deploy and deployment.json not empty?
if (freshDeploy && Object.keys(deployment.targets).length > 0 && network !== 'local') {
throw new Error(
`Cannot make a fresh deploy on ${deploymentPath} because a deployment has already been made on this path. If you intend to deploy a new instance, use a different path or delete the deployment files for this one.`
);
}
}
const standaloneFeeds = Object.values(feeds).filter(({ standalone }) => standalone);
const getDeployParameter = async name => {
const defaultParam = defaults[name];
if (ignoreCustomParameters) {
return defaultParam;
}
let effectiveValue = defaultParam;
const param = params[name];
if (param) {
if (!yes) {
try {
await confirmAction(
yellow(
`⚠⚠⚠ WARNING: Found an entry for ${name} in params.js. Specified value is ${param} and default is ${defaultParam}.` +
'\nDo you want to use the specified value (default otherwise)? (y/n) '
)
);
effectiveValue = param;
} catch (err) {
console.error(err);
}
} else {
// yes = true
effectiveValue = param;
}
}
if (effectiveValue !== defaultParam) {
console.log(
yellow(
`PARAMETER OVERRIDE: Overriding default ${name} with ${effectiveValue}, specified in params.json.`
)
);
}
return effectiveValue;
};
console.log(
gray('Checking all contracts not flagged for deployment have addresses in this network...')
);
const missingDeployments = Object.keys(config).filter(name => {
return !config[name].deploy && (!deployment.targets[name] || !deployment.targets[name].address);
});
if (missingDeployments.length) {
throw Error(
`Cannot use existing contracts for deployment as addresses not found for the following contracts on ${network}:\n` +
missingDeployments.join('\n') +
'\n' +
gray(`Used: ${deploymentFile} as source`)
);
}
console.log(gray('Loading the compiled contracts locally...'));
const { earliestCompiledTimestamp, compiled } = loadCompiledFiles({ buildPath });
// now get the latest time a Solidity file was edited
const latestSolTimestamp = getLatestSolTimestamp(CONTRACTS_FOLDER);
const {
providerUrl: envProviderUrl,
privateKey: envPrivateKey,
etherscanLinkPrefix,
} = loadConnections({
network,
useFork,
});
if (!providerUrl) {
if (!envProviderUrl) {
throw new Error('Missing .env key of PROVIDER_URL. Please add and retry.');
}
providerUrl = envProviderUrl;
}
// if not specified, or in a local network, override the private key passed as a CLI option, with the one specified in .env
if (network !== 'local' && !privateKey) {
privateKey = envPrivateKey;
}
const nonceManager = new NonceManager({});
const deployer = new Deployer({
compiled,
contractDeploymentGasLimit,
config,
configFile,
deployment,
deploymentFile,
gasPrice,
methodCallGasLimit,
network,
privateKey,
providerUrl,
dryRun,
useOvm,
useFork,
ignoreSafetyChecks,
nonceManager: manageNonces ? nonceManager : undefined,
});
const { account } = deployer;
nonceManager.web3 = deployer.web3;
nonceManager.account = account;
let currentSynthetixSupply;
let oldExrates;
let currentLastMintEvent;
let currentWeekOfInflation;
let systemSuspended = false;
let systemSuspendedReason;
try {
const oldSynthetix = deployer.getExistingContract({ contract: 'Synthetix' });
currentSynthetixSupply = await oldSynthetix.methods.totalSupply().call();
// inflationSupplyToDate = total supply - 100m
const inflationSupplyToDate = w3utils
.toBN(currentSynthetixSupply)
.sub(w3utils.toBN(w3utils.toWei((100e6).toString())));
// current weekly inflation 75m / 52
const weeklyInflation = w3utils.toBN(w3utils.toWei((75e6 / 52).toString()));
currentWeekOfInflation = inflationSupplyToDate.div(weeklyInflation);
// Check result is > 0 else set to 0 for currentWeek
currentWeekOfInflation = currentWeekOfInflation.gt(w3utils.toBN('0'))
? currentWeekOfInflation.toNumber()
: 0;
// Calculate lastMintEvent as Inflation start date + number of weeks issued * secs in weeks
const mintingBuffer = 86400;
const secondsInWeek = 604800;
const inflationStartDate = inflationStartTimestampInSecs;
currentLastMintEvent =
inflationStartDate + currentWeekOfInflation * secondsInWeek + mintingBuffer;
} catch (err) {
if (freshDeploy) {
currentSynthetixSupply = await getDeployParameter('INITIAL_ISSUANCE');
currentWeekOfInflation = 0;
currentLastMintEvent = 0;
} else {
console.error(
red(
'Cannot connect to existing Synthetix contract. Please double check the deploymentPath is correct for the network allocated'
)
);
process.exitCode = 1;
return;
}
}
try {
oldExrates = deployer.getExistingContract({ contract: 'ExchangeRates' });
if (!oracleExrates) {
oracleExrates = await oldExrates.methods.oracle().call();
}
} catch (err) {
if (freshDeploy) {
oracleExrates = oracleExrates || account;
oldExrates = undefined; // unset to signify that a fresh one will be deployed
} else {
console.error(
red(
'Cannot connect to existing ExchangeRates contract. Please double check the deploymentPath is correct for the network allocated'
)
);
process.exitCode = 1;
return;
}
}
try {
const oldSystemStatus = deployer.getExistingContract({ contract: 'SystemStatus' });
const systemSuspensionStatus = await oldSystemStatus.methods.systemSuspension().call();
systemSuspended = systemSuspensionStatus.suspended;
systemSuspendedReason = systemSuspensionStatus.reason;
} catch (err) {
if (!freshDeploy) {
console.error(
red(
'Cannot connect to existing SystemStatus contract. Please double check the deploymentPath is correct for the network allocated'
)
);
process.exitCode = 1;
return;
}
}
for (const address of [account, oracleExrates]) {
if (!w3utils.isAddress(address)) {
console.error(red('Invalid address detected (please check your inputs):', address));
process.exitCode = 1;
return;
}
}
const newSynthsToAdd = synths
.filter(({ name }) => !config[`Synth${name}`])
.map(({ name }) => name);
let aggregatedPriceResults = 'N/A';
if (oldExrates && network !== 'local') {
const padding = '\n\t\t\t\t';
const aggResults = await checkAggregatorPrices({
network,
useOvm,
providerUrl,
synths,
oldExrates,
standaloneFeeds,
});
aggregatedPriceResults = padding + aggResults.join(padding);
}
const deployerBalance = parseInt(
w3utils.fromWei(await deployer.web3.eth.getBalance(account), 'ether'),
10
);
if (useFork) {
// Make sure the pwned account has ETH when using a fork
const accounts = await deployer.web3.eth.getAccounts();
await deployer.web3.eth.sendTransaction({
from: accounts[0],
to: account,
value: w3utils.toWei('10', 'ether'),
});
} else if (deployerBalance < 5) {
console.log(
yellow(`⚠ WARNING: Deployer account balance could be too low: ${deployerBalance} ETH`)
);
}
let ovmDeploymentPathWarning = false;
// OVM targets must end with '-ovm'.
if (useOvm) {
const lastPathElement = path.basename(deploymentPath);
ovmDeploymentPathWarning = !lastPathElement.includes('ovm');
}
parameterNotice({
'Dry Run': dryRun ? green('true') : yellow('⚠ NO'),
'Using a fork': useFork ? green('true') : yellow('⚠ NO'),
Concurrency: `${concurrency} max parallel calls`,
Network: network,
'OVM?': useOvm
? ovmDeploymentPathWarning
? red('⚠ No -ovm folder suffix!')
: green('true')
: 'false',
'Gas price to use': `${gasPrice} GWEI`,
'Method call gas limit': `${methodCallGasLimit} gas`,
'Contract deployment gas limit': `${contractDeploymentGasLimit} gas`,
'Deployment Path': new RegExp(network, 'gi').test(deploymentPath)
? deploymentPath
: yellow('⚠⚠⚠ cant find network name in path. Please double check this! ') + deploymentPath,
Provider: providerUrl,
'Local build last modified': `${new Date(earliestCompiledTimestamp)} ${yellow(
((new Date().getTime() - earliestCompiledTimestamp) / 60000).toFixed(2) + ' mins ago'
)}`,
'Last Solidity update':
new Date(latestSolTimestamp) +
(latestSolTimestamp > earliestCompiledTimestamp
? yellow(' ⚠⚠⚠ this is later than the last build! Is this intentional?')
: green(' ✅')),
'Add any new synths found?': addNewSynths
? green('✅ YES\n\t\t\t\t') + newSynthsToAdd.join(', ')
: yellow('⚠ NO'),
'Deployer account:': account,
'Synthetix totalSupply': `${Math.round(w3utils.fromWei(currentSynthetixSupply) / 1e6)}m`,
'ExchangeRates Oracle': oracleExrates,
'Last Mint Event': `${currentLastMintEvent} (${new Date(currentLastMintEvent * 1000)})`,
'Current Weeks Of Inflation': currentWeekOfInflation,
'Aggregated Prices': aggregatedPriceResults,
'System Suspended': systemSuspended
? green(' ✅', 'Reason:', systemSuspendedReason)
: yellow('⚠ NO'),
});
if (!yes) {
try {
await confirmAction(
yellow(
`⚠⚠⚠ WARNING: This action will deploy the following contracts to ${network}:\n${Object.entries(
config
)
.filter(([, { deploy }]) => deploy)
.map(([contract]) => contract)
.join(', ')}` + `\nIt will also set proxy targets and add synths to Synthetix.\n`
) +
gray('-'.repeat(50)) +
'\nDo you want to continue? (y/n) '
);
} catch (err) {
console.log(gray('Operation cancelled'));
return;
}
}
console.log(
gray(`Starting deployment to ${network.toUpperCase()}${useFork ? ' (fork)' : ''}...`)
);
const runStep = async opts =>
performTransactionalStep({
gasLimit: methodCallGasLimit, // allow overriding of gasLimit
...opts,
account,
gasPrice,
etherscanLinkPrefix,
ownerActions,
ownerActionsFile,
dryRun,
nonceManager: manageNonces ? nonceManager : undefined,
});
console.log(gray(`\n------ DEPLOY LIBRARIES ------\n`));
await deployer.deployContract({
name: 'SafeDecimalMath',
});
await deployer.deployContract({
name: 'Math',
});
console.log(gray(`\n------ DEPLOY CORE PROTOCOL ------\n`));
const addressOf = c => (c ? c.options.address : '');
const addressResolver = await deployer.deployContract({
name: 'AddressResolver',
args: [account],
});
const readProxyForResolver = await deployer.deployContract({
name: 'ReadProxyAddressResolver',
source: 'ReadProxy',
args: [account],
});
if (addressResolver && readProxyForResolver) {
await runStep({
contract: 'ReadProxyAddressResolver',
target: readProxyForResolver,
read: 'target',
expected: input => input === addressOf(addressResolver),
write: 'setTarget',
writeArg: addressOf(addressResolver),
});
}
await deployer.deployContract({
name: 'FlexibleStorage',
deps: ['ReadProxyAddressResolver'],
args: [addressOf(readProxyForResolver)],
});
const systemSettings = await deployer.deployContract({
name: 'SystemSettings',
args: [account, addressOf(readProxyForResolver)],
});
const systemStatus = await deployer.deployContract({
name: 'SystemStatus',
args: [account],
});
if (network !== 'mainnet' && systemStatus) {
// On testnet, give the deployer the rights to update status
await runStep({
contract: 'SystemStatus',
target: systemStatus,
read: 'accessControl',
readArg: [toBytes32('System'), account],
expected: ({ canSuspend } = {}) => canSuspend,
write: 'updateAccessControls',
writeArg: [
['System', 'Issuance', 'Exchange', 'SynthExchange', 'Synth'].map(toBytes32),
[account, account, account, account, account],
[true, true, true, true, true],
[true, true, true, true, true],
],
});
}
const exchangeRates = await deployer.deployContract({
name: 'ExchangeRates',
source: useOvm ? 'ExchangeRatesWithoutInvPricing' : 'ExchangeRates',
args: [account, oracleExrates, addressOf(readProxyForResolver), [], []],
});
const rewardEscrow = await deployer.deployContract({
name: 'RewardEscrow',
args: [account, ZERO_ADDRESS, ZERO_ADDRESS],
});
const rewardEscrowV2 = await deployer.deployContract({
name: 'RewardEscrowV2',
source: useOvm ? 'ImportableRewardEscrowV2' : 'RewardEscrowV2',
args: [account, addressOf(readProxyForResolver)],
deps: ['AddressResolver'],
});
const synthetixEscrow = await deployer.deployContract({
name: 'SynthetixEscrow',
args: [account, ZERO_ADDRESS],
});
const synthetixState = await deployer.deployContract({
name: 'SynthetixState',
source: useOvm ? 'SynthetixStateWithLimitedSetup' : 'SynthetixState',
args: [account, account],
});
const proxyFeePool = await deployer.deployContract({
name: 'ProxyFeePool',
source: 'Proxy',
args: [account],
});
const delegateApprovalsEternalStorage = await deployer.deployContract({
name: 'DelegateApprovalsEternalStorage',
source: 'EternalStorage',
args: [account, ZERO_ADDRESS],
});
const delegateApprovals = await deployer.deployContract({
name: 'DelegateApprovals',
args: [account, addressOf(delegateApprovalsEternalStorage)],
});
if (delegateApprovals && delegateApprovalsEternalStorage) {
await runStep({
contract: 'EternalStorage',
target: delegateApprovalsEternalStorage,
read: 'associatedContract',
expected: input => input === addressOf(delegateApprovals),
write: 'setAssociatedContract',
writeArg: addressOf(delegateApprovals),
});
}
const liquidations = await deployer.deployContract({
name: 'Liquidations',
args: [account, addressOf(readProxyForResolver)],
});
const eternalStorageLiquidations = await deployer.deployContract({
name: 'EternalStorageLiquidations',
source: 'EternalStorage',
args: [account, addressOf(liquidations)],
});
if (liquidations && eternalStorageLiquidations) {
await runStep({
contract: 'EternalStorageLiquidations',
target: eternalStorageLiquidations,
read: 'associatedContract',
expected: input => input === addressOf(liquidations),
write: 'setAssociatedContract',
writeArg: addressOf(liquidations),
});
}
const feePoolEternalStorage = await deployer.deployContract({
name: 'FeePoolEternalStorage',
args: [account, ZERO_ADDRESS],
});
const feePool = await deployer.deployContract({
name: 'FeePool',
deps: ['ProxyFeePool', 'AddressResolver'],
args: [addressOf(proxyFeePool), account, addressOf(readProxyForResolver)],
});
if (proxyFeePool && feePool) {
await runStep({
contract: 'ProxyFeePool',
target: proxyFeePool,
read: 'target',
expected: input => input === addressOf(feePool),
write: 'setTarget',
writeArg: addressOf(feePool),
});
}
if (feePoolEternalStorage && feePool) {
await runStep({
contract: 'FeePoolEternalStorage',
target: feePoolEternalStorage,
read: 'associatedContract',
expected: input => input === addressOf(feePool),
write: 'setAssociatedContract',
writeArg: addressOf(feePool),
});
}
const feePoolState = await deployer.deployContract({
name: 'FeePoolState',
deps: ['FeePool'],
args: [account, addressOf(feePool)],
});
if (feePool && feePoolState) {
// Rewire feePoolState if there is a feePool upgrade
await runStep({
contract: 'FeePoolState',
target: feePoolState,
read: 'feePool',
expected: input => input === addressOf(feePool),
write: 'setFeePool',
writeArg: addressOf(feePool),
});
}
const rewardsDistribution = await deployer.deployContract({
name: 'RewardsDistribution',
deps: useOvm ? ['RewardEscrowV2', 'ProxyFeePool'] : ['RewardEscrowV2', 'ProxyFeePool'],
args: [
account, // owner
ZERO_ADDRESS, // authority (synthetix)
ZERO_ADDRESS, // Synthetix Proxy
addressOf(rewardEscrowV2),
addressOf(proxyFeePool),
],
});
// New Synthetix proxy.
const proxyERC20Synthetix = await deployer.deployContract({
name: 'ProxyERC20',
args: [account],
});
const tokenStateSynthetix = await deployer.deployContract({
name: 'TokenStateSynthetix',
source: 'TokenState',
args: [account, account],
});
const synthetix = await deployer.deployContract({
name: 'Synthetix',
source: useOvm ? 'MintableSynthetix' : 'Synthetix',
deps: ['ProxyERC20', 'TokenStateSynthetix', 'AddressResolver'],
args: [
addressOf(proxyERC20Synthetix),
addressOf(tokenStateSynthetix),
account,
currentSynthetixSupply,
addressOf(readProxyForResolver),
],
});
if (synthetix && proxyERC20Synthetix) {
await runStep({
contract: 'ProxyERC20',
target: proxyERC20Synthetix,
read: 'target',
expected: input => input === addressOf(synthetix),
write: 'setTarget',
writeArg: addressOf(synthetix),
});
await runStep({
contract: 'Synthetix',
target: synthetix,
read: 'proxy',
expected: input => input === addressOf(proxyERC20Synthetix),
write: 'setProxy',
writeArg: addressOf(proxyERC20Synthetix),
});
}
// Old Synthetix proxy based off Proxy.sol: this has been deprecated.
// To be removed after May 30, 2020:
// https://docs.synthetix.io/integrations/guide/#proxy-deprecation
const proxySynthetix = await deployer.deployContract({
name: 'ProxySynthetix',
source: 'Proxy',
args: [account],
});
if (proxySynthetix && synthetix) {
await runStep({
contract: 'ProxySynthetix',
target: proxySynthetix,
read: 'target',
expected: input => input === addressOf(synthetix),
write: 'setTarget',
writeArg: addressOf(synthetix),
});
}
const debtCache = await deployer.deployContract({
name: 'DebtCache',
deps: ['AddressResolver'],
args: [account, addressOf(readProxyForResolver)],
});
let exchanger;
if (useOvm) {
exchanger = await deployer.deployContract({
name: 'Exchanger',
source: 'Exchanger',
deps: ['AddressResolver'],
args: [account, addressOf(readProxyForResolver)],
});
} else {
exchanger = await deployer.deployContract({
name: 'Exchanger',
source: 'ExchangerWithVirtualSynth',
deps: ['AddressResolver'],
args: [account, addressOf(readProxyForResolver)],
});
await deployer.deployContract({
name: 'VirtualSynthMastercopy',
});
}
const exchangeState = await deployer.deployContract({
name: 'ExchangeState',
deps: ['Exchanger'],
args: [account, addressOf(exchanger)],
});
if (exchanger && exchangeState) {
// The exchangeState contract has Exchanger as it's associated contract
await runStep({
contract: 'ExchangeState',
target: exchangeState,
read: 'associatedContract',
expected: input => input === exchanger.options.address,
write: 'setAssociatedContract',
writeArg: exchanger.options.address,
});
}
if (exchanger && systemStatus) {
// SIP-65: ensure Exchanger can suspend synths if price spikes occur
await runStep({
contract: 'SystemStatus',
target: systemStatus,
read: 'accessControl',
readArg: [toBytes32('Synth'), addressOf(exchanger)],
expected: ({ canSuspend } = {}) => canSuspend,
write: 'updateAccessControl',
writeArg: [toBytes32('Synth'), addressOf(exchanger), true, false],
});
}
// only reset token state if redeploying
if (tokenStateSynthetix && config['TokenStateSynthetix'].deploy) {
const initialIssuance = await getDeployParameter('INITIAL_ISSUANCE');
await runStep({
contract: 'TokenStateSynthetix',
target: tokenStateSynthetix,
read: 'balanceOf',
readArg: account,
expected: input => input === initialIssuance,
write: 'setBalanceOf',
writeArg: [account, initialIssuance],
});
}
if (tokenStateSynthetix && synthetix) {
await runStep({
contract: 'TokenStateSynthetix',
target: tokenStateSynthetix,
read: 'associatedContract',
expected: input => input === addressOf(synthetix),
write: 'setAssociatedContract',
writeArg: addressOf(synthetix),
});
}
const issuer = await deployer.deployContract({
name: 'Issuer',
source: useOvm ? 'IssuerWithoutLiquidations' : 'Issuer',
deps: ['AddressResolver'],
args: [account, addressOf(readProxyForResolver)],
});
const issuerAddress = addressOf(issuer);
await deployer.deployContract({
name: 'TradingRewards',
deps: ['AddressResolver', 'Exchanger'],
args: [account, account, addressOf(readProxyForResolver)],
});
if (synthetixState && issuer) {
// The SynthetixState contract has Issuer as it's associated contract (after v2.19 refactor)
await runStep({
contract: 'SynthetixState',
target: synthetixState,
read: 'associatedContract',
expected: input => input === issuerAddress,
write: 'setAssociatedContract',
writeArg: issuerAddress,
});
}
if (useOvm && synthetixState && feePool) {
// The SynthetixStateLimitedSetup) contract has FeePool to appendAccountIssuanceRecord
await runStep({
contract: 'SynthetixState',
target: synthetixState,
read: 'feePool',
expected: input => input === addressOf(feePool),
write: 'setFeePool',
writeArg: addressOf(feePool),
});
}
if (synthetixEscrow) {
await deployer.deployContract({
name: 'EscrowChecker',
deps: ['SynthetixEscrow'],
args: [addressOf(synthetixEscrow)],
});
}
if (rewardEscrow && synthetix) {
await runStep({
contract: 'RewardEscrow',
target: rewardEscrow,
read: 'synthetix',
expected: input => input === addressOf(synthetix),
write: 'setSynthetix',
writeArg: addressOf(synthetix),
});
}
if (rewardEscrow && feePool) {
await runStep({
contract: 'RewardEscrow',
target: rewardEscrow,
read: 'feePool',
expected: input => input === addressOf(feePool),
write: 'setFeePool',
writeArg: addressOf(feePool),
});
}
if (!useOvm) {
const supplySchedule = await deployer.deployContract({
name: 'SupplySchedule',
args: [account, currentLastMintEvent, currentWeekOfInflation],
});
if (supplySchedule && synthetix) {
await runStep({
contract: 'SupplySchedule',
target: supplySchedule,
read: 'synthetixProxy',
expected: input => input === addressOf(proxySynthetix),
write: 'setSynthetixProxy',
writeArg: addressOf(proxySynthetix),
});
}
}
if (synthetix && rewardsDistribution) {
await runStep({
contract: 'RewardsDistribution',
target: rewardsDistribution,
read: 'authority',
expected: input => input === addressOf(synthetix),
write: 'setAuthority',
writeArg: addressOf(synthetix),
});
await runStep({
contract: 'RewardsDistribution',
target: rewardsDistribution,
read: 'synthetixProxy',
expected: input => input === addressOf(proxyERC20Synthetix),
write: 'setSynthetixProxy',
writeArg: addressOf(proxyERC20Synthetix),
});
}
// RewardEscrow on RewardsDistribution should be set to new RewardEscrowV2
if (rewardEscrowV2 && rewardsDistribution) {
await runStep({
contract: 'RewardsDistribution',
target: rewardsDistribution,
read: 'rewardEscrow',
expected: input => input === addressOf(rewardEscrowV2),
write: 'setRewardEscrow',
writeArg: addressOf(rewardEscrowV2),
});
}
// ----------------
// Setting proxyERC20 Synthetix for synthetixEscrow
// ----------------
// Skip setting unless redeploying either of these,
if (config['Synthetix'].deploy || config['SynthetixEscrow'].deploy) {
// Note: currently on mainnet SynthetixEscrow.methods.synthetix() does NOT exist
// it is "havven" and the ABI we have here is not sufficient
if (network === 'mainnet' && !useOvm) {