I have ERC20 contracts with imports and solc is not able to compile contracts with imports. I have tried truffle compile and it works fine and generates ABI. I want to fetch smart contract file ABI by compiling it programmatically (without using terminal). What is the best way of doing it?

2 Answers 2


There are tools like Truffle and Hardhat, but sometimes they can be finicky with solc version.

There is the main npm package 'solc'. You can install it locally like any other node package. Then write a .js script which uses the package's features, like below:

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

const contractPath = path.resolve(__dirname, "contracts", "MyContract.sol");
const source = fs.readFileSync(contractPath, "utf8");
let compileOutput = solc.compile(source, 1)

I included the 'path' variable to show you the solidity files can be stored anywhere; in this case according to the code they should be in a folder called 'contracts' at the same level where you're executing this javascript.

|-- contracts/
  \-- MyContract.sol

Important: Solidity changes fairly often, and the structure of the object 'compileOutput' that gets dumped by the solc.compile() function has changed, I believe. However, it should contain a 'contracts' key that will allow you to retrieve the bytecode and ABI (interface).

These sub-objects can be saved or used in front-end code, or you can 'export' them and chain your compile script into your deploy script. By importing your compile script at the beginning of your deployment, you get an up to date version of the ABI and bytecode, because the compile script will be run, and the exports / imports pass along any objects from the compile output you want to use.

Run with node.

node compile.js


Its the code to get ABI, bytecode, contract-name of solidity contract, here solidity codes are stored in a variable contract:-

var solc = require('solc');

var contract=`
    pragma solidity ^0.8.0;
    contract hello{
       string public hii='hello world';
       function update(string memory message) public{hii=message;}

var input = {
  language: 'Solidity',
  sources: {'test.sol': {content: contract}},
  settings: {outputSelection: {'*': {'*': ['*']}}}

var output = JSON.parse(solc.compile(JSON.stringify(input)));

for (var contractName in output.contracts['test.sol']) {
    console.log('contractName: ',contractName)
    console.log('bytecode: ',output.contracts['test.sol'][contractName].evm.bytecode.object )
    console.log('abi :', output.contracts['test.sol'][contractName].abi)

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.