2

I have been using the Hardhat environment for a while now, and every time I have to provide the ABI to the front-end team, I need to copy-paste the ABI manually from the JSON file, since it contains other useless values which they don't need.

{
  "_format": "hh-sol-artifact-1",
  "contractName": "Test",
  "sourceName": "contracts/Test.sol",
  "abi": [...]
}

So, my question is if there is a script that I can use that extracts the ABI part automatically, and create separate files for these just ABIs? Not sure if the question is relevant, but just wanted to try something that can make our lives easier. Thanks in advance.

1
  • Javascript questions are not part of Ethereum
    – Nulik
    Commented Feb 10, 2023 at 14:09

2 Answers 2

2

I created a code to extract the ABIs from the artifacts and copy them into a new folder. Let me know if there is a simpler solution:

const extractAbi = async () => {
  const mainFolder = "artifacts/contracts/";
  fs.readdirSync(mainFolder).forEach((folder) => {
    if (folder.includes(".sol")) {
      const absolutePath = mainFolder + folder + "/";

      fs.readdirSync(absolutePath).forEach((file: any) => {
        if (!file.includes(".dbg.json")) {
          const finalPath = absolutePath + file;
          const parentDirectory = __dirname.substr(
            0,
            __dirname.lastIndexOf("/")
          );
          const abiFolder = parentDirectory + "/abis";

          try {
            if (!fs.existsSync(abiFolder)) {
              fs.mkdirSync(abiFolder);
            }
          } catch (err) {
            console.error(err);
          }

          let data: any = fs.readFileSync(finalPath);

          fs.writeFileSync(
            `abis/${file}`,
            JSON.stringify(JSON.parse(data).abi)
          );
        }
      });
    }
  });
};
0

A great package to use is hardhat-deploy, which creates deployment objects for each deployed contract. These objects contain the abi and the address of any deployed contract and you can export them to json.

1
  • Thanks for the answer. Though I am not able to implement it and get the solution. Can you tell me some more? Commented Feb 10, 2023 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.