hardhat-deploy 2.0.0-next.4 → 2.0.0-next.41

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 (58) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +630 -1
  3. package/dist/esm/config/default.d.ts.map +1 -1
  4. package/dist/esm/config/default.js +8 -5
  5. package/dist/esm/config/default.js.map +1 -1
  6. package/dist/esm/config/get-config.d.ts.map +1 -1
  7. package/dist/esm/config/get-config.js +5 -2
  8. package/dist/esm/config/get-config.js.map +1 -1
  9. package/dist/esm/config/validation.d.ts.map +1 -1
  10. package/dist/esm/config/validation.js +12 -7
  11. package/dist/esm/config/validation.js.map +1 -1
  12. package/dist/esm/generate-types.d.ts +2 -3
  13. package/dist/esm/generate-types.d.ts.map +1 -1
  14. package/dist/esm/generate-types.js +153 -83
  15. package/dist/esm/generate-types.js.map +1 -1
  16. package/dist/esm/helpers.d.ts +12 -6
  17. package/dist/esm/helpers.d.ts.map +1 -1
  18. package/dist/esm/helpers.js +52 -24
  19. package/dist/esm/helpers.js.map +1 -1
  20. package/dist/esm/hook-handlers/config.d.ts.map +1 -1
  21. package/dist/esm/hook-handlers/config.js +53 -1
  22. package/dist/esm/hook-handlers/config.js.map +1 -1
  23. package/dist/esm/hook-handlers/solidity.d.ts.map +1 -1
  24. package/dist/esm/hook-handlers/solidity.js +13 -7
  25. package/dist/esm/hook-handlers/solidity.js.map +1 -1
  26. package/dist/esm/index.d.ts +3 -0
  27. package/dist/esm/index.d.ts.map +1 -1
  28. package/dist/esm/index.js +17 -5
  29. package/dist/esm/index.js.map +1 -1
  30. package/dist/esm/tasks/deploy.d.ts +1 -0
  31. package/dist/esm/tasks/deploy.d.ts.map +1 -1
  32. package/dist/esm/tasks/deploy.js +13 -5
  33. package/dist/esm/tasks/deploy.js.map +1 -1
  34. package/dist/esm/type-extensions.d.ts +2 -2
  35. package/dist/esm/type-extensions.d.ts.map +1 -1
  36. package/dist/esm/types.d.ts +14 -10
  37. package/dist/esm/types.d.ts.map +1 -1
  38. package/dist/esm/utils/files.d.ts +9 -0
  39. package/dist/esm/utils/files.d.ts.map +1 -0
  40. package/dist/esm/utils/files.js +25 -0
  41. package/dist/esm/utils/files.js.map +1 -0
  42. package/package.json +16 -13
  43. package/src/config/default.ts +12 -0
  44. package/src/config/get-config.ts +13 -0
  45. package/src/config/validation.ts +27 -0
  46. package/src/generate-types.ts +292 -0
  47. package/src/helpers.ts +285 -0
  48. package/src/hook-handlers/config.ts +80 -0
  49. package/src/hook-handlers/solidity.ts +33 -0
  50. package/src/index.ts +47 -0
  51. package/src/tasks/deploy.ts +35 -0
  52. package/src/type-extensions.ts +12 -0
  53. package/src/types.ts +21 -0
  54. package/src/utils/files.ts +37 -0
  55. package/dist/esm/tasks/compile.d.ts +0 -6
  56. package/dist/esm/tasks/compile.d.ts.map +0 -1
  57. package/dist/esm/tasks/compile.js +0 -254
  58. package/dist/esm/tasks/compile.js.map +0 -1
@@ -0,0 +1,292 @@
1
+ import type {ArtifactGenerationConfig} from './types.js';
2
+ import debug from 'debug';
3
+ import fs from 'node:fs';
4
+ import path, {basename, dirname} from 'node:path';
5
+ import slash from 'slash';
6
+ import {FileTraversed, traverse} from './utils/files.js';
7
+
8
+ const log = debug('hardhat-deploy:generate-types');
9
+
10
+ function writeIfDifferent(filePath: string, newTextContent: string) {
11
+ // Ensure we're working with a string
12
+ const contentToWrite = String(newTextContent);
13
+
14
+ try {
15
+ let existingContent;
16
+
17
+ try {
18
+ existingContent = fs.readFileSync(filePath, 'utf8');
19
+ } catch (error) {
20
+ // console.log(`do not exist? => writing ${filePath}`);
21
+ // File doesn't exist, write and return
22
+ fs.writeFileSync(filePath, contentToWrite);
23
+ return {written: true, reason: 'File did not exist'};
24
+ }
25
+
26
+ // Simple string comparison
27
+ if (contentToWrite !== existingContent) {
28
+ // console.log(`content different => writing ${filePath}`);
29
+ fs.writeFileSync(filePath, contentToWrite);
30
+ return {written: true, reason: 'Content was different'};
31
+ }
32
+
33
+ return {written: false, reason: 'Content was identical'};
34
+ } catch (error) {
35
+ console.error('Error in writeIfDifferent:', error);
36
+ throw error;
37
+ }
38
+ }
39
+
40
+ function ensureDirExistsSync(folderPath: string) {
41
+ // Check if directory already exists
42
+ if (fs.existsSync(folderPath)) {
43
+ return {created: false, reason: 'Directory already exists'};
44
+ }
45
+
46
+ // console.log(`do not exist? => mkdir ${folderPath}`);
47
+ // Directory doesn't exist, create it
48
+ fs.mkdirSync(folderPath, {recursive: true});
49
+ return {created: true, reason: 'Directory was created'};
50
+ }
51
+
52
+ function writeFiles(name: string | undefined, data: any, config: ArtifactGenerationConfig) {
53
+ const destinations = config.destinations;
54
+ const js = typeof destinations?.js === 'string' ? [destinations?.js] : destinations?.js || [];
55
+ const ts = typeof destinations?.ts === 'string' ? [destinations?.ts] : destinations?.ts || [];
56
+ const json = typeof destinations?.json === 'string' ? [destinations?.json] : destinations?.json || [];
57
+ const jsm = typeof destinations?.jsm === 'string' ? [destinations?.jsm] : destinations?.jsm || [];
58
+ const tsm = typeof destinations?.tsm === 'string' ? [destinations?.tsm] : destinations?.tsm || [];
59
+
60
+ if (ts.length > 0) {
61
+ const newContent = `export default ${JSON.stringify(data, null, 2)} as const;`;
62
+ for (const tsFile of ts) {
63
+ if (tsFile.endsWith('.ts')) {
64
+ if (!name) {
65
+ const filepath = tsFile;
66
+ const folderPath = path.dirname(filepath);
67
+ ensureDirExistsSync(folderPath);
68
+ writeIfDifferent(filepath, newContent);
69
+
70
+ ensureDirExistsSync(`${folderPath}/types`);
71
+ for (const name of Object.keys(data)) {
72
+ const splitted = name.split('/');
73
+ const numPath = splitted.length;
74
+ let pathToBase = '';
75
+ for (let i = 0; i < numPath; i++) {
76
+ pathToBase += '../';
77
+ }
78
+ let lastName = splitted.pop() || name;
79
+ const content = `
80
+ import artifacts from '${pathToBase}${basename(tsFile.replace('.ts', '.js'))}';
81
+ export type Abi_${lastName} = typeof artifacts["${name}"]["abi"];
82
+ `;
83
+ ensureDirExistsSync(dirname(`${folderPath}/types/${name}`));
84
+ writeIfDifferent(`${folderPath}/types/${name}.ts`, content);
85
+ }
86
+ }
87
+ } else {
88
+ if (name) {
89
+ const filepath = `${tsFile}/${name}.ts`;
90
+ const folderPath = path.dirname(filepath);
91
+ ensureDirExistsSync(folderPath);
92
+ writeIfDifferent(filepath, newContent);
93
+ } else {
94
+ let indexFileContent = ``;
95
+
96
+ for (const name of Object.keys(data)) {
97
+ let transformedName = name.replaceAll('/', '_').replaceAll('.', '_');
98
+ indexFileContent += `
99
+ import ${transformedName} from './${name}.js';
100
+ export {${transformedName}};
101
+ export type Abi_${transformedName} = typeof ${transformedName}.abi;
102
+ `;
103
+ }
104
+ writeIfDifferent(`${tsFile}/index.ts`, indexFileContent);
105
+ }
106
+ }
107
+ }
108
+ }
109
+
110
+ if (js.length > 0) {
111
+ const newContent = `export default /** @type {const} **/ (${JSON.stringify(data, null, 2)});`;
112
+ // const dtsContent = `export = ${JSON.stringify(data, null, 2)} as const;`;
113
+ const dtsContent = `declare const _default: ${JSON.stringify(data, null, 2)};export default _default;`;
114
+ // const dtsContent = `declare const _default: ${JSON.stringify(data, null, 2)};export = _default;`;
115
+ const cjsContent = `module.exports = /** @type {const} **/ (${JSON.stringify(data, null, 2)});`;
116
+ for (const jsFile of js) {
117
+ if (jsFile.endsWith('.js')) {
118
+ if (!name) {
119
+ const filepath = jsFile;
120
+ const folderPath = path.dirname(filepath);
121
+ ensureDirExistsSync(folderPath);
122
+ writeIfDifferent(filepath, newContent);
123
+ writeIfDifferent(filepath.replace(/\.js$/, '.d.ts'), dtsContent);
124
+ writeIfDifferent(filepath.replace(/\.js$/, '.cjs'), cjsContent);
125
+ }
126
+ } else {
127
+ if (name) {
128
+ const filepath = `${jsFile}/${name}.js`;
129
+ const folderPath = path.dirname(filepath);
130
+ ensureDirExistsSync(folderPath);
131
+ writeIfDifferent(filepath, newContent);
132
+ writeIfDifferent(filepath.replace(/\.js$/, '.d.ts'), dtsContent);
133
+ writeIfDifferent(filepath.replace(/\.js$/, '.cjs'), cjsContent);
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ if (json.length > 0) {
140
+ const newContent = JSON.stringify(data, null, 2);
141
+ for (const jsonFile of json) {
142
+ if (jsonFile.endsWith('.json')) {
143
+ if (!name) {
144
+ const filepath = jsonFile;
145
+ const folderPath = path.dirname(filepath);
146
+ ensureDirExistsSync(folderPath);
147
+ writeIfDifferent(filepath, newContent);
148
+ }
149
+ } else {
150
+ if (name) {
151
+ const filepath = `${jsonFile}/${name}.json`;
152
+ const folderPath = path.dirname(filepath);
153
+ ensureDirExistsSync(folderPath);
154
+ writeIfDifferent(filepath, newContent);
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ if (!name) {
161
+ if (tsm.length > 0) {
162
+ let newContent = '';
163
+ for (const key of Object.keys(data)) {
164
+ newContent += `export const ${key} = ${JSON.stringify(data[key], null, 2)} as const;`;
165
+ }
166
+ for (const tsFile of tsm) {
167
+ const filepath = tsFile;
168
+ const folderPath = path.dirname(filepath);
169
+ ensureDirExistsSync(folderPath);
170
+ writeIfDifferent(filepath, newContent);
171
+ }
172
+ }
173
+
174
+ if (jsm.length > 0) {
175
+ let newContent = '';
176
+ for (const key of Object.keys(data)) {
177
+ newContent += `export const ${key} = /** @type {const} **/ (${JSON.stringify(data[key], null, 2)});`;
178
+ }
179
+ for (const jsFile of jsm) {
180
+ const filepath = jsFile;
181
+ const folderPath = path.dirname(filepath);
182
+ ensureDirExistsSync(folderPath);
183
+ writeIfDifferent(filepath, newContent);
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ export async function generateTypes(paths: {artifacts: string[]}, config: ArtifactGenerationConfig): Promise<void> {
190
+ const buildInfoCache = new Map<string, any>();
191
+ const allArtifacts: {[name: string]: any} = {};
192
+ const shortNameDict: {[shortName: string]: boolean} = {};
193
+
194
+ for (const artifactsPath of paths.artifacts) {
195
+ const files: FileTraversed[] = traverse(
196
+ artifactsPath,
197
+ [],
198
+ artifactsPath,
199
+ (name) => name != 'build-info' && !name.endsWith('.t.sol') && !name.endsWith('.dbg.json')
200
+ );
201
+
202
+ // console.log('--------------------------');
203
+ // console.log(files);
204
+ // console.log('--------------------------');
205
+
206
+ for (const file of files) {
207
+ const filepath = file.path;
208
+ if (file.directory || !filepath.endsWith('.json')) {
209
+ continue;
210
+ }
211
+ const filename = slash(path.basename(filepath));
212
+ const dirname = slash(path.dirname(file.relativePath));
213
+
214
+ // const namePath = dirname.replace('.sol', '');
215
+ const contractName = filename.replace('.json', '');
216
+ // const shortName = artifact.artifactsEmitted[i];
217
+ // console.log({path: filepath});
218
+ const content = fs.readFileSync(filepath, 'utf-8');
219
+ const parsed = JSON.parse(content);
220
+
221
+ if (!parsed.buildInfoId) continue;
222
+
223
+ // TODO read config for artifacts folder
224
+ let buildInfoFilepath = path.join(artifactsPath, 'build-info', `${parsed.buildInfoId}.output.json`);
225
+
226
+ if (!parsed.buildInfoId) {
227
+ // support hardhat v2 artifacts files
228
+ if (fs.existsSync(filepath.replace('.json', '.dbg.json'))) {
229
+ // console.warn(`Artifact ${filepath} does not have a buildInfoId, but found a .dbg.json file. Using that instead.`);
230
+ const dbgContent = fs.readFileSync(filepath.replace('.json', '.dbg.json'), 'utf-8');
231
+ const dbgParsed = JSON.parse(dbgContent);
232
+ const buildInfoRelativePath = dbgParsed.buildInfo;
233
+ parsed.buildInfoId = path.basename(buildInfoRelativePath, '.json');
234
+ // console.log({buildInfoRelativePath, buildInfoId: parsed.buildInfoId});
235
+ buildInfoFilepath = path.join(artifactsPath, 'build-info', `${parsed.buildInfoId}.json`);
236
+ }
237
+ }
238
+
239
+ // const backupBuildInfoFilepath = path.join(
240
+ // './generated',
241
+ // buildInfoFilepath.slice(buildInfoFilepath.indexOf('/', 1))
242
+ // );
243
+ let buildInfoFilepathToUse = buildInfoFilepath;
244
+ // if (!fs.existsSync(buildInfoFilepathToUse)) {
245
+ // buildInfoFilepathToUse = backupBuildInfoFilepath;
246
+ // }
247
+ let parsedBuildInfo;
248
+ if (!buildInfoCache.has(buildInfoFilepathToUse)) {
249
+ if (!fs.existsSync(buildInfoFilepathToUse)) continue;
250
+ const buildInfoContent = fs.readFileSync(buildInfoFilepathToUse, 'utf-8');
251
+ parsedBuildInfo = JSON.parse(buildInfoContent);
252
+ buildInfoCache.set(buildInfoFilepathToUse, parsedBuildInfo);
253
+ } else {
254
+ parsedBuildInfo = buildInfoCache.get(buildInfoFilepathToUse);
255
+ }
256
+
257
+ const solidityOutput = parsedBuildInfo.output.contracts[parsed.inputSourceName][contractName];
258
+ const hardhatArtifactObject = {...parsed, ...solidityOutput};
259
+ const {buildInfoId, _format, ...artifactObject} = hardhatArtifactObject;
260
+ const fullName = `${dirname}/${contractName}`;
261
+ allArtifacts[fullName] = artifactObject;
262
+ if (shortNameDict[contractName]) {
263
+ delete allArtifacts[contractName];
264
+ } else {
265
+ allArtifacts[contractName] = artifactObject;
266
+ shortNameDict[contractName] = true;
267
+ }
268
+ }
269
+ }
270
+
271
+ for (const key of Object.keys(allArtifacts)) {
272
+ if (key.indexOf('/') >= 0) {
273
+ const split = key.split('/');
274
+ if (split.length > 1) {
275
+ const shortName = split[split.length - 1];
276
+ if (allArtifacts[shortName]) {
277
+ delete allArtifacts[key];
278
+ }
279
+ }
280
+ }
281
+ }
282
+
283
+ for (const key of Object.keys(allArtifacts)) {
284
+ const artifact = allArtifacts[key];
285
+ writeFiles(key, artifact, config);
286
+ }
287
+ // const json = hre.config.generateTypedArtifacts.json || [];
288
+ // json.push('./generated/_artifacts.json');
289
+ // writeFiles(undefined, allArtifacts, {...hre.config.generateTypedArtifacts, json: json});
290
+
291
+ writeFiles(undefined, allArtifacts, config);
292
+ }
package/src/helpers.ts ADDED
@@ -0,0 +1,285 @@
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 {
11
+ Environment,
12
+ UnresolvedUnknownNamedAccounts,
13
+ UnresolvedNetworkSpecificData,
14
+ loadEnvironment,
15
+ enhanceEnvIfNeeded,
16
+ } from 'rocketh';
17
+
18
+ export function setupHardhatDeploy<
19
+ Extensions extends Record<string, (env: Environment<any, any, any>) => any> = {},
20
+ NamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,
21
+ Data extends UnresolvedNetworkSpecificData = UnresolvedNetworkSpecificData
22
+ >(extensions: Extensions) {
23
+ async function loadEnvironmentFromHardhatWithExtensions(
24
+ required: {hre: HardhatRuntimeEnvironment},
25
+ options?: {
26
+ useChainIdOfForkedNetwork?: boolean;
27
+ }
28
+ ) {
29
+ const env = await loadEnvironmentFromHardhat<NamedAccounts, Data>(required, options);
30
+ return enhanceEnvIfNeeded(env, extensions);
31
+ }
32
+
33
+ return {
34
+ loadEnvironmentFromHardhat: loadEnvironmentFromHardhatWithExtensions,
35
+ };
36
+ }
37
+
38
+ export async function loadEnvironmentFromHardhat<
39
+ NamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,
40
+ Data extends UnresolvedNetworkSpecificData = UnresolvedNetworkSpecificData
41
+ >(
42
+ {hre}: {hre: HardhatRuntimeEnvironment},
43
+ options?: {
44
+ useChainIdOfForkedNetwork?: boolean;
45
+ }
46
+ ): Promise<Environment<NamedAccounts, Data>> {
47
+ const connection = await hre.network.connect();
48
+ let provider: any = connection.provider;
49
+ let network: string | {fork: string} = connection.networkName;
50
+ let forkChainId: number | undefined;
51
+ const fork = process.env.HARDHAT_FORK as string | undefined;
52
+ if (fork) {
53
+ if (options?.useChainIdOfForkedNetwork) {
54
+ const forkNetworkConfig = 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
+ network = {
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
+ // console.log(`loading environments...`);
110
+ return loadEnvironment<NamedAccounts, Data>({
111
+ provider,
112
+ network,
113
+ extra: {
114
+ connection,
115
+ },
116
+ });
117
+ }
118
+
119
+ function getVariable(prefix: string, name: string): string | SensitiveString | undefined {
120
+ const variableName = prefix + name;
121
+ let uri = process.env[variableName];
122
+ if (uri === 'SECRET') {
123
+ return configVariable(`SECRET_${variableName}`);
124
+ } else if (uri?.startsWith('SECRET:')) {
125
+ const splitted = uri.split(':');
126
+ if (splitted.length !== 2) {
127
+ throw new Error(`invalid secret uri ${uri}`);
128
+ }
129
+ return configVariable(`SECRET_${prefix + splitted[1]}`);
130
+ }
131
+ return uri;
132
+ }
133
+
134
+ export function getRPC(networkName: string): string | SensitiveString | undefined {
135
+ let uri = getVariable('ETH_NODE_URI_', networkName);
136
+
137
+ if (uri && uri !== '') {
138
+ return uri;
139
+ }
140
+
141
+ uri = process.env.ETH_NODE_URI;
142
+ if (uri) {
143
+ uri = uri.replace('{{networkName}}', networkName);
144
+ }
145
+ if (!uri || uri === '') {
146
+ if (networkName === 'localhost') {
147
+ return 'http://localhost:8545';
148
+ }
149
+ return uri;
150
+ // throw new Error(`no uri specified or for network ${networkName}`);
151
+ }
152
+ if (uri.indexOf('{{') >= 0) {
153
+ throw new Error(`invalid uri or network not supported by node provider : ${uri}`);
154
+ }
155
+
156
+ return uri;
157
+ }
158
+
159
+ export function getMnemonic(networkName?: string): string | SensitiveString {
160
+ if (networkName) {
161
+ const mnemonic = getVariable('MNEMONIC_', networkName);
162
+
163
+ if (mnemonic && mnemonic !== '') {
164
+ return mnemonic;
165
+ }
166
+ }
167
+
168
+ const mnemonic = process.env.MNEMONIC;
169
+ if (!mnemonic || mnemonic === '') {
170
+ return 'test test test test test test test test test test test junk';
171
+ }
172
+ return mnemonic;
173
+ }
174
+
175
+ export function getAccounts(networkName?: string): {mnemonic: string | SensitiveString} {
176
+ return {mnemonic: getMnemonic(networkName)};
177
+ }
178
+
179
+ export function addNetworksFromEnv(networks?: Record<string, NetworkUserConfig>): Record<string, NetworkUserConfig> {
180
+ const newNetworks: Record<string, NetworkUserConfig> = networks ? {...networks} : {};
181
+ const allEnv = Object.keys(process.env);
182
+ for (const envKey of allEnv) {
183
+ if (envKey.startsWith(`ETH_NODE_URI_`) && envKey.length > `ETH_NODE_URI_`.length) {
184
+ const networkName = envKey.slice(`ETH_NODE_URI_`.length);
185
+ const url = getRPC(networkName);
186
+ if (!newNetworks[networkName]) {
187
+ if (url) {
188
+ newNetworks[networkName] = {
189
+ type: 'http',
190
+ url,
191
+ accounts: getAccounts(networkName),
192
+ };
193
+ } else {
194
+ console.error(`no url for network ${networkName}`);
195
+ }
196
+ } else {
197
+ console.error(`duplicated network ${networkName}`);
198
+ }
199
+ }
200
+ }
201
+ return newNetworks;
202
+ }
203
+
204
+ export function populateNetworksFromEnv(
205
+ networks: Record<string, Omit<NetworkUserConfig, 'accounts' | 'url'> | EdrNetworkUserConfig>
206
+ ): Record<string, NetworkUserConfig> {
207
+ const newNetworks: Record<string, NetworkUserConfig> = {};
208
+ for (const networkName of Object.keys(networks)) {
209
+ const network = networks[networkName];
210
+ if (network.type === 'edr-simulated') {
211
+ // we leave memory network alone
212
+ newNetworks[networkName] = network as EdrNetworkUserConfig;
213
+ } else {
214
+ const url = getRPC(networkName);
215
+ if (url) {
216
+ newNetworks[networkName] = {
217
+ ...network,
218
+ url,
219
+ accounts: getAccounts(networkName),
220
+ };
221
+ } else {
222
+ if (!('url' in network) || !network.url) {
223
+ console.error(`no url for network ${networkName}`);
224
+ }
225
+ }
226
+ }
227
+ }
228
+ return newNetworks;
229
+ }
230
+
231
+ export function addForkConfiguration(networks: Record<string, NetworkUserConfig>): Record<string, NetworkUserConfig> {
232
+ const currentNetworkName = process.env.HARDHAT_FORK;
233
+ let forkURL: SensitiveString | string | undefined;
234
+ let hardhatAccounts: EdrNetworkHDAccountsUserConfig | undefined;
235
+ if (
236
+ currentNetworkName &&
237
+ currentNetworkName !== 'hardhat' &&
238
+ currentNetworkName !== 'edr' &&
239
+ currentNetworkName !== 'edr-simulated' &&
240
+ currentNetworkName !== 'memory'
241
+ ) {
242
+ const currentNetwork = networks[currentNetworkName] as HttpNetworkUserConfig;
243
+ if (currentNetwork) {
244
+ if (currentNetwork.type === 'http') {
245
+ forkURL = currentNetwork.url;
246
+ if (
247
+ currentNetwork.accounts &&
248
+ typeof currentNetwork.accounts === 'object' &&
249
+ 'mnemonic' in currentNetwork.accounts
250
+ ) {
251
+ hardhatAccounts = currentNetwork.accounts;
252
+ }
253
+
254
+ // else if (currentNetwork.accounts && Array.isArray(currentNetwork.accounts)) {
255
+ // hardhatAccounts = currentNetwork.accounts.map((v) => ({
256
+ // balance: '10000000000000000000000',
257
+ // privateKey: v,
258
+ // }));
259
+ // }
260
+ }
261
+ }
262
+ }
263
+
264
+ const existingHardhat: EdrNetworkUserConfig =
265
+ networks.hardhat && networks.hardhat.type === 'edr-simulated'
266
+ ? networks.hardhat
267
+ : {type: 'edr-simulated', chainType: 'l1'};
268
+
269
+ const newNetworks: Record<string, NetworkUserConfig> = {
270
+ ...populateNetworksFromEnv(networks),
271
+ hardhat: {
272
+ ...existingHardhat,
273
+ ...{
274
+ accounts: hardhatAccounts || existingHardhat?.accounts,
275
+ forking: forkURL
276
+ ? {
277
+ url: forkURL,
278
+ blockNumber: process.env.HARDHAT_FORK_NUMBER ? parseInt(process.env.HARDHAT_FORK_NUMBER) : undefined,
279
+ }
280
+ : undefined,
281
+ },
282
+ },
283
+ };
284
+ return newNetworks;
285
+ }
@@ -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
+ };
@@ -0,0 +1,33 @@
1
+ import type {HookContext, SolidityHooks} from 'hardhat/types/hooks';
2
+
3
+ import {generateTypes} from '../generate-types.js';
4
+
5
+ export default async (): Promise<Partial<SolidityHooks>> => {
6
+ const handlers: Partial<SolidityHooks> = {
7
+ async onCleanUpArtifacts(
8
+ context: HookContext,
9
+ artifactPaths: string[],
10
+ next: (nextContext: HookContext, artifactPaths: string[]) => Promise<void>
11
+ ) {
12
+ let artifactPathsToProcess = [context.config.paths.artifacts];
13
+ // if (context.config.generateTypedArtifacts.externalArtifacts) {
14
+ // artifactPathsToProcess = artifactPathsToProcess.concat(
15
+ // context.config.generateTypedArtifacts.externalArtifacts
16
+ // );
17
+ // }
18
+
19
+ if (artifactPaths.length > 0) {
20
+ await generateTypes(
21
+ {
22
+ artifacts: artifactPathsToProcess,
23
+ },
24
+ context.config.generateTypedArtifacts
25
+ );
26
+ }
27
+
28
+ return next(context, artifactPaths);
29
+ },
30
+ };
31
+
32
+ return handlers;
33
+ };