forked from ItsNickBarry/hardhat-abi-exporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
78 lines (59 loc) · 2.13 KB
/
index.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
const fs = require('fs');
const path = require('path');
const { extendConfig } = require('hardhat/config');
const { HardhatPluginError } = require('hardhat/plugins');
const {
TASK_COMPILE,
} = require('hardhat/builtin-tasks/task-names');
extendConfig(function (config, userConfig) {
config.abiExporter = Object.assign(
{
path: './abi',
clear: false,
flat: false,
only: [],
except: [],
spacing: 2
},
userConfig.abiExporter
);
});
task(TASK_COMPILE, async function (args, hre, runSuper) {
const config = hre.config.abiExporter;
await runSuper();
const outputDirectory = path.resolve(hre.config.paths.root, config.path);
if (!outputDirectory.startsWith(hre.config.paths.root)) {
throw new HardhatPluginError('resolved path must be inside of project directory');
}
if (outputDirectory === hre.config.paths.root) {
throw new HardhatPluginError('resolved path must not be root directory');
}
if (config.clear) {
fs.rmdirSync(outputDirectory, { recursive: true });
}
if (!fs.existsSync(outputDirectory)) {
fs.mkdirSync(outputDirectory, { recursive: true });
}
for (let fullName of await hre.artifacts.getAllFullyQualifiedNames()) {
if (config.only.length && !config.only.some(m => fullName.match(m))) continue;
if (config.except.length && config.except.some(m => fullName.match(m))) continue;
const { abi, sourceName, contractName } = await hre.artifacts.readArtifact(fullName);
console.log(`Exported ${ contractName }`);
if (!abi.length) continue;
const destination = path.resolve(
outputDirectory,
config.flat ? '' : sourceName,
contractName
) + '.json';
if (!fs.existsSync(path.dirname(destination))) {
fs.mkdirSync(path.dirname(destination), { recursive: true });
}
fs.writeFileSync(destination, `${ JSON.stringify(abi, null, config.spacing) }\n`, { flag: 'w' });
const abiJs = path.resolve(
outputDirectory,
config.flat ? '' : sourceName,
contractName
) + '.js';
fs.writeFileSync(abiJs, `export default ${ JSON.stringify(abi, null, config.spacing) };\n`, { flag: 'w' });
}
});