How can I compile solidity files which perform relative imports through py-solc
? Here's a minimal example:
Directory structure
my-project - main.py - bar.sol - baz.sol
main.py:
from solc import compile_source def get_contract_source(file_name): with open(file_name) as f: return f.read() contract_source_code = get_contract_source("bar.sol") compiled_sol = compile_source(contract_source_code) # Compiled source code
baz.sol:
pragma solidity ^0.4.0; contract baz { function baz(){ } }
bar.sol:
pragma solidity ^0.4.0; import "./baz" as baz; contract bar { function bar(){ } }
When I try to run the python file I get the following error:
solc.exceptions.SolcError: An error occurred during execution > command: `solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc` > return code: `1` > stderr: > stdout: :17:1: Error: Source "baz" not found: File outside of allowed directories. import "./baz" as baz; ^----------------------^
I'm still not 100% clear on how imports work. I've reviewed the docs and it seems like I need to pass some extra arguments to the compile_source
command. I've found some potentially useful docs here and I think I need to play around with allow_paths
or compile_files
which I will. If I find a solution before I get an answer I will post what I find.
Ok, turns out compile_files
is exactly what I need.
The new compile command is
import os PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) compiled_sol = compile_files([os.path.join(self.PROJECT_ROOT, "bar.sol"), os.path.join(self.PROJECT_ROOT, "baz.sol")])
and it turns out my import was wrong. I need to import baz
like import "./baz.sol" as baz;
- I was missing the .sol
extension.