Solidity Tutorial – How to Include One Solidity File into Another

solcsolidity

I completely stuck on modules importing into Solidity contract. Here is my files/directory layout:

.
|-> contracts/
  |-> contract1.sol
  |-> contract2.sol

File contract1.sol contains only pragma and import statements like:

pragma solidity ^0.4.0;
import "./contract2" as c2;

File contract2.sol conntains only pragma statement:

pragma solidity ^0.4.0;

Then I open node shell and input following code:

> solc = require('solc')
> solc.compile(fs.readFileSync('contracts/contract1.sol').toString())
{ contracts: {},
  errors: [ ':3:1: ParserError: Source "contract2" not found: File not supplied initially.\nimport "./contract2" as c2;\n^-------------------------^\n' ],
  sourceList: [ '' ],
  sources: {} }

I already tried to:

  • specify full path in contract1.sol
  • add extension .sol
  • remove ./contracts/ prefix and run commands inside contracts folder.

Nothing works. Accordingly to this article begin import with dot and slash is enough but, damn, no!

How to include one sol file into another?
Node version is 8.1.13, solcjs version is 0.4.13+commit.0fb4cb1a.Emscripten.clang

Best Answer

I deployed a contract using web3js sometime back and I faced the similar problem, I fixed it by defining all dependent contract in an input object and then compiled it.

You can take a look at this code for reference -

https://gist.github.com/inovizz/1fdc2af0182584b90008e0cf2895554c

Hope this helps.