Ejemplo n.º 1
0
def get_abi(contract_source: str, name: str) -> Dict:
    """
    Given a contract source and name, returns a dict of {name: abi}

    This function is deprecated in favor of `brownie.project.compiler.get_abi`
    """
    input_json = {
        "language": "Vyper",
        "sources": {
            name: {
                "content": contract_source
            }
        },
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi"]
                }
            }
        },
    }
    if _active_version == Version(vyper.__version__):
        try:
            compiled = vyper_json.compile_json(input_json)
        except VyperException as exc:
            raise exc.with_traceback(None)
    else:
        try:
            compiled = vvm.compile_standard(input_json,
                                            vyper_version=_active_version)
        except vvm.exceptions.VyperError as exc:
            raise CompilerError(exc, "vyper")

    return {name: compiled["contracts"][name][name]["abi"]}
Ejemplo n.º 2
0
def compile_from_input_json(
    input_json: Dict, silent: bool = True, allow_paths: Optional[str] = None
) -> Dict:

    """
    Compiles contracts from a standard input json.

    Args:
        input_json: solc input json
        silent: verbose reporting
        allow_paths: compiler allowed filesystem import path

    Returns: standard compiler output json
    """

    optimizer = input_json["settings"]["optimizer"]
    input_json["settings"].setdefault("evmVersion", None)
    if input_json["settings"]["evmVersion"] in EVM_EQUIVALENTS:
        input_json["settings"]["evmVersion"] = EVM_EQUIVALENTS[input_json["settings"]["evmVersion"]]

    if not silent:
        print(f"Compiling contracts...\n  Solc version: {str(solcx.get_solc_version())}")

        opt = f"Enabled  Runs: {optimizer['runs']}" if optimizer["enabled"] else "Disabled"
        print(f"  Optimizer: {opt}")

        if input_json["settings"]["evmVersion"]:
            print(f"  EVM Version: {input_json['settings']['evmVersion'].capitalize()}")

    try:
        return solcx.compile_standard(input_json, allow_paths=allow_paths,)
    except solcx.exceptions.SolcError as e:
        raise CompilerError(e, "solc")
Ejemplo n.º 3
0
def compile_from_input_json(input_json: Dict,
                            silent: bool = True,
                            allow_paths: Optional[str] = None) -> Dict:
    """
    Compiles contracts from a standard input json.

    Args:
        input_json: vyper input json
        silent: verbose reporting
        allow_paths: compiler allowed filesystem import path

    Returns: standard compiler output json
    """

    version = get_version()
    if not silent:
        print("Compiling contracts...")
        print(f"  Vyper version: {version}")
    if version < Version("0.1.0-beta.17"):
        outputs = input_json["settings"]["outputSelection"]["*"]["*"]
        outputs.remove("userdoc")
        outputs.remove("devdoc")
    if version == Version(vyper.__version__):
        try:
            return vyper_json.compile_json(input_json, root_path=allow_paths)
        except VyperException as exc:
            raise exc.with_traceback(None)
    else:
        try:
            return vvm.compile_standard(input_json,
                                        base_path=allow_paths,
                                        vyper_version=version)
        except vvm.exceptions.VyperError as exc:
            raise CompilerError(exc, "vyper")
Ejemplo n.º 4
0
def compile_from_input_json(input_json, silent=True):
    '''Compiles contracts from a standard input json.

    Args:
        input_json: solc input json
        silent: verbose reporting

    Returns: standard compiler output json'''
    optimizer = input_json['settings']['optimizer']
    input_json['settings'].setdefault('evmVersion', None)
    if not silent:
        print("Compiling contracts...")
        print(f"  Solc {solcx.get_solc_version_string()}")
        print("  Optimizer: " + (f"Enabled  Runs: {optimizer['runs']}"
                                 if optimizer['enabled'] else 'Disabled'))
        if input_json['settings']['evmVersion']:
            print(
                f"  EVM Version: {input_json['settings']['evmVersion'].capitalize()}"
            )
    try:
        return solcx.compile_standard(
            input_json,
            optimize=optimizer['enabled'],
            optimize_runs=optimizer['runs'],
            evm_version=input_json['settings']['evmVersion'],
            allow_paths=".")
    except solcx.exceptions.SolcError as e:
        raise CompilerError(e)
Ejemplo n.º 5
0
def compile_from_input_json(input_json: Dict, silent: bool = True) -> Dict:
    """Compiles contracts from a standard input json.

    Args:
        input_json: solc input json
        silent: verbose reporting

    Returns: standard compiler output json"""
    optimizer = input_json["settings"]["optimizer"]
    input_json["settings"].setdefault("evmVersion", None)
    if not silent:
        print("Compiling contracts...")
        print(f"  Solc {solcx.get_solc_version_string()}")
        print("  Optimizer: " + (f"Enabled  Runs: {optimizer['runs']}"
                                 if optimizer["enabled"] else "Disabled"))
        if input_json["settings"]["evmVersion"]:
            print(
                f"  EVM Version: {input_json['settings']['evmVersion'].capitalize()}"
            )
    try:
        return solcx.compile_standard(
            input_json,
            optimize=optimizer["enabled"],
            optimize_runs=optimizer["runs"],
            evm_version=input_json["settings"]["evmVersion"],
            allow_paths=".",
        )
    except solcx.exceptions.SolcError as e:
        raise CompilerError(e)
Ejemplo n.º 6
0
def _compile_and_format(input_json):
    try:
        compiled = solcx.compile_standard(
            input_json,
            optimize=CONFIG['solc']['optimize'],
            optimize_runs=CONFIG['solc']['runs'],
            allow_paths="."
        )
    except solcx.exceptions.SolcError as e:
        raise CompilerError(e)
    compiled = generate_pcMap(compiled)
    result = {}
    compiler_info = CONFIG['solc'].copy()
    compiler_info['version'] = solcx.get_solc_version_string().strip('\n')
    for filename in input_json['sources']:
        for match in re.findall(
            "\n(?:contract|library|interface) [^ {]{1,}",
            input_json['sources'][filename]['content']
        ):
            type_, name = match.strip('\n').split(' ')
            data = compiled['contracts'][filename][name]
            evm = data['evm']
            ref = [
                (k, x) for v in evm['bytecode']['linkReferences'].values()
                for k, x in v.items()
            ]
            for n, loc in [(i[0], x['start']*2) for i in ref for x in i[1]]:
                evm['bytecode']['object'] = "{}__{:_<36}__{}".format(
                    evm['bytecode']['object'][:loc],
                    n[:36],
                    evm['bytecode']['object'][loc+40:]
                )
            result[name] = {
                'abi': data['abi'],
                'ast': compiled['sources'][filename]['ast'],
                'bytecode': evm['bytecode']['object'],
                'compiler': compiler_info,
                'contractName': name,
                'deployedBytecode': evm['deployedBytecode']['object'],
                'deployedSourceMap': evm['deployedBytecode']['sourceMap'],
                'networks': {},
                'opcodes': evm['deployedBytecode']['opcodes'],
                'sha1': sha1(input_json['sources'][filename]['content'].encode()).hexdigest(),
                'source': input_json['sources'][filename]['content'],
                'sourceMap': evm['bytecode']['sourceMap'],
                'sourcePath': filename,
                'type': type_,
                'pcMap': evm['deployedBytecode']['pcMap']
            }
    return result
Ejemplo n.º 7
0
def compile_from_input_json(input_json, silent=True):
    '''Compiles contracts from a standard input json.

    Args:
        input_json: solc input json
        silent: verbose reporting

    Returns: standard compiler output json'''
    optimizer = input_json['settings']['optimizer']
    if not silent:
        print("Compiling contracts...")
        print("Optimizer: " + (f"Enabled  Runs: {optimizer['runs']}"
                               if optimizer['enabled'] else 'Disabled'))
    try:
        return solcx.compile_standard(input_json,
                                      optimize=optimizer['enabled'],
                                      optimize_runs=optimizer['runs'],
                                      allow_paths=".")
    except solcx.exceptions.SolcError as e:
        raise CompilerError(e)