Py-solc和solidity导入

时间:2018-05-08 17:07:21

标签: python solidity web3

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

目录结构

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,似乎我需要向compile_source命令传递一些额外的参数。我发现了一些可能有用的文档here,我想我需要使用allow_pathscompile_files。如果我在得到答案之前找到解决方案,我会发布我发现的内容。

1 个答案:

答案 0 :(得分:0)

好的,结果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")])

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