Haoliang Yu
Haoliang Yu

Reputation: 3097

Compile solidity with solc-js but get empty result

I try to compile the following contract (tested on remix) with solc-js

pragma solidity ^0.4.21;

contract Calculator {
    uint8 public result = 0;

    function add(uint8 value) public {
        result = result + value;
    }
}

This is the code I am using

const { readFileSync } = require('fs');
const solc = require('solc');
const Web3 = require('web3');

// connect to the local instance
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const params = {
  language: "Solidity",
  sources: {
    'example': {
      content: readFileSync('./contracts/example.sol', 'utf-8')
    }
  }
};

const compiled = JSON.parse(solc.compileStandardWrapper(JSON.stringify(params)));

// check the result
console.log(compiled);

I follow the instruction from the solc repo and the compiler input JSON spec. It works without any error but the result is very empty

{
  "contracts": {
    "example": {
      "Calculator": {
        "evm": {}
      }
    }
  },
  "sources": {
    "example": {
      "id": 0
    }
  }
}

It doesn't have a lot of content as described at the output description. I am not sure what goes wrong in my code.

Upvotes: 2

Views: 1823

Answers (1)

Adam Kipnis
Adam Kipnis

Reputation: 10981

You need to tell solc-js what you want included in the output response. By default, it only compiles and reports errors. From the Input/Output JSON description (in the settings section):

// The following can be used to select desired outputs.

// If this field is omitted, then the compiler loads and does type checking, but will not generate any outputs apart from errors.

For example, to output the abi and bytecode, your input should be

const params = {
    language: "Solidity",
    sources: {
      "example": {
        content: readFileSync('./contracts/example.sol', 'utf-8')
      }
    },
    settings: {
      outputSelection: {
        "*": {
          "*": [ "abi", "evm.bytecode" ]
        }
      }
    }
};

The available options for outputSelection include:

abi - ABI
ast - AST of all source files
legacyAST - legacy AST of all source files
devdoc - Developer documentation (natspec)
userdoc - User documentation (natspec)
metadata - Metadata
ir - New assembly format before desugaring
evm.assembly - New assembly format after desugaring
evm.legacyAssembly - Old-style assembly format in JSON
evm.bytecode.object - Bytecode object
evm.bytecode.opcodes - Opcodes list
evm.bytecode.sourceMap - Source mapping (useful for debugging)
evm.bytecode.linkReferences - Link references (if unlinked object)
evm.deployedBytecode* - Deployed bytecode (has the same options as evm.bytecode)
evm.methodIdentifiers - The list of function hashes
evm.gasEstimates - Function gas estimates
ewasm.wast - eWASM S-expressions format (not supported atm)
ewasm.wasm - eWASM binary format (not supported atm)

Upvotes: 2

Related Questions