|
| 1 | +const fs = require('fs') |
| 2 | +const path = require('path') |
| 3 | +const { extendConfig } = require('hardhat/config') |
| 4 | + |
| 5 | +const { HardhatPluginError } = require('hardhat/plugins') |
| 6 | + |
| 7 | +const { |
| 8 | + TASK_COMPILE, |
| 9 | +} = require('hardhat/builtin-tasks/task-names') |
| 10 | + |
| 11 | +extendConfig(function (config, userConfig) { |
| 12 | + config.abiExporter = Object.assign( |
| 13 | + { |
| 14 | + path: './abi', |
| 15 | + clear: false, |
| 16 | + flat: false, |
| 17 | + only: [], |
| 18 | + except: [], |
| 19 | + spacing: 2, |
| 20 | + }, |
| 21 | + userConfig.abiExporter, |
| 22 | + ) |
| 23 | +}) |
| 24 | + |
| 25 | +task(TASK_COMPILE, async function (args, hre, runSuper) { |
| 26 | + const config = hre.config.abiExporter |
| 27 | + |
| 28 | + await runSuper() |
| 29 | + |
| 30 | + const outputDirectory = path.resolve(hre.config.paths.root, config.path) |
| 31 | + |
| 32 | + if (!outputDirectory.startsWith(hre.config.paths.root)) { |
| 33 | + throw new HardhatPluginError('resolved path must be inside of project directory') |
| 34 | + } |
| 35 | + |
| 36 | + if (outputDirectory === hre.config.paths.root) { |
| 37 | + throw new HardhatPluginError('resolved path must not be root directory') |
| 38 | + } |
| 39 | + |
| 40 | + if (config.clear) { |
| 41 | + if (fs.existsSync(outputDirectory)) { |
| 42 | + fs.rmdirSync(outputDirectory, { recursive: true }) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + if (!fs.existsSync(outputDirectory)) { |
| 47 | + fs.mkdirSync(outputDirectory, { recursive: true }) |
| 48 | + } |
| 49 | + |
| 50 | + for (const fullName of await hre.artifacts.getAllFullyQualifiedNames()) { |
| 51 | + if (config.only.length && !config.only.some(m => fullName.match(m))) continue |
| 52 | + if (config.except.length && config.except.some(m => fullName.match(m))) continue |
| 53 | + |
| 54 | + const { abi, sourceName, contractName, bytecode, deployedBytecode } = await hre.artifacts.readArtifact(fullName) |
| 55 | + |
| 56 | + if (!abi.length) continue |
| 57 | + |
| 58 | + const destination = path.resolve( |
| 59 | + outputDirectory, |
| 60 | + config.flat ? '' : sourceName, |
| 61 | + contractName, |
| 62 | + ) + '.json' |
| 63 | + |
| 64 | + if (!fs.existsSync(path.dirname(destination))) { |
| 65 | + fs.mkdirSync(path.dirname(destination), { recursive: true }) |
| 66 | + } |
| 67 | + |
| 68 | + fs.writeFileSync(destination, `${JSON.stringify({ abi, bytecode, deployedBytecode }, null, config.spacing)}\n`, { flag: 'w' }) |
| 69 | + } |
| 70 | +}) |
0 commit comments