hardhat-deploy 2.0.0-next.7 → 2.0.0-next.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +120 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +197 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/config/default.d.ts.map +1 -0
  8. package/dist/config/default.js +5 -0
  9. package/dist/config/default.js.map +1 -0
  10. package/dist/config/get-config.d.ts.map +1 -0
  11. package/dist/config/get-config.js +9 -0
  12. package/dist/config/get-config.js.map +1 -0
  13. package/dist/config/validation.d.ts.map +1 -0
  14. package/dist/config/validation.js +17 -0
  15. package/dist/config/validation.js.map +1 -0
  16. package/dist/generate-types.d.ts +5 -0
  17. package/dist/generate-types.d.ts.map +1 -0
  18. package/dist/generate-types.js +241 -0
  19. package/dist/generate-types.js.map +1 -0
  20. package/dist/helpers.d.ts +34 -0
  21. package/dist/helpers.d.ts.map +1 -0
  22. package/dist/{esm/helpers.js → helpers.js} +106 -73
  23. package/dist/helpers.js.map +1 -0
  24. package/dist/hook-handlers/config.d.ts.map +1 -0
  25. package/dist/hook-handlers/config.js +68 -0
  26. package/dist/hook-handlers/config.js.map +1 -0
  27. package/dist/hook-handlers/solidity.d.ts.map +1 -0
  28. package/dist/hook-handlers/solidity.js +21 -0
  29. package/dist/hook-handlers/solidity.js.map +1 -0
  30. package/dist/index.d.ts +8 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/{esm/index.js → index.js} +20 -3
  33. package/dist/index.js.map +1 -0
  34. package/dist/postinstall.d.ts +3 -0
  35. package/dist/postinstall.d.ts.map +1 -0
  36. package/dist/postinstall.js +148 -0
  37. package/dist/postinstall.js.map +1 -0
  38. package/dist/{esm/tasks → tasks}/deploy.d.ts +1 -0
  39. package/dist/tasks/deploy.d.ts.map +1 -0
  40. package/dist/tasks/deploy.js +32 -0
  41. package/dist/tasks/deploy.js.map +1 -0
  42. package/dist/{esm/type-extensions.d.ts → type-extensions.d.ts} +2 -2
  43. package/dist/type-extensions.d.ts.map +1 -0
  44. package/dist/type-extensions.js.map +1 -0
  45. package/dist/types.d.ts +13 -0
  46. package/dist/types.d.ts.map +1 -0
  47. package/dist/types.js.map +1 -0
  48. package/dist/utils/files.d.ts +10 -0
  49. package/dist/utils/files.d.ts.map +1 -0
  50. package/dist/utils/files.js +44 -0
  51. package/dist/utils/files.js.map +1 -0
  52. package/dist/v1-detection.d.ts +12 -0
  53. package/dist/v1-detection.d.ts.map +1 -0
  54. package/dist/v1-detection.js +118 -0
  55. package/dist/v1-detection.js.map +1 -0
  56. package/dist/v1-entry.cjs +92 -0
  57. package/package.json +57 -27
  58. package/src/cli.ts +246 -0
  59. package/src/config/default.ts +6 -0
  60. package/src/config/get-config.ts +12 -0
  61. package/src/config/validation.ts +25 -0
  62. package/src/generate-types.ts +278 -0
  63. package/src/helpers.ts +311 -0
  64. package/src/hook-handlers/config.ts +80 -0
  65. package/src/hook-handlers/solidity.ts +33 -0
  66. package/src/index.ts +53 -0
  67. package/src/postinstall.ts +166 -0
  68. package/src/tasks/deploy.ts +43 -0
  69. package/src/type-extensions.ts +12 -0
  70. package/src/types.ts +9 -0
  71. package/src/utils/files.ts +59 -0
  72. package/src/v1-entry.cjs +92 -0
  73. package/templates/basic/README.md +44 -0
  74. package/templates/basic/contracts/Counter.sol +19 -0
  75. package/templates/basic/contracts/Counter.t.sol +29 -0
  76. package/templates/basic/deploy/01_deploy_counter.ts +13 -0
  77. package/templates/basic/hardhat.config.ts +50 -0
  78. package/templates/basic/package.json +31 -0
  79. package/templates/basic/pnpm-lock.yaml +1643 -0
  80. package/templates/basic/rocketh/config.ts +65 -0
  81. package/templates/basic/rocketh/deploy.ts +20 -0
  82. package/templates/basic/rocketh/environment.ts +22 -0
  83. package/templates/basic/test/Counter.ts +61 -0
  84. package/templates/basic/tsconfig.json +13 -0
  85. package/dist/esm/config/default.d.ts.map +0 -1
  86. package/dist/esm/config/default.js +0 -8
  87. package/dist/esm/config/default.js.map +0 -1
  88. package/dist/esm/config/get-config.d.ts.map +0 -1
  89. package/dist/esm/config/get-config.js +0 -8
  90. package/dist/esm/config/get-config.js.map +0 -1
  91. package/dist/esm/config/validation.d.ts.map +0 -1
  92. package/dist/esm/config/validation.js +0 -16
  93. package/dist/esm/config/validation.js.map +0 -1
  94. package/dist/esm/generate-types.d.ts +0 -6
  95. package/dist/esm/generate-types.d.ts.map +0 -1
  96. package/dist/esm/generate-types.js +0 -198
  97. package/dist/esm/generate-types.js.map +0 -1
  98. package/dist/esm/helpers.d.ts +0 -18
  99. package/dist/esm/helpers.d.ts.map +0 -1
  100. package/dist/esm/helpers.js.map +0 -1
  101. package/dist/esm/hook-handlers/config.d.ts.map +0 -1
  102. package/dist/esm/hook-handlers/config.js +0 -16
  103. package/dist/esm/hook-handlers/config.js.map +0 -1
  104. package/dist/esm/hook-handlers/solidity.d.ts.map +0 -1
  105. package/dist/esm/hook-handlers/solidity.js +0 -15
  106. package/dist/esm/hook-handlers/solidity.js.map +0 -1
  107. package/dist/esm/index.d.ts +0 -5
  108. package/dist/esm/index.d.ts.map +0 -1
  109. package/dist/esm/index.js.map +0 -1
  110. package/dist/esm/tasks/deploy.d.ts.map +0 -1
  111. package/dist/esm/tasks/deploy.js +0 -21
  112. package/dist/esm/tasks/deploy.js.map +0 -1
  113. package/dist/esm/type-extensions.d.ts.map +0 -1
  114. package/dist/esm/type-extensions.js.map +0 -1
  115. package/dist/esm/types.d.ts +0 -15
  116. package/dist/esm/types.d.ts.map +0 -1
  117. package/dist/esm/types.js.map +0 -1
  118. /package/dist/{esm/config → config}/default.d.ts +0 -0
  119. /package/dist/{esm/config → config}/get-config.d.ts +0 -0
  120. /package/dist/{esm/config → config}/validation.d.ts +0 -0
  121. /package/dist/{esm/hook-handlers → hook-handlers}/config.d.ts +0 -0
  122. /package/dist/{esm/hook-handlers → hook-handlers}/solidity.d.ts +0 -0
  123. /package/dist/{esm/type-extensions.js → type-extensions.js} +0 -0
  124. /package/dist/{esm/types.js → types.js} +0 -0
@@ -0,0 +1,278 @@
1
+ import type {ArtifactGenerationConfig} from './types.js';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {FileTraversed, slash, traverse} from './utils/files.js';
5
+
6
+
7
+ function writeIfDifferent(filePath: string, newTextContent: string) {
8
+ // Ensure we're working with a string
9
+ const contentToWrite = String(newTextContent);
10
+
11
+ try {
12
+ let existingContent;
13
+
14
+ try {
15
+ existingContent = fs.readFileSync(filePath, 'utf8');
16
+ } catch (error) {
17
+ // console.log(`do not exist? => writing ${filePath}`);
18
+ // File doesn't exist, write and return
19
+ fs.writeFileSync(filePath, contentToWrite);
20
+ return {written: true, reason: 'File did not exist'};
21
+ }
22
+
23
+ // Simple string comparison
24
+ if (contentToWrite !== existingContent) {
25
+ // console.log(`content different => writing ${filePath}`);
26
+ fs.writeFileSync(filePath, contentToWrite);
27
+ return {written: true, reason: 'Content was different'};
28
+ }
29
+
30
+ return {written: false, reason: 'Content was identical'};
31
+ } catch (error) {
32
+ console.error('Error in writeIfDifferent:', error);
33
+ throw error;
34
+ }
35
+ }
36
+
37
+ function ensureDirExistsSync(folderPath: string) {
38
+ // Check if directory already exists
39
+ if (fs.existsSync(folderPath)) {
40
+ return {created: false, reason: 'Directory already exists'};
41
+ }
42
+
43
+ // console.log(`do not exist? => mkdir ${folderPath}`);
44
+ // Directory doesn't exist, create it
45
+ fs.mkdirSync(folderPath, {recursive: true});
46
+ return {created: true, reason: 'Directory was created'};
47
+ }
48
+
49
+ type Artifact = {
50
+ contractName: string;
51
+ abi: any[];
52
+ // ...
53
+ };
54
+
55
+ type Artifacts = {[key: string]: Artifact};
56
+
57
+ function writeArtifactToFile(folder: string, canonicalName: string, data: Artifact, mode: 'typescript' | 'javascript') {
58
+ const name = canonicalName.split('/').pop();
59
+ const artifactName = `Artifact_${name}`;
60
+ const tsFilepath = path.join(folder, 'artifacts', canonicalName) + '.ts';
61
+ const folderPath = path.dirname(tsFilepath);
62
+ ensureDirExistsSync(folderPath);
63
+ if (mode === 'typescript') {
64
+ const newContent = `export const ${artifactName}: ${JSON.stringify(data, null, 2)} = ${JSON.stringify(data, null, 2)} as const;`;
65
+ writeIfDifferent(tsFilepath, newContent);
66
+ } else if (mode === 'javascript') {
67
+ const newContent = `export const ${artifactName} = /** @type {const} **/ (${JSON.stringify(data, null, 2)});`;
68
+ const dtsContent = `export declare const ${artifactName}: ${JSON.stringify(data, null, 2)};`;
69
+ const jsFilepath = path.join(folder, 'artifacts', canonicalName) + '.js';
70
+ writeIfDifferent(jsFilepath, newContent);
71
+ writeIfDifferent(jsFilepath.replace(/\.js$/, '.d.ts'), dtsContent);
72
+ }
73
+ }
74
+
75
+ function writeArtifactIndexToFile(folder: string, data: Artifacts, mode: 'typescript' | 'javascript') {
76
+ const tsFilepath = path.join(folder, 'artifacts', 'index') + '.ts';
77
+ const folderPath = path.dirname(tsFilepath);
78
+ ensureDirExistsSync(folderPath);
79
+ if (mode === 'typescript') {
80
+ let newContent = '';
81
+ for (const canonicalName of Object.keys(data)) {
82
+ const transformedName = canonicalName.replaceAll('/', '_').replaceAll('.', '_');
83
+ const name = canonicalName.split('/').pop();
84
+ const artifactName = `Artifact_${name}`;
85
+ const importNaming =
86
+ canonicalName != name ? `${artifactName} as ${transformedName}` : `${artifactName} as ${name}`;
87
+ newContent += `export {${importNaming}} from './${canonicalName}.js';\n`;
88
+ }
89
+
90
+ writeIfDifferent(tsFilepath, newContent);
91
+ } else if (mode === 'javascript') {
92
+ let newContent = '';
93
+ for (const canonicalName of Object.keys(data)) {
94
+ const transformedName = canonicalName.replaceAll('/', '_').replaceAll('.', '_');
95
+ const name = canonicalName.split('/').pop();
96
+ const artifactName = `Artifact_${name}`;
97
+ const importNaming =
98
+ canonicalName != name ? `${artifactName} as ${transformedName}` : `${artifactName} as ${name}`;
99
+ newContent += `export {${importNaming}} from './${canonicalName}.js';\n`;
100
+ }
101
+ const jsFilepath = path.join(folder, 'artifacts', 'index') + '.js';
102
+ writeIfDifferent(jsFilepath, newContent);
103
+ writeIfDifferent(jsFilepath.replace(/\.js$/, '.d.ts'), newContent);
104
+ }
105
+ }
106
+
107
+ function writeABIDefinitionToFile(
108
+ folder: string,
109
+ canonicalName: string,
110
+ data: Artifact,
111
+ mode: 'typescript' | 'javascript',
112
+ ) {
113
+ const nameAsPath = canonicalName.split('/');
114
+ const name = nameAsPath[nameAsPath.length - 1];
115
+ const abiName = `Abi_${name}`;
116
+ const artifactName = `Artifact_${name}`;
117
+ const relativePath = `../`.repeat(nameAsPath.length);
118
+ const tsFilepath = path.join(folder, 'abis', canonicalName) + '.ts';
119
+ const folderPath = path.dirname(tsFilepath);
120
+ ensureDirExistsSync(folderPath);
121
+ if (mode === 'typescript') {
122
+ const newContent = `import {${artifactName}} from '${relativePath}artifacts/${canonicalName}.js';
123
+ export type ${abiName} = (typeof ${artifactName})['abi'];\n`;
124
+ writeIfDifferent(tsFilepath, newContent);
125
+ } else if (mode === 'javascript') {
126
+ const jsFilepath = path.join(folder, 'abis', canonicalName) + '.js';
127
+ const newContent = `export {};\n`;
128
+ const dtsContent = `import {${artifactName}} from '${relativePath}artifacts/${canonicalName}.js';
129
+ export type ${abiName} = (typeof ${artifactName})['abi'];\n`;
130
+ writeIfDifferent(jsFilepath, newContent);
131
+ writeIfDifferent(jsFilepath.replace(/\.js$/, '.d.ts'), dtsContent);
132
+ }
133
+ }
134
+ function writeABIDefinitionIndexToFile(folder: string, data: Artifacts, mode: 'typescript' | 'javascript') {
135
+ const tsFilepath = path.join(folder, 'abis', 'index') + '.ts';
136
+ const folderPath = path.dirname(tsFilepath);
137
+ ensureDirExistsSync(folderPath);
138
+ if (mode === 'typescript') {
139
+ let newContent = '';
140
+ for (const canonicalName of Object.keys(data)) {
141
+ const transformedName = canonicalName.replaceAll('/', '_').replaceAll('.', '_');
142
+ const name = canonicalName.split('/').pop();
143
+ const abiName = `Abi_${name}`;
144
+ const importNaming = canonicalName != name ? `${abiName} as ${transformedName}` : `${abiName} as ${name}`;
145
+ newContent += `export {${importNaming}} from "./${canonicalName}.js"\n`;
146
+ }
147
+ writeIfDifferent(tsFilepath, newContent);
148
+ } else if (mode === 'javascript') {
149
+ const jsFilepath = path.join(folder, 'abis', 'index') + '.js';
150
+ let newContent = '';
151
+ for (const canonicalName of Object.keys(data)) {
152
+ const transformedName = canonicalName.replaceAll('/', '_').replaceAll('.', '_');
153
+ const name = canonicalName.split('/').pop();
154
+ const abiName = `Abi_${name}`;
155
+ const importNaming = canonicalName != name ? `${abiName} as ${transformedName}` : `${abiName} as ${name}`;
156
+ newContent += `export {${importNaming}} from "./${canonicalName}.js"\n`;
157
+ }
158
+ writeIfDifferent(jsFilepath, newContent);
159
+ writeIfDifferent(jsFilepath.replace(/\.js$/, '.d.ts'), newContent);
160
+ }
161
+ }
162
+
163
+ export async function generateTypes(paths: {artifacts: string[]}, config: ArtifactGenerationConfig): Promise<void> {
164
+ const buildInfoCache = new Map<string, any>();
165
+ const allArtifacts: {[name: string]: any} = {};
166
+ const shortNameDict: {[shortName: string]: boolean} = {};
167
+
168
+ for (const artifactsPath of paths.artifacts) {
169
+ const files: FileTraversed[] = traverse(
170
+ artifactsPath,
171
+ [],
172
+ artifactsPath,
173
+ (name) => name != 'build-info' && !name.endsWith('.t.sol') && !name.endsWith('.dbg.json'),
174
+ );
175
+
176
+ // console.log('--------------------------');
177
+ // console.log(files);
178
+ // console.log('--------------------------');
179
+
180
+ for (const file of files) {
181
+ const filepath = file.path;
182
+ if (file.directory || !filepath.endsWith('.json')) {
183
+ continue;
184
+ }
185
+ const filename = slash(path.basename(filepath));
186
+ const dirname = slash(path.dirname(file.relativePath));
187
+
188
+ // const namePath = dirname.replace('.sol', '');
189
+ const contractName = filename.replace('.json', '');
190
+ // const shortName = artifact.artifactsEmitted[i];
191
+ // console.log({path: filepath});
192
+ const content = fs.readFileSync(filepath, 'utf-8');
193
+ const parsed = JSON.parse(content);
194
+
195
+ if (!parsed.buildInfoId) continue;
196
+
197
+ // TODO read config for artifacts folder
198
+ let buildInfoFilepath = path.join(artifactsPath, 'build-info', `${parsed.buildInfoId}.output.json`);
199
+
200
+ if (!parsed.buildInfoId) {
201
+ // support hardhat v2 artifacts files
202
+ if (fs.existsSync(filepath.replace('.json', '.dbg.json'))) {
203
+ // console.warn(`Artifact ${filepath} does not have a buildInfoId, but found a .dbg.json file. Using that instead.`);
204
+ const dbgContent = fs.readFileSync(filepath.replace('.json', '.dbg.json'), 'utf-8');
205
+ const dbgParsed = JSON.parse(dbgContent);
206
+ const buildInfoRelativePath = dbgParsed.buildInfo;
207
+ parsed.buildInfoId = path.basename(buildInfoRelativePath, '.json');
208
+ // console.log({buildInfoRelativePath, buildInfoId: parsed.buildInfoId});
209
+ buildInfoFilepath = path.join(artifactsPath, 'build-info', `${parsed.buildInfoId}.json`);
210
+ }
211
+ }
212
+
213
+ // const backupBuildInfoFilepath = path.join(
214
+ // './generated',
215
+ // buildInfoFilepath.slice(buildInfoFilepath.indexOf('/', 1))
216
+ // );
217
+ let buildInfoFilepathToUse = buildInfoFilepath;
218
+ // if (!fs.existsSync(buildInfoFilepathToUse)) {
219
+ // buildInfoFilepathToUse = backupBuildInfoFilepath;
220
+ // }
221
+ let parsedBuildInfo;
222
+ if (!buildInfoCache.has(buildInfoFilepathToUse)) {
223
+ if (!fs.existsSync(buildInfoFilepathToUse)) continue;
224
+ const buildInfoContent = fs.readFileSync(buildInfoFilepathToUse, 'utf-8');
225
+ parsedBuildInfo = JSON.parse(buildInfoContent);
226
+ buildInfoCache.set(buildInfoFilepathToUse, parsedBuildInfo);
227
+ } else {
228
+ parsedBuildInfo = buildInfoCache.get(buildInfoFilepathToUse);
229
+ }
230
+
231
+ const solidityOutput = parsedBuildInfo.output.contracts[parsed.inputSourceName][contractName];
232
+ const hardhatArtifactObject = {...parsed, ...solidityOutput};
233
+ const {buildInfoId, _format, ...artifactObject} = hardhatArtifactObject;
234
+ const fullName = `${dirname}/${contractName}`;
235
+ allArtifacts[fullName] = artifactObject;
236
+ if (shortNameDict[contractName]) {
237
+ delete allArtifacts[contractName];
238
+ } else {
239
+ allArtifacts[contractName] = artifactObject;
240
+ shortNameDict[contractName] = true;
241
+ }
242
+ }
243
+ }
244
+
245
+ for (const key of Object.keys(allArtifacts)) {
246
+ if (key.indexOf('/') >= 0) {
247
+ const split = key.split('/');
248
+ if (split.length > 1) {
249
+ const shortName = split[split.length - 1];
250
+ if (allArtifacts[shortName]) {
251
+ delete allArtifacts[key];
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ // for (const key of Object.keys(allArtifacts)) {
258
+ // const artifact = allArtifacts[key];
259
+ // writeFiles(key, artifact, config);
260
+ // }
261
+ // // const json = hre.config.generateTypedArtifacts.json || [];
262
+ // // json.push('./generated/_artifacts.json');
263
+ // // writeFiles(undefined, allArtifacts, {...hre.config.generateTypedArtifacts, json: json});
264
+
265
+ // writeFiles(undefined, allArtifacts, config);
266
+
267
+ for (const destination of config.destinations) {
268
+ const generatedFolder = destination.folder;
269
+ const mode = destination.mode;
270
+ for (const key of Object.keys(allArtifacts)) {
271
+ writeABIDefinitionToFile(generatedFolder, key, allArtifacts[key], mode);
272
+ writeArtifactToFile(generatedFolder, key, allArtifacts[key], mode);
273
+ }
274
+
275
+ writeArtifactIndexToFile(generatedFolder, allArtifacts, mode);
276
+ writeABIDefinitionIndexToFile(generatedFolder, allArtifacts, mode);
277
+ }
278
+ }
package/src/helpers.ts ADDED
@@ -0,0 +1,311 @@
1
+ import {configVariable} from 'hardhat/config';
2
+ import {
3
+ EdrNetworkHDAccountsUserConfig,
4
+ EdrNetworkUserConfig,
5
+ HttpNetworkUserConfig,
6
+ NetworkUserConfig,
7
+ SensitiveString,
8
+ } from 'hardhat/types/config';
9
+ import {HardhatRuntimeEnvironment} from 'hardhat/types/hre';
10
+ import {NetworkConnection} from 'hardhat/types/network';
11
+ import type {Environment, UnresolvedUnknownNamedAccounts, UnresolvedNetworkSpecificData} from 'rocketh/types';
12
+ import {enhanceEnvIfNeeded, chainByCanonicalName} from 'rocketh';
13
+ import {loadEnvironmentFromFiles} from '@rocketh/node';
14
+
15
+ export function setupHardhatDeploy<
16
+ Extensions extends Record<string, (env: Environment<any, any, any>) => any> = {},
17
+ NamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,
18
+ Data extends UnresolvedNetworkSpecificData = UnresolvedNetworkSpecificData,
19
+ >(extensions: Extensions) {
20
+ async function loadEnvironmentFromHardhatWithExtensions(
21
+ required: {hre: HardhatRuntimeEnvironment; connection?: NetworkConnection},
22
+ // options?: {
23
+ // useChainIdOfForkedNetwork?: boolean;
24
+ // }
25
+ ) {
26
+ const env = await loadEnvironmentFromHardhat<NamedAccounts, Data>(required);
27
+ return enhanceEnvIfNeeded(env, extensions);
28
+ }
29
+
30
+ return {
31
+ loadEnvironmentFromHardhat: loadEnvironmentFromHardhatWithExtensions,
32
+ };
33
+ }
34
+
35
+ export async function generateForkConfig(
36
+ params: {hre: HardhatRuntimeEnvironment; connection?: NetworkConnection},
37
+ // options?: {
38
+ // useChainIdOfForkedNetwork?: boolean;
39
+ // }
40
+ ): Promise<{provider: any; environment: string | {fork: string}; connection: NetworkConnection; isFork: boolean}> {
41
+ const fork = process.env.HARDHAT_FORK as string | undefined;
42
+
43
+ const connection =
44
+ params.connection || fork
45
+ ? await params.hre.network.connect({network: 'fork'})
46
+ : await params.hre.network.connect();
47
+
48
+ let provider: any = connection.provider;
49
+ let environment: string | {fork: string} = connection.networkName;
50
+ let forkChainId: number | undefined;
51
+
52
+ if (fork) {
53
+ // if (options?.useChainIdOfForkedNetwork) {
54
+ // const forkNetworkConfig = params.hre.config.networks[fork];
55
+
56
+ // if (forkNetworkConfig.type === 'edr-simulated') {
57
+ // forkChainId = forkNetworkConfig.chainId;
58
+ // } else if (forkNetworkConfig.chainId) {
59
+ // forkChainId = forkNetworkConfig.chainId;
60
+ // } else {
61
+ // if ('url' in forkNetworkConfig) {
62
+ // const url = await forkNetworkConfig.url.getUrl();
63
+ // const response = await fetch(url, {
64
+ // method: 'POST',
65
+ // headers: {
66
+ // 'Content-Type': 'application/json',
67
+ // },
68
+ // body: JSON.stringify({
69
+ // jsonrpc: '2.0',
70
+ // id: 1,
71
+ // method: 'eth_chainId',
72
+ // params: [],
73
+ // }),
74
+ // });
75
+ // const json = (await response.json()) as {result: string};
76
+ // forkChainId = Number(json.result);
77
+ // } else {
78
+ // throw new Error(`cannot fetch chainId`);
79
+ // }
80
+ // }
81
+ // }
82
+
83
+ environment = {
84
+ fork,
85
+ };
86
+ }
87
+
88
+ if (forkChainId) {
89
+ const originalProvider = provider;
90
+ const chainId = forkChainId;
91
+ async function request(args: {method: string; params?: string[]}): Promise<any> {
92
+ if (args.method === 'eth_chainId') {
93
+ return `0x${chainId.toString(16)}`;
94
+ }
95
+ return originalProvider.request(args);
96
+ }
97
+ provider = new Proxy(originalProvider, {
98
+ get: function (target, property, receiver) {
99
+ switch (property) {
100
+ case 'request':
101
+ return request;
102
+ default:
103
+ return originalProvider[property];
104
+ }
105
+ },
106
+ });
107
+ }
108
+
109
+ return {provider, environment, connection, isFork: !!fork};
110
+ }
111
+
112
+ export async function loadEnvironmentFromHardhat<
113
+ NamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,
114
+ Data extends UnresolvedNetworkSpecificData = UnresolvedNetworkSpecificData,
115
+ >(
116
+ params: {hre: HardhatRuntimeEnvironment; connection?: NetworkConnection},
117
+ // TODO ?
118
+ // options?: {
119
+ // useChainIdOfForkedNetwork?: boolean;
120
+ // }
121
+ ): Promise<Environment<NamedAccounts, Data>> {
122
+ const {connection, environment, provider, isFork} = await generateForkConfig(params);
123
+ // console.log(`loading environments...`);
124
+ return loadEnvironmentFromFiles<NamedAccounts, Data>({
125
+ provider,
126
+ environment,
127
+ extra: {
128
+ connection,
129
+ },
130
+ saveDeployments: isFork ? false : undefined,
131
+ });
132
+ }
133
+
134
+ function getVariable(prefix: string, name: string): string | SensitiveString | undefined {
135
+ // We transform dash into underscore as dash are not supported everywhere in env var names
136
+ const variableName = (prefix + name).replaceAll('-', '_');
137
+ let uri = process.env[variableName];
138
+ if (uri === 'SECRET') {
139
+ return configVariable(`SECRET_${variableName}`);
140
+ } else if (uri?.startsWith('SECRET:')) {
141
+ const splitted = uri.split(':');
142
+ if (splitted.length !== 2) {
143
+ throw new Error(`invalid secret uri ${uri}`);
144
+ }
145
+ return configVariable(`SECRET_${prefix + splitted[1]}`);
146
+ }
147
+ return uri;
148
+ }
149
+
150
+ export function getRPC(networkName: string): string | SensitiveString | undefined {
151
+ let uri = getVariable('ETH_NODE_URI_', networkName);
152
+
153
+ if (uri && uri !== '') {
154
+ return uri;
155
+ }
156
+
157
+ uri = process.env.ETH_NODE_URI;
158
+ if (uri) {
159
+ uri = uri.replace('{{networkName}}', networkName);
160
+ }
161
+ if (!uri || uri === '') {
162
+ if (networkName === 'localhost') {
163
+ return 'http://localhost:8545';
164
+ }
165
+ return uri;
166
+ // throw new Error(`no uri specified or for network ${networkName}`);
167
+ }
168
+ if (uri.indexOf('{{') >= 0) {
169
+ throw new Error(`invalid uri or network not supported by node provider : ${uri}`);
170
+ }
171
+
172
+ return uri;
173
+ }
174
+
175
+ export function getMnemonic(networkName?: string, doNotDefault?: boolean): string | SensitiveString | undefined {
176
+ if (networkName) {
177
+ const mnemonic = getVariable('MNEMONIC_', networkName);
178
+
179
+ if (mnemonic && mnemonic !== '') {
180
+ return mnemonic;
181
+ }
182
+ }
183
+
184
+ const mnemonic = process.env.MNEMONIC;
185
+ if (!mnemonic || mnemonic === '') {
186
+ if (doNotDefault) {
187
+ return undefined;
188
+ }
189
+ return 'test test test test test test test test test test test junk';
190
+ }
191
+ return mnemonic;
192
+ }
193
+
194
+ export function getAccounts(
195
+ networkName?: string,
196
+ doNotDefault?: boolean,
197
+ ): {mnemonic: string | SensitiveString} | undefined {
198
+ const mnemonic = getMnemonic(networkName, doNotDefault);
199
+ if (!mnemonic) {
200
+ return undefined;
201
+ }
202
+ return {mnemonic};
203
+ }
204
+
205
+ export function addNetworksFromEnv(networks?: Record<string, NetworkUserConfig>): Record<string, NetworkUserConfig> {
206
+ const newNetworks: Record<string, NetworkUserConfig> = networks ? {...networks} : {};
207
+ const allEnv = Object.keys(process.env);
208
+ for (const envKey of allEnv) {
209
+ if (envKey.startsWith(`ETH_NODE_URI_`) && envKey.length > `ETH_NODE_URI_`.length) {
210
+ const networkName = envKey.slice(`ETH_NODE_URI_`.length);
211
+ const url = getRPC(networkName);
212
+ if (!newNetworks[networkName]) {
213
+ if (url) {
214
+ newNetworks[networkName] = {
215
+ type: 'http',
216
+ url,
217
+ accounts: getAccounts(networkName),
218
+ };
219
+ } else {
220
+ console.error(`no url for network ${networkName}`);
221
+ }
222
+ } else {
223
+ console.error(`duplicated network ${networkName}`);
224
+ }
225
+ }
226
+ }
227
+ return newNetworks;
228
+ }
229
+
230
+ const listOfNetworkNamesWithTestAccountAllowed = ['hardhat', 'localhost', 'memory', 'test'];
231
+ export function addNetworksFromKnownList(
232
+ networks?: Record<string, NetworkUserConfig>,
233
+ ): Record<string, NetworkUserConfig> {
234
+ const newNetworks: Record<string, NetworkUserConfig> = networks ? {...networks} : {};
235
+ const canonicalNames = Object.keys(chainByCanonicalName);
236
+
237
+ for (const canonicalName of canonicalNames) {
238
+ const chain = chainByCanonicalName[canonicalName];
239
+ const url = getRPC(canonicalName) || chain.rpcUrls.default.http[0];
240
+ if (!newNetworks[canonicalName]) {
241
+ if (url) {
242
+ newNetworks[canonicalName] = {
243
+ type: 'http',
244
+ url,
245
+ accounts: getAccounts(canonicalName, !listOfNetworkNamesWithTestAccountAllowed.includes(canonicalName)),
246
+ chainType: chain.chainType === 'op-stack' ? 'op' : undefined,
247
+ chainId: chain.id,
248
+ };
249
+ } else {
250
+ console.error(`no url for chain ${canonicalName}`);
251
+ }
252
+ } else {
253
+ // console.error(`duplicated chain ${canonicalName}`);
254
+ }
255
+ }
256
+ return newNetworks;
257
+ }
258
+
259
+ export function addForkConfiguration(networks: Record<string, NetworkUserConfig>): Record<string, NetworkUserConfig> {
260
+ const currentNetworkName = process.env.HARDHAT_FORK;
261
+ let forkURL: SensitiveString | string | undefined;
262
+ let hardhatAccounts: EdrNetworkHDAccountsUserConfig | undefined;
263
+ if (
264
+ currentNetworkName &&
265
+ currentNetworkName !== 'hardhat' &&
266
+ currentNetworkName !== 'edr' &&
267
+ currentNetworkName !== 'edr-simulated' &&
268
+ currentNetworkName !== 'memory'
269
+ ) {
270
+ const currentNetwork = networks[currentNetworkName] as HttpNetworkUserConfig;
271
+ if (currentNetwork) {
272
+ if (currentNetwork.type === 'http') {
273
+ forkURL = currentNetwork.url;
274
+ if (
275
+ currentNetwork.accounts &&
276
+ typeof currentNetwork.accounts === 'object' &&
277
+ 'mnemonic' in currentNetwork.accounts
278
+ ) {
279
+ hardhatAccounts = currentNetwork.accounts;
280
+ }
281
+
282
+ // else if (currentNetwork.accounts && Array.isArray(currentNetwork.accounts)) {
283
+ // hardhatAccounts = currentNetwork.accounts.map((v) => ({
284
+ // balance: '10000000000000000000000',
285
+ // privateKey: v,
286
+ // }));
287
+ // }
288
+ }
289
+ }
290
+ }
291
+
292
+ const existingForkConfiguration: EdrNetworkUserConfig =
293
+ networks.fork && networks.fork.type === 'edr-simulated' ? networks.fork : {type: 'edr-simulated', chainType: 'l1'};
294
+
295
+ const newNetworks: Record<string, NetworkUserConfig> = {
296
+ ...networks,
297
+ fork: {
298
+ ...existingForkConfiguration,
299
+ ...{
300
+ accounts: hardhatAccounts || existingForkConfiguration?.accounts,
301
+ forking: forkURL
302
+ ? {
303
+ url: forkURL,
304
+ blockNumber: process.env.HARDHAT_FORK_NUMBER ? parseInt(process.env.HARDHAT_FORK_NUMBER) : undefined,
305
+ }
306
+ : undefined,
307
+ },
308
+ },
309
+ };
310
+ return newNetworks;
311
+ }
@@ -0,0 +1,80 @@
1
+ import type {ConfigHooks} from 'hardhat/types/hooks';
2
+
3
+ import {getConfig} from '../config/get-config.js';
4
+ import {validateTypechainUserConfig} from '../config/validation.js';
5
+ import {SolidityBuildProfileConfig, SolidityConfig} from 'hardhat/types/config';
6
+
7
+ function addIfNotPresent(array: string[], value: string) {
8
+ if (array.indexOf(value) === -1) {
9
+ array.push(value);
10
+ }
11
+ }
12
+ function setupExtraSolcSettings(settings: {
13
+ metadata: {useLiteralContent: boolean};
14
+ outputSelection: {'*': {'': string[]; '*': string[]}};
15
+ }): void {
16
+ settings.metadata = settings.metadata || {};
17
+ settings.metadata.useLiteralContent = true;
18
+
19
+ if (settings.outputSelection === undefined) {
20
+ settings.outputSelection = {
21
+ '*': {
22
+ '*': [],
23
+ '': [],
24
+ },
25
+ };
26
+ }
27
+ if (settings.outputSelection['*'] === undefined) {
28
+ settings.outputSelection['*'] = {
29
+ '*': [],
30
+ '': [],
31
+ };
32
+ }
33
+ if (settings.outputSelection['*']['*'] === undefined) {
34
+ settings.outputSelection['*']['*'] = [];
35
+ }
36
+ if (settings.outputSelection['*'][''] === undefined) {
37
+ settings.outputSelection['*'][''] = [];
38
+ }
39
+
40
+ addIfNotPresent(settings.outputSelection['*']['*'], 'abi');
41
+ // addIfNotPresent(settings.outputSelection['*']['*'], 'evm.bytecode');
42
+ // addIfNotPresent(settings.outputSelection['*']['*'], 'evm.deployedBytecode');
43
+ addIfNotPresent(settings.outputSelection['*']['*'], 'metadata');
44
+ addIfNotPresent(settings.outputSelection['*']['*'], 'devdoc');
45
+ addIfNotPresent(settings.outputSelection['*']['*'], 'userdoc');
46
+ addIfNotPresent(settings.outputSelection['*']['*'], 'storageLayout');
47
+ // addIfNotPresent(settings.outputSelection['*']['*'], 'evm.methodIdentifiers');
48
+ addIfNotPresent(settings.outputSelection['*']['*'], 'evm.gasEstimates');
49
+ // addIfNotPresent(settings.outputSelection["*"][""], "ir");
50
+ // addIfNotPresent(settings.outputSelection["*"][""], "irOptimized");
51
+ // addIfNotPresent(settings.outputSelection["*"][""], "ast");
52
+ }
53
+
54
+ export default async (): Promise<Partial<ConfigHooks>> => {
55
+ const handlers: Partial<ConfigHooks> = {
56
+ validateUserConfig: validateTypechainUserConfig,
57
+ resolveUserConfig: async (userConfig, resolveConfigurationVariable, next) => {
58
+ const resolvedConfig = await next(userConfig, resolveConfigurationVariable);
59
+
60
+ const solidity: SolidityConfig = structuredClone(resolvedConfig.solidity);
61
+ const profiles: Record<string, SolidityBuildProfileConfig> = solidity.profiles;
62
+ for (const profileName of Object.keys(profiles)) {
63
+ const profile: SolidityBuildProfileConfig = profiles[profileName];
64
+ const compilers = profile.compilers;
65
+ for (const compiler of compilers) {
66
+ const settings = compiler.settings;
67
+ setupExtraSolcSettings(settings);
68
+ }
69
+ }
70
+
71
+ return {
72
+ ...resolvedConfig,
73
+ solidity,
74
+ generateTypedArtifacts: getConfig(userConfig.generateTypedArtifacts),
75
+ };
76
+ },
77
+ };
78
+
79
+ return handlers;
80
+ };