10

I have to update my front-end file with deployed latest ABI in json format. I am using following code in my deploy script (Run after the original smart contract is deployed)

import { DeployFunction } from "hardhat-deploy/types";
import { HardhatRuntimeEnvironment } from "hardhat/types";
import fs from "fs";


const updateUI: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
    const { network, ethers } = hre;
    
    console.log("Writing to front end...");
    
    //Updating ABI on front end JSON file
    const frontEndAbiFile = "path/to/store/abi.json";
    const fundme = await ethers.getContract("FundMe"); //already deployed contract on hardhat/rinkeby
    //I want to get the ABI here so that I can write and save it to frontEndAbiFile location.
    fs.writeFileSync(frontEndAbiFile, 'How shoud I get ABI in json?' );
    
};

export default updateUI;

How I can get ABI in json format FundMe contract? Please read the comments in my above code. Note:I am using TypeScript.

1

5 Answers 5

6

If you are deploying by command line, you can read from the file where is previously builded, in the case of hardhat there is a example:

const fs = require("fs")
const path = require("path")

const getTheAbi = () => {
  try {
    const dir = path.resolve(
      __dirname,
      "./artifacts/contracts/HelloWorld.sol/HelloWorld.json"
    )
    const file = fs.readFileSync(dir, "utf8")
    const json = JSON.parse(file)
    const abi = json.abi
    console.log(`abi`, abi)

    return abi
  } catch (e) {
    console.log(`e`, e)
  }
}
1
  • What is the option to get the ABI of already deployed contract on the mainnet?
    – VitoCK
    Jul 4, 2023 at 8:46
2

you can skip ABI to get contract instance directly:

const contractInstance = await ethers.getContractAt("contracts/XYZ.sol:ContractName", contractAddress);
1
fs.writeFileSync(
    frontEndAbiFile,

    fundme.interface.format(ethers.utils.FormatTypes.json)
)

When you deploy, this will update your front-end file.

0

it should be in a project folder like artifacts/contracts/FundMe/FundMe.json

or on remix

contracts/artifacts/

2
  • I am developing locally using hardhat not on remix.
    – SanjayDefi
    Jul 8, 2022 at 14:58
  • good stuff, in which case please refer to the first part of the answer. that's the location in a hardhat proj
    – sola24
    Jul 9, 2022 at 9:25
0

You can use the built-in method readArtifact

const hre = require('hardhat') or import * as hre from 'hardhat';

const myContractArtifact = await hre.artifacts.readArtifact('MyContract');

const {bytecode, abi} = myContractArtifact;

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.