Py-solc 和 solidity 导入

Py-solc and solidity imports

如何编译通过 py-solc 执行相对导入的 solidity 文件?这是一个最小的例子:

目录结构

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(){

    }
}

当我尝试 运行 python 文件时,出现以下错误:

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;
^----------------------^

我仍然不是 100% 清楚导入的工作原理。我有 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,我想我需要玩玩 allow_pathscompile_files,我会的。如果我在得到答案之前找到解决方案,我会 post 我找到的。

好的,事实证明 compile_files 正是我需要的。

新的编译命令是

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")])

事实证明我的导入是错误的。我需要像 import "./baz.sol" as baz; 一样导入 baz - 我缺少 .sol 扩展名。