-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathindex.ts
718 lines (623 loc) · 21.1 KB
/
index.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
import "@nomicfoundation/hardhat-verify";
import { Etherscan } from "@nomicfoundation/hardhat-verify/etherscan";
import {
DeploymentParameters,
IgnitionError,
StatusResult,
} from "@nomicfoundation/ignition-core";
import debug from "debug";
import {
ensureDir,
pathExists,
readFile,
readdirSync,
rm,
writeJSON,
} from "fs-extra";
import { extendConfig, extendEnvironment, scope } from "hardhat/config";
import { NomicLabsHardhatPluginError } from "hardhat/plugins";
import path from "path";
import "./type-extensions";
import { calculateDeploymentStatusDisplay } from "./ui/helpers/calculate-deployment-status-display";
import { bigintReviver } from "./utils/bigintReviver";
import { getApiKeyAndUrls } from "./utils/getApiKeyAndUrls";
import { resolveDeploymentId } from "./utils/resolve-deployment-id";
import { shouldBeHardhatPluginError } from "./utils/shouldBeHardhatPluginError";
import { verifyEtherscanContract } from "./utils/verifyEtherscanContract";
/* ignition config defaults */
const IGNITION_DIR = "ignition";
const ignitionScope = scope(
"ignition",
"Deploy your smart contracts using Hardhat Ignition"
);
const log = debug("hardhat:ignition");
extendConfig((config, userConfig) => {
/* setup path configs */
const userPathsConfig = userConfig.paths ?? {};
config.paths = {
...config.paths,
ignition: path.resolve(
config.paths.root,
userPathsConfig.ignition ?? IGNITION_DIR
),
};
Object.keys(config.networks).forEach((networkName) => {
const userNetworkConfig = userConfig.networks?.[networkName] ?? {};
config.networks[networkName].ignition = {
maxFeePerGasLimit: userNetworkConfig.ignition?.maxFeePerGasLimit,
maxPriorityFeePerGas: userNetworkConfig.ignition?.maxPriorityFeePerGas,
};
});
/* setup core configs */
const userIgnitionConfig = userConfig.ignition ?? {};
config.ignition = userIgnitionConfig;
});
/**
* Add an `ignition` stub to throw
*/
extendEnvironment((hre) => {
if ((hre as any).ignition === undefined) {
(hre as any).ignition = {
type: "stub",
deploy: () => {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
"Please install either `@nomicfoundation/hardhat-ignition-viem` or `@nomicfoundation/hardhat-ignition-ethers` to use Ignition in your Hardhat tests"
);
},
};
}
});
ignitionScope
.task("deploy")
.addPositionalParam("modulePath", "The path to the module file to deploy")
.addOptionalParam(
"parameters",
"A relative path to a JSON file to use for the module parameters"
)
.addOptionalParam("deploymentId", "Set the id of the deployment")
.addOptionalParam(
"defaultSender",
"Set the default sender for the deployment"
)
.addOptionalParam("strategy", "Set the deployment strategy to use", "basic")
.addFlag("reset", "Wipes the existing deployment state before deploying")
.addFlag("verify", "Verify the deployment on Etherscan")
.setDescription("Deploy a module to the specified network")
.setAction(
async (
{
modulePath,
parameters: parametersInput,
deploymentId: givenDeploymentId,
defaultSender,
reset,
verify,
strategy: strategyName,
}: {
modulePath: string;
parameters?: string;
deploymentId: string | undefined;
defaultSender: string | undefined;
reset: boolean;
verify: boolean;
strategy: string;
},
hre
) => {
const { default: chalk } = await import("chalk");
const { default: Prompt } = await import("prompts");
const { deploy } = await import("@nomicfoundation/ignition-core");
const { HardhatArtifactResolver } = await import(
"./hardhat-artifact-resolver"
);
const { loadModule } = await import("./utils/load-module");
const { PrettyEventHandler } = await import("./ui/pretty-event-handler");
if (verify) {
if (
hre.config.etherscan === undefined ||
hre.config.etherscan.apiKey === undefined ||
hre.config.etherscan.apiKey === ""
) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
"No etherscan API key configured"
);
}
}
const chainId = Number(
await hre.network.provider.request({
method: "eth_chainId",
})
);
const deploymentId = resolveDeploymentId(givenDeploymentId, chainId);
const deploymentDir =
hre.network.name === "hardhat"
? undefined
: path.join(hre.config.paths.ignition, "deployments", deploymentId);
if (chainId !== 31337) {
if (process.env.HARDHAT_IGNITION_CONFIRM_DEPLOYMENT === undefined) {
const prompt = await Prompt({
type: "confirm",
name: "networkConfirmation",
message: `Confirm deploy to network ${hre.network.name} (${chainId})?`,
initial: false,
});
if (prompt.networkConfirmation !== true) {
console.log("Deploy cancelled");
return;
}
}
if (reset && process.env.HARDHAT_IGNITION_CONFIRM_RESET === undefined) {
const resetPrompt = await Prompt({
type: "confirm",
name: "resetConfirmation",
message: `Confirm reset of deployment "${deploymentId}" on chain ${chainId}?`,
initial: false,
});
if (resetPrompt.resetConfirmation !== true) {
console.log("Deploy cancelled");
return;
}
}
} else if (deploymentDir !== undefined) {
// since we're on hardhat-network
// check for a previous run of this deploymentId and compare instanceIds
// if they're different, wipe deployment state
const instanceFilePath = path.join(
hre.config.paths.cache,
".hardhat-network-instances.json"
);
const instanceFileExists = await pathExists(instanceFilePath);
const instanceFile: {
[deploymentId: string]: string;
} = instanceFileExists ? require(instanceFilePath) : {};
const metadata = (await hre.network.provider.request({
method: "hardhat_metadata",
})) as { instanceId: string };
if (instanceFile[deploymentId] !== metadata.instanceId) {
await rm(deploymentDir, { recursive: true, force: true });
}
// save current instanceId to instanceFile for future runs
instanceFile[deploymentId] = metadata.instanceId;
await ensureDir(path.dirname(instanceFilePath));
await writeJSON(instanceFilePath, instanceFile, { spaces: 2 });
}
if (reset) {
if (deploymentDir === undefined) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
"Deploy cancelled: Cannot reset deployment on ephemeral Hardhat network"
);
} else {
await rm(deploymentDir, { recursive: true, force: true });
}
}
if (strategyName !== "basic" && strategyName !== "create2") {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
"Invalid strategy name, must be either 'basic' or 'create2'"
);
}
await hre.run("compile", { quiet: true });
const userModule = loadModule(hre.config.paths.ignition, modulePath);
if (userModule === undefined) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
"No Ignition modules found"
);
}
let parameters: DeploymentParameters | undefined;
if (parametersInput === undefined) {
parameters = await resolveParametersFromModuleName(
userModule.id,
hre.config.paths.ignition
);
} else if (parametersInput.endsWith(".json")) {
parameters = await resolveParametersFromFileName(parametersInput);
} else {
parameters = resolveParametersString(parametersInput);
}
const accounts = (await hre.network.provider.request({
method: "eth_accounts",
})) as string[];
const artifactResolver = new HardhatArtifactResolver(hre);
const executionEventListener = new PrettyEventHandler();
const strategyConfig = hre.config.ignition.strategyConfig?.[strategyName];
try {
const ledgerConnectionStart = () =>
executionEventListener.ledgerConnectionStart();
const ledgerConnectionSuccess = () =>
executionEventListener.ledgerConnectionSuccess();
const ledgerConnectionFailure = () =>
executionEventListener.ledgerConnectionFailure();
const ledgerConfirmationStart = () =>
executionEventListener.ledgerConfirmationStart();
const ledgerConfirmationSuccess = () =>
executionEventListener.ledgerConfirmationSuccess();
const ledgerConfirmationFailure = () =>
executionEventListener.ledgerConfirmationFailure();
try {
await hre.network.provider.send("hardhat_setLedgerOutputEnabled", [
false,
]);
hre.network.provider.once("connection_start", ledgerConnectionStart);
hre.network.provider.once(
"connection_success",
ledgerConnectionSuccess
);
hre.network.provider.once(
"connection_failure",
ledgerConnectionFailure
);
hre.network.provider.on(
"confirmation_start",
ledgerConfirmationStart
);
hre.network.provider.on(
"confirmation_success",
ledgerConfirmationSuccess
);
hre.network.provider.on(
"confirmation_failure",
ledgerConfirmationFailure
);
} catch (error) {
log(error);
}
const result = await deploy({
config: hre.config.ignition,
provider: hre.network.provider,
executionEventListener,
artifactResolver,
deploymentDir,
ignitionModule: userModule,
deploymentParameters: parameters ?? {},
accounts,
defaultSender,
strategy: strategyName,
strategyConfig,
maxFeePerGasLimit:
hre.config.networks[hre.network.name]?.ignition.maxFeePerGasLimit,
maxPriorityFeePerGas:
hre.config.networks[hre.network.name]?.ignition
.maxPriorityFeePerGas,
});
try {
await hre.network.provider.send("hardhat_setLedgerOutputEnabled", [
true,
]);
hre.network.provider.off("connection_start", ledgerConnectionStart);
hre.network.provider.off(
"connection_success",
ledgerConnectionSuccess
);
hre.network.provider.off(
"connection_failure",
ledgerConnectionFailure
);
hre.network.provider.off(
"confirmation_start",
ledgerConfirmationStart
);
hre.network.provider.off(
"confirmation_success",
ledgerConfirmationSuccess
);
hre.network.provider.off(
"confirmation_failure",
ledgerConfirmationFailure
);
} catch (error) {
log(error);
}
if (result.type === "SUCCESSFUL_DEPLOYMENT" && verify) {
console.log("");
console.log(chalk.bold("Verifying deployed contracts"));
console.log("");
await hre.run(
{ scope: "ignition", task: "verify" },
{ deploymentId }
);
}
if (result.type !== "SUCCESSFUL_DEPLOYMENT") {
process.exitCode = 1;
}
} catch (e) {
if (e instanceof IgnitionError && shouldBeHardhatPluginError(e)) {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
e.message,
e
);
}
throw e;
}
}
);
ignitionScope
.task("visualize")
.addFlag("noOpen", "Disables opening report in browser")
.addPositionalParam("modulePath", "The path to the module file to visualize")
.setDescription("Visualize a module as an HTML report")
.setAction(
async (
{ noOpen = false, modulePath }: { noOpen: boolean; modulePath: string },
hre
) => {
const { IgnitionModuleSerializer, batches } = await import(
"@nomicfoundation/ignition-core"
);
const { loadModule } = await import("./utils/load-module");
const { open } = await import("./utils/open");
const { writeVisualization } = await import(
"./visualization/write-visualization"
);
await hre.run("compile", { quiet: true });
const userModule = loadModule(hre.config.paths.ignition, modulePath);
if (userModule === undefined) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
"No Ignition modules found"
);
} else {
try {
const serializedIgnitionModule =
IgnitionModuleSerializer.serialize(userModule);
const batchInfo = batches(userModule);
await writeVisualization(
{ module: serializedIgnitionModule, batches: batchInfo },
{
cacheDir: hre.config.paths.cache,
}
);
} catch (e) {
if (e instanceof IgnitionError && shouldBeHardhatPluginError(e)) {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
e.message,
e
);
}
throw e;
}
}
if (!noOpen) {
const indexFile = path.join(
hre.config.paths.cache,
"visualization",
"index.html"
);
console.log(`Deployment visualization written to ${indexFile}`);
open(indexFile);
}
}
);
ignitionScope
.task("status")
.addPositionalParam("deploymentId", "The id of the deployment to show")
.setDescription("Show the current status of a deployment")
.setAction(async ({ deploymentId }: { deploymentId: string }, hre) => {
const { status } = await import("@nomicfoundation/ignition-core");
const { HardhatArtifactResolver } = await import(
"./hardhat-artifact-resolver"
);
const deploymentDir = path.join(
hre.config.paths.ignition,
"deployments",
deploymentId
);
const artifactResolver = new HardhatArtifactResolver(hre);
let statusResult: StatusResult;
try {
statusResult = await status(deploymentDir, artifactResolver);
} catch (e) {
if (e instanceof IgnitionError && shouldBeHardhatPluginError(e)) {
throw new NomicLabsHardhatPluginError("hardhat-ignition", e.message, e);
}
throw e;
}
console.log(calculateDeploymentStatusDisplay(deploymentId, statusResult));
});
ignitionScope
.task("deployments")
.setDescription("List all deployment IDs")
.setAction(async (_, hre) => {
const { listDeployments } = await import("@nomicfoundation/ignition-core");
const deploymentDir = path.join(hre.config.paths.ignition, "deployments");
try {
const deployments = await listDeployments(deploymentDir);
for (const deploymentId of deployments) {
console.log(deploymentId);
}
} catch (e) {
if (e instanceof IgnitionError && shouldBeHardhatPluginError(e)) {
throw new NomicLabsHardhatPluginError("hardhat-ignition", e.message, e);
}
throw e;
}
});
ignitionScope
.task("wipe")
.addPositionalParam(
"deploymentId",
"The id of the deployment with the future to wipe"
)
.addPositionalParam("futureId", "The id of the future to wipe")
.setDescription("Reset a deployment's future to allow rerunning")
.setAction(
async (
{ deploymentId, futureId }: { deploymentId: string; futureId: string },
hre
) => {
const { wipe } = await import("@nomicfoundation/ignition-core");
const { HardhatArtifactResolver } = await import(
"./hardhat-artifact-resolver"
);
const deploymentDir = path.join(
hre.config.paths.ignition,
"deployments",
deploymentId
);
try {
await wipe(deploymentDir, new HardhatArtifactResolver(hre), futureId);
} catch (e) {
if (e instanceof IgnitionError && shouldBeHardhatPluginError(e)) {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
e.message,
e
);
}
throw e;
}
console.log(`${futureId} state has been cleared`);
}
);
ignitionScope
.task("verify")
.addFlag(
"includeUnrelatedContracts",
"Include all compiled contracts in the verification"
)
.addPositionalParam("deploymentId", "The id of the deployment to verify")
.setDescription(
"Verify contracts from a deployment against the configured block explorers"
)
.setAction(
async (
{
deploymentId,
includeUnrelatedContracts = false,
}: { deploymentId: string; includeUnrelatedContracts: boolean },
hre
) => {
const { getVerificationInformation } = await import(
"@nomicfoundation/ignition-core"
);
const deploymentDir = path.join(
hre.config.paths.ignition,
"deployments",
deploymentId
);
if (
hre.config.etherscan === undefined ||
hre.config.etherscan.apiKey === undefined ||
hre.config.etherscan.apiKey === ""
) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
"No etherscan API key configured"
);
}
try {
for await (const [
chainConfig,
contractInfo,
] of getVerificationInformation(
deploymentDir,
hre.config.etherscan.customChains,
includeUnrelatedContracts
)) {
const apiKeyAndUrls = getApiKeyAndUrls(
hre.config.etherscan.apiKey,
chainConfig
);
const instance = new Etherscan(...apiKeyAndUrls);
console.log(
`Verifying contract "${contractInfo.name}" for network ${chainConfig.network}...`
);
const result = await verifyEtherscanContract(instance, contractInfo);
if (result.type === "success") {
console.log(
`Successfully verified contract "${contractInfo.name}" for network ${chainConfig.network}:\n - ${result.contractURL}`
);
console.log("");
} else {
if (/already verified/gi.test(result.reason.message)) {
const contractURL = instance.getContractUrl(contractInfo.address);
console.log(
`Contract ${contractInfo.name} already verified on network ${chainConfig.network}:\n - ${contractURL}`
);
console.log("");
continue;
} else {
if (!includeUnrelatedContracts) {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
`Verification failed. Please run \`hardhat ignition verify ${deploymentId} --include-unrelated-contracts\` to attempt verifying all contracts.`
);
} else {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
result.reason.message
);
}
}
}
}
} catch (e) {
if (e instanceof IgnitionError && shouldBeHardhatPluginError(e)) {
throw new NomicLabsHardhatPluginError(
"hardhat-ignition",
e.message,
e
);
}
throw e;
}
}
);
async function resolveParametersFromModuleName(
moduleName: string,
ignitionPath: string
): Promise<DeploymentParameters | undefined> {
const files = readdirSync(ignitionPath);
const configFilename = `${moduleName}.config.json`;
return files.includes(configFilename)
? resolveConfigPath(path.resolve(ignitionPath, configFilename))
: undefined;
}
async function resolveParametersFromFileName(
fileName: string
): Promise<DeploymentParameters> {
const filepath = path.resolve(process.cwd(), fileName);
return resolveConfigPath(filepath);
}
async function resolveConfigPath(
filepath: string
): Promise<DeploymentParameters> {
try {
const rawFile = await readFile(filepath);
return JSON.parse(rawFile.toString(), bigintReviver);
} catch (e) {
if (e instanceof NomicLabsHardhatPluginError) {
throw e;
}
if (e instanceof Error) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
`Could not parse parameters from ${filepath}`,
e
);
}
throw e;
}
}
function resolveParametersString(paramString: string): DeploymentParameters {
try {
return JSON.parse(paramString, bigintReviver);
} catch (e) {
if (e instanceof NomicLabsHardhatPluginError) {
throw e;
}
if (e instanceof Error) {
throw new NomicLabsHardhatPluginError(
"@nomicfoundation/hardhat-ignition",
"Could not parse JSON parameters",
e
);
}
throw e;
}
}