Exemplo n.º 1
0
def get_compiled_registrar_contract():
    if is_solc_03x():
        compiled_contracts = compile_files([REGISTRAR_V3_SOURCE_PATH])
    elif is_solc_04x():
        compiled_contracts = compile_files([REGISTRAR_V4_SOURCE_PATH])
    else:
        raise ValueError(
            "Unsupported version of solc.  Found: {0}.  Only 0.3.x and 0.4.x "
            "are supported".format(get_solc_version())
        )
    contract_data = compiled_contracts['Registrar']
    return contract_data
Exemplo n.º 2
0
def compile_project_contracts(project_dir, contracts_dir, **compiler_kwargs):
    compiler_kwargs.setdefault('output_values', ['bin', 'bin-runtime', 'abi'])
    contract_source_paths = find_project_contracts(project_dir, contracts_dir)
    try:
        compiled_sources = compile_files(contract_source_paths, **compiler_kwargs)
    except ContractsNotFound:
        return contract_source_paths, {}

    return contract_source_paths, compiled_sources
Exemplo n.º 3
0
def validate_solc():
    if get_solc_version() is None:
        raise RuntimeError(
            "Couldn't find the solc in the current $PATH.\n"
            "Make sure the solidity compiler is installed and available on your $PATH.",
        )

    try:
        compile_files(
            [CONTRACT_MANAGER.get_contract_path(CONTRACT_HUMAN_STANDARD_TOKEN)],
            'HumanStandardToken',
            optimize=False,
        )
    except subprocess.CalledProcessError as e:
        msg = (
            'The solidity compiler failed to execute. Please make sure that you\n'
            'are using the binary version of the compiler (solc-js is not compatible)\n'
            'and that the version is >= {}'.format(MIN_REQUIRED_SOLC)
        )

        if e.output:
            msg += (
                '\n'
                'Output: ' + e.output
            )

        raise RuntimeError(msg)

    except OSError as e:
        msg = (
            'The solidity compiler failed to execute. Please make sure the\n'
            'binary is compatible with your architecture and you can execute it.'
        )

        child_traceback = getattr(e, 'child_traceback', None)
        if child_traceback:
            msg += (
                '\n'
                'Traceback: ' + child_traceback
            )

        raise RuntimeError(msg)
Exemplo n.º 4
0
def main(ethereum_net_addr):
    w3 = Web3(Web3.HTTPProvider(ethereum_net_addr))
    w3.eth.defaultAccount = w3.eth.accounts[0]

    print("=== Experiment 2: Voting on Private Ethereum Network ===")

    # Compile the Solidity
    print("Compiling 'voting.sol' ...")
    compiled_sol = compile_files(['voting.sol'])
    contract_interface = compiled_sol['voting.sol:Voting']

    # Get contract object
    voting_contract = w3.eth.contract(abi=contract_interface['abi'],
                                      bytecode=contract_interface['bin'])

    # Deploy the contract and get the address
    print("Deploying contract to network ...")
    tx_hash = voting_contract.constructor(
        [bytes('Alex', 'utf-8'),
         bytes('John', 'utf-8')]).transact()
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print("Deployed voting contract: {}".format(tx_receipt.contractAddress))

    # Get contract instance
    voting = w3.eth.contract(
        address=tx_receipt.contractAddress,
        abi=contract_interface['abi'],
    )

    bytes_john = bytes('John', 'utf-8')
    bytes_alex = bytes('Alex', 'utf-8')

    print("Voting for 'John' ...")
    tx_hash = voting.functions.voteForCandidate(bytes_john).transact()
    w3.eth.waitForTransactionReceipt(tx_hash)

    print("Voting for 'John' ...")
    tx_hash = voting.functions.voteForCandidate(bytes_john).transact()
    w3.eth.waitForTransactionReceipt(tx_hash)

    print("Voting for 'Alex' ...")
    tx_hash = voting.functions.voteForCandidate(bytes_alex).transact()
    w3.eth.waitForTransactionReceipt(tx_hash)

    print("Voting for 'John' ...")
    tx_hash = voting.functions.voteForCandidate(bytes_john).transact()
    w3.eth.waitForTransactionReceipt(tx_hash)

    print("Total votes for 'John': {}".format(
        voting.functions.totalVotesFor(bytes_john).call()))

    print("Total votes for 'Alex': {}".format(
        voting.functions.totalVotesFor(bytes_alex).call()))
Exemplo n.º 5
0
 def compiler_contract(self,contract_file_name, contract_name,contract_args=None,import_remappings=[]):
     '''
     编译合约
     '''
     compiled_sol = compile_files([contract_file_name],import_remappings=import_remappings)
     contract_interface = compiled_sol.get("{}:{}".format(contract_file_name, contract_name))
     bytecode = contract_interface['bin']
     if contract_args:
         args_abi = self.constructor_abi(contract_args[0],contract_args[1])
         if args_abi:
             bytecode += args_abi
     return bytecode
Exemplo n.º 6
0
def compile(tree_depth):
    miximus = "../contracts/roll_up.sol"
    Pairing = "../contracts/Pairing.sol"
    Verifier = "../contracts/Verifier.sol"

    compiled_sol = compile_files([Pairing, Verifier, miximus],
                                 allow_paths="./contracts")

    miximus_interface = compiled_sol[miximus + ':roll_up']
    verifier_interface = compiled_sol[Verifier + ':Verifier']

    return (miximus_interface, verifier_interface)
Exemplo n.º 7
0
def compile(tree_depth):
    miximus = "../contracts/Miximus.sol"
    MerkelTree = "../contracts/MerkelTree.sol"  
    Pairing =  "../contracts/Pairing.sol"
    Verifier = "../contracts/Verifier.sol"

    compiled_sol =  compile_files([Pairing, MerkelTree, Pairing, Verifier, miximus], allow_paths="./contracts")

    miximus_interface = compiled_sol[miximus + ':Miximus']
    verifier_interface = compiled_sol[Verifier + ':Verifier']

    return(miximus_interface, verifier_interface)
Exemplo n.º 8
0
 def compile_contract(self, contract_name: str, libs=None, *args):
     """Compile contract and return JSON containing abi and bytecode"""
     contract_json = compile_files(
         [self.get_contract_path(contract_name)[0]],
         output_values=('abi', 'bin', 'ast'),
         import_remappings=self.get_mappings(),
         optimize=False)
     contract_json = {
         os.path.basename(key).split('.', 1)[0]: value
         for key, value in contract_json.items()
     }
     return contract_json.get(contract_name, None)
Exemplo n.º 9
0
def get_static_or_compile(
        contract_path: str,
        contract_name: str,
        **compiler_flags):
    """Search the path of `contract_path` for a file with the same name and the
    extension `.static-abi.json`. If the file exists, and the recorded checksum
    matches, this will return the precompiled contract, otherwise it will
    compile it.

    Writing compiled contracts to the desired file and path happens only when
    the environment variable `STORE_PRECOMPILED` is set (to whatever value).
    Users are not expected to ever set this value, the functionality is exposed
    through the `setup.py compile_contracts` command.

    Args:
        contract_path: the path of the contract file
        contract_name: the contract name
        **compiler_flags: flags that will be passed to the compiler
    """
    # this will be set by `setup.py compile_contracts`
    store_updated = os.environ.get('STORE_PRECOMPILED', False)
    precompiled = None
    precompiled_path = '{}.static-abi.json'.format(contract_path)
    try:
        with open(precompiled_path) as f:
            precompiled = json.load(f)
    except IOError:
        pass

    if precompiled or store_updated:
        checksum = contract_checksum(contract_path)
    if precompiled and precompiled['checksum'] == checksum:
        return precompiled

    validate_solc()

    compiled = compile_files(
        [contract_path],
        contract_name,
        **compiler_flags
    )

    if store_updated:
        compiled['checksum'] = checksum
        with open(precompiled_path, 'w') as f:
            json.dump(compiled, f)
        print("'{}' written".format(precompiled_path))
    compiled_abi = [
        v for k, v in compiled.items()
        if k.split(':')[1] == contract_name
    ]
    assert len(compiled_abi) == 1
    return compiled_abi[0]
Exemplo n.º 10
0
    def _compile_all_contracts(self) -> None:
        """
        Compile solidity contracts into ABI and BIN. This requires solc somewhere in the $PATH
        and also the :ref:`ethereum.tools` python library.
        """
        if self.contracts_source_dirs is None:
            raise TypeError(
                "Missing contracts source path, can't compile contracts.")

        # Raise an error if solc version goes down.
        self.compare_old_solc_version()

        old_working_dir = Path.cwd()
        chdir(_BASE)

        def relativise(path):
            return path.relative_to(_BASE)

        import_dir_map = [
            '%s=%s' % (k, relativise(v))
            for k, v in self.contracts_source_dirs.items()
        ]
        try:
            for contracts_dir in self.contracts_source_dirs.values():
                res = compile_files(
                    [
                        str(relativise(file))
                        for file in contracts_dir.glob('*.sol')
                    ],
                    output_values=('abi', 'bin', 'bin-runtime', 'ast',
                                   'metadata'),
                    import_remappings=import_dir_map,
                    optimize=False,
                )

                # Strip `ast` part from result
                # TODO: Remove after https://github.com/ethereum/py-solc/issues/56 is fixed
                res = {
                    contract_name: {
                        content_key: content_value
                        for content_key, content_value in
                        contract_content.items() if content_key != 'ast'
                    }
                    for contract_name, contract_content in res.items()
                }
                self.contracts.update(_fix_contract_key_names(res))
        except FileNotFoundError as ex:
            raise ContractManagerCompilationError(
                'Could not compile the contract. Check that solc is available.',
            ) from ex
        finally:
            chdir(old_working_dir)
Exemplo n.º 11
0
def deploy_new_company(company_id):
    """
    Deploy new company contract
    :param company_id: Company off chain id for deploy
    :return: True in case of successful, false otherwise
    """
    try:
        instance = Company.objects.get(pk=company_id)
    except Company.DoesNotExist:
        logger.error(
            'Company with id {} not found, contract will bot be deployed.'.
            format(company_id))
        return False
    else:
        oracle = OracleHandler()
        w3 = utils.get_w3()
        contract_file = 'dapp/contracts/Company.sol'
        compile_sol = compile_files([
            contract_file,
        ],
                                    output_values=(
                                        "abi",
                                        "ast",
                                        "bin",
                                        "bin-runtime",
                                    ))
        create_abi(compile_sol[contract_file + ':Company']['abi'], 'Company')
        obj = w3.eth.contract(
            abi=compile_sol[contract_file + ':Company']['abi'],
            bytecode=compile_sol[contract_file + ':Company']['bin'],
            bytecode_runtime=compile_sol[contract_file +
                                         ':Company']['bin-runtime'],
        )
        args = [
            settings.VERA_COIN_CONTRACT_ADDRESS,
            settings.VERA_ORACLE_CONTRACT_ADDRESS,
        ]
        logger.info('Try to unlock account: {}.'.format(
            oracle.unlockAccount()))
        try:
            txn_hash = obj.deploy(transaction={'from': oracle.account},
                                  args=args)
        except Exception as e:
            logger.warning(
                'Error while deploy new company contract. Company {}: {}'.
                format(company_id, e))
        else:
            logger.info('Lock account: {}'.format(oracle.lockAccount()))
            save_txn.delay(txn_hash.hex(), 'NewCompany',
                           instance.created_by.id, company_id)
            save_txn_to_history.delay(instance.created_by.id, txn_hash.hex(),
                                      'Creation of a new Company contract')
Exemplo n.º 12
0
 def _compile_solidity_file(cls):
     logger.info("Compiling solidity code from solidity file of " +
                 cls.__name__)
     if not cls._contract_name:
         cls._contract_name = cls.__class__.__name__
     file_path = os.path.join(os.getcwd(), cls._solidity_file)
     # Windows dev uncomment below line
     # file_path = cls._solidity_file
     compiled_solidity = compile_files([file_path])
     cls._abi_code = compiled_solidity[file_path + ":" +
                                       cls._contract_name]["abi"]
     cls._byte_code = compiled_solidity[file_path + ":" +
                                        cls._contract_name]["bin"]
Exemplo n.º 13
0
def compile_file():
    output = compile_files(["../rnode.sol"])
    abi = output['../rnode.sol:Rnode']["abi"]
    bin = output['../rnode.sol:Rnode']["bin"]
    print(abi)
    print(bin)
    config = {}
    config["abi"] = abi
    config["bin"] = bin
    print("config: ")
    print(config)

    return config
Exemplo n.º 14
0
def get_compiled_registrar_contract():
    if is_solc_03x():
        registrar_source_path = REGISTRAR_V3_SOURCE_PATH
    elif is_solc_04x():
        registrar_source_path = REGISTRAR_V4_SOURCE_PATH
    else:
        raise ValueError(
            "Unsupported version of solc.  Found: {0}.  Only 0.3.x and 0.4.x "
            "are supported".format(get_solc_version()))
    compiled_contracts = compile_files([registrar_source_path])
    contract_data = compiled_contracts['Registrar']
    normalized_data = normalize_contract_data(contract_data, {})
    return normalized_data
Exemplo n.º 15
0
 def __init__(self):
     """
     Sets up Ethereum interaction variables and compiles the contract, allowing web3 to call functions directly.
     """
     with open('./.blkchnmsg/contract', 'r') as f:
         self.addr = f.readline().strip()
         self.addr_2 = f.readline()
     compiled = compile_files(
         ['./../contract/contracts/BlckChnMsgStorage.sol'])
     compiled_manager = compile_files(
         ["./../contract/contracts/IdentityManager.sol"])
     self.contract_interface = compiled[
         './../contract/contracts/BlckChnMsgStorage.sol:BlckChnMsgStorage']
     self.manager_interface = compiled_manager[
         "./../contract/contracts/IdentityManager.sol:IdentityManager"]
     self.w3 = Web3(HTTPProvider("http://localhost:7545"))
     self.contract = self.w3.eth.contract(
         abi=self.contract_interface['abi'],
         bytecode=self.contract_interface['bin'])
     self.manager_contract = self.w3.eth.contract(
         abi=self.manager_interface['abi'],
         bytecode=self.manager_interface['bin'])
Exemplo n.º 16
0
def init_singletons():
    compiled_sol = compile_files(['review.sol'])

    contract_interface = compiled_sol['review.sol:Reviews']

    w3 = web3.Web3(web3.providers.eth_tester.EthereumTesterProvider()
                   )  # TODO: somehow configure private chain & geth
    w3.eth.enable_unaudited_features()

    contract = w3.eth.contract(abi=contract_interface['abi'],
                               bytecode=contract_interface['bin'])

    return w3, contract, contract_interface
Exemplo n.º 17
0
def deploy_contract(w3, contract_name, account, args=None):
    contract_compiled = compile_files([
        CONTRACT_DIR + contract_name + '.sol'
    ])[CONTRACT_DIR + contract_name + '.sol:' + contract_name]
    contract = w3.eth.contract(abi=contract_compiled['abi'],
                               bytecode=contract_compiled['bin'])

    tx_hash = contract.deploy(args=args, transaction={'from': account})
    tx_receipt = wait_for_transaction_receipt(w3, tx_hash)

    contract_address = tx_receipt['contractAddress']

    return contract_address
Exemplo n.º 18
0
    def compile(self):
        """
        return: (abi, bytecode)
        """
        compiled_sol = compile_files([ContractPath])
        contract_interface = compiled_sol['{}:{}'.format(
            ContractPath, ContractName)]
        contract_interface = compiled_sol['<stdin>:Greeter']

        self._abi = contract_interface['abi']
        self._bytecode = contract_interface['bin']

        return self.abi, self.bytecode
Exemplo n.º 19
0
def validate_solc():
    if get_solc_version() is None:
        raise RuntimeError(
            "Couldn't find the solc in the current $PATH.\n"
            "Make sure the solidity compiler is installed and available on your $PATH.",
        )

    try:
        compile_files(
            [
                CONTRACT_MANAGER.get_contract_path(
                    CONTRACT_HUMAN_STANDARD_TOKEN)
            ],
            'HumanStandardToken',
            optimize=False,
        )
    except subprocess.CalledProcessError as e:
        msg = (
            'The solidity compiler failed to execute. Please make sure that you\n'
            'are using the binary version of the compiler (solc-js is not compatible)\n'
            'and that the version is >= {}'.format(MIN_REQUIRED_SOLC))

        if e.output:
            msg += ('\n' 'Output: ' + e.output)

        raise RuntimeError(msg)

    except OSError as e:
        msg = (
            'The solidity compiler failed to execute. Please make sure the\n'
            'binary is compatible with your architecture and you can execute it.'
        )

        child_traceback = getattr(e, 'child_traceback', None)
        if child_traceback:
            msg += ('\n' 'Traceback: ' + child_traceback)

        raise RuntimeError(msg)
Exemplo n.º 20
0
def compile_drfp_sol():
    CONTRACT_NAME = 'drfp'
    FILE_NAME = CONTRACT_NAME + '.sol'
    PATH = '/truffle/contracts/' + FILE_NAME

    printd('compiling %s...' % (FILE_NAME))
    COMPILED = compile_files([FILE_NAME])
    RFP = COMPILED[FILE_NAME + ':' + CONTRACT_NAME]
    global DRFPContract
    DRFPContract = testrpc.eth.contract(abi=RFP['abi'],
                                        bytecode=RFP['bin'],
                                        bytecode_runtime=RFP['bin-runtime'])

    printd(DRFPContract)
Exemplo n.º 21
0
    def __init__(self, contract_file_name, contract_name):
        compiled_sol = compile_files([contract_file_name])
        contract_interface = compiled_sol['{}:{}'.format(
            contract_file_name, contract_name)]

        contract = w3.eth.contract(
            abi=contract_interface['abi'],
            bytecode=contract_interface['bin'],
            bytecode_runtime=contract_interface['bin-runtime'])
        tx_hash = contract.deploy(transaction={'from': w3.eth.accounts[0]})
        self.mining(2)
        tx_recepit = w3.eth.getTransactionReceipt(tx_hash)
        contract_address = tx_recepit['contractAddress']
        self.contract_instance = contract(contract_address)
Exemplo n.º 22
0
def deploy_n_transact(file_path, mappings=[]):
    # compile all files
    contracts = compile_files(file_path, import_remappings=mappings)
    link_add = {}
    contract_interface, links = separate_main_n_link(file_path, contracts)
    # first deploy all link libraries
    for link in links:
        link_add[link] = deploy_contract(links[link])    
    # now link dependent library code to main contract binary 
    # https://solidity.readthedocs.io/en/v0.4.24/using-the-compiler.html?highlight=library
    if link_add:
        contract_interface['bin'] = link_code(contract_interface['bin'], link_add)    
    # return contract receipt and abi(application binary interface)
    return deploy_contract(contract_interface), contract_interface['abi']
Exemplo n.º 23
0
    def _compile_all_contracts(self) -> Dict:
        """
        Compile solidity contracts into ABI and BIN. This requires solc somewhere in the $PATH
        and also the :ref:`ethereum.tools` python library.  The return value is a dict that
        should be written into contracts.json.
        """
        ret = {}
        old_working_dir = Path.cwd()
        chdir(_BASE)

        def relativise(path: Path) -> Path:
            return path.relative_to(_BASE)

        import_dir_map = [
            "%s=%s" % (k, relativise(v))
            for k, v in self.contracts_source_dirs.items()
        ]
        import_dir_map.insert(
            0, ".=.")  # allow solc to compile contracts in all subdirs
        try:
            for contracts_dir in self.contracts_source_dirs.values():
                res = compile_files(
                    [
                        str(relativise(file))
                        for file in contracts_dir.glob("*.sol")
                    ],
                    output_values=PRECOMPILED_DATA_FIELDS + ["ast"],
                    import_remappings=import_dir_map,
                    optimize=False,
                )

                # Strip `ast` part from result
                # TODO: Remove after https://github.com/ethereum/py-solc/issues/56 is fixed
                res = {
                    contract_name: {
                        content_key: content_value
                        for content_key, content_value in
                        contract_content.items() if content_key != "ast"
                    }
                    for contract_name, contract_content in res.items()
                }
                ret.update(_fix_contract_key_names(res))
        except FileNotFoundError as ex:
            raise ContractSourceManagerCompilationError(
                "Could not compile the contract. Check that solc is available."
            ) from ex
        finally:
            chdir(old_working_dir)
        check_runtime_codesize(ret)
        return ret
Exemplo n.º 24
0
def compile_project_contracts(project, compiler_settings=None):
    logger = logging.getLogger('populus.compilation.compile_project_contracts')

    if compiler_settings is None:
        compiler_settings = {}

    compiler_settings.setdefault('output_values',
                                 DEFAULT_COMPILER_OUTPUT_VALUES)
    logger.debug("Compiler Settings: %s", pprint.pformat(compiler_settings))

    project_contract_source_paths = get_project_source_paths(
        project.contracts_source_dir)
    logger.debug(
        "Found %s project source files: %s",
        len(project_contract_source_paths),
        project_contract_source_paths,
    )

    test_contract_source_paths = get_test_source_paths(project.tests_dir)
    logger.debug(
        "Found %s test source files: %s",
        len(test_contract_source_paths),
        test_contract_source_paths,
    )

    all_source_paths = tuple(
        itertools.chain(
            project_contract_source_paths,
            test_contract_source_paths,
        ))

    try:
        compiled_contracts = compile_files(all_source_paths,
                                           **compiler_settings)
    except ContractsNotFound:
        return all_source_paths, {}

    normalized_compiled_contracts = dict(
        process_compiler_output(contract_name, contract_data)
        for contract_name, contract_data in compiled_contracts.items())

    logger.info("> Found %s contract source files", len(all_source_paths))
    for path in all_source_paths:
        logger.info("  - %s", os.path.relpath(path))

    logger.info("> Compiled %s contracts", len(normalized_compiled_contracts))
    for contract_name in sorted(normalized_compiled_contracts.keys()):
        logger.info("  - %s", contract_name)

    return all_source_paths, normalized_compiled_contracts
Exemplo n.º 25
0
def test_contract_factories(web3):
    from solc import compile_files
    from populus.utils.filesystem import recursive_find_files
    from populus.utils.contracts import (
        package_contracts,
        construct_contract_factories,
    )

    base_tests_dir = os.path.dirname(__file__)

    solidity_source_files = recursive_find_files(base_tests_dir, '*.sol')
    compiled_contracts = compile_files(solidity_source_files)
    test_contract_factories = construct_contract_factories(web3, compiled_contracts)
    return package_contracts(test_contract_factories)
def main():
    if len(sys.argv) != 2:
        sys.stderr.write("usage: " + sys.argv[0] + " dirpath\n")
        sys.stderr.write("dirpath - path with solidity files")
        sys.stderr.write("every solidity file should endswith with .sol")
        exit(1)

    folder_path = sys.argv[1]
    create_folder(folder_path + "/bin")

    for file_name in os.listdir(folder_path):
        if ".sol" not in file_name:
            continue

        log("\n\n\nCompiling file: " + file_name)

        file_path = folder_path + '/' + file_name
        file_solc_version, _, contract_name, _ = file_name.split("--")

        if file_solc_version is None or contract_name is None:
            sys.stderr.write("Bad file name: " + file_name)
            exit(2)

        bin_file_path = "{}/bin/{}--.bin".format(folder_path, file_name[:-6])
        if os.path.exists(bin_file_path):  # Skip if file is compiled
            log("Skipping. File compiled: " + bin_file_path)
            continue

        if file_solc_version not in COMPILER_BIN.keys():
            sys.stderr.write("File has no supported compiler version: " +
                             file_solc_version)
            exit(2)

        solc_path = COMPILER_BIN[file_solc_version]

        log("Compiler version: " + file_solc_version)
        log("File path: " + file_path)
        log("Set env SOLC_BINARY path to: " + solc_path)
        log("Contract name: " + contract_name)

        os.environ["SOLC_BINARY"] = solc_path

        bin_data = solc.compile_files([file_path],
                                      optimize=True)["{}:{}".format(
                                          file_path, contract_name)]["bin"]

        log("Saving bin to: " + bin_file_path)
        with open(bin_file_path, "w") as f:
            f.write(bin_data)
Exemplo n.º 27
0
def regen_artifacts(contracts_directory, artifacts_file):
    starting_directory = os.getcwd()
    os.chdir(contracts_directory)
    # Search and load contract objects from filenames
    contracts = {}
    solc_files = []
    for root, dirs, files in os.walk(os.getcwd()):
        for _file in files:
            if _file.endswith('.sol'):
                solc_files.append(os.path.join(root, _file))
                continue  # No need to process further
            # Vyper contracts are 1 contract per file,
            # and do not have an explicit name,
            # so use base of filename as name
            #if _file.endswith('.vy'):
            #    name = _file.strip('.vy')
            #    with open(os.path.join(root, _file), 'r') as f:
            #        full_code = f.read()
            #    contracts[name] = Contract(full_code, vyper.parser, vyper.compiler)
            #    continue # No need to process further

    # Solidity can have multiple contracts in a file
    # and has no batching functionality,
    # so just create object for every contract
    if solc_files:
        # TODO solc needs to be located in the contracts_directory to work
        results = solc.compile_files(solc_files)
        for name, artifact in results.items():
            # TODO Fix this so it works right with Contract object
            name = name.split(':')[1]
            contracts[name] = Contract(b"", lambda c: c, lambda c: artifact)
            artifact['checksum'] = generate_checksum(b"")
            contracts[name].read_artifacts(artifact)

    # Set artifacts from file (if present)
    if os.path.isfile(artifacts_file):
        with open(artifacts_file, 'r') as f:
            for name, artifacts in json.loads(f.read()).items():
                if name in contracts.keys():
                    contracts[name].read_artifacts(artifacts)

    os.chdir(starting_directory)

    # Once everything is parsed, write it all out again
    artifact_list = [(name, contract.write_artifacts())
                     for name, contract in contracts.items()]
    with open(artifacts_file, 'w') as f:
        artifacts = dict(artifact_list)
        f.write(json.dumps(artifacts))
Exemplo n.º 28
0
def test_contract_factories(web3):
    from solc import compile_files
    from populus.utils.filesystem import recursive_find_files
    from populus.utils.contracts import (
        package_contracts,
        construct_contract_factories,
    )

    base_tests_dir = os.path.dirname(__file__)

    solidity_source_files = recursive_find_files(base_tests_dir, '*.sol')
    compiled_contracts = compile_files(solidity_source_files)
    test_contract_factories = construct_contract_factories(
        web3, compiled_contracts)
    return package_contracts(test_contract_factories)
Exemplo n.º 29
0
 def __init__(self, contract_address, account=None, password=None):
     self.web3 = utils.get_w3()
     self.account = account or settings.WEB_ETH_COINBASE
     self.contract_address = contract_address
     try:
         with open(settings.ABI_PATH + 'Company.abi.json', 'r') as ad:
             self.abi = json.load(ad)
     except FileNotFoundError:
         path = 'dapp/contracts/Company.sol'
         compiled = compile_files([path, ],
                                  output_values=("abi", "ast", "bin", "bin-runtime",))
         with open(settings.ABI_PATH + 'Company.abi.json', 'w+') as ad:
             ad.write(json.dumps(compiled[path + ':Company']['abi']))
             self.abi = compiled[path + ':Company']['abi']
     self.__password = password or settings.COINBASE_PASSWORD_SECRET
     self.contract = self.web3.eth.contract(abi=self.abi, address=self.contract_address)
Exemplo n.º 30
0
def compile_contracts(contract_name: str, alias: str, paths: List[str]) -> str:
    '''
    Compile multiple contracts to bytecode.
    '''
    bin_id = '{0}.sol:{0}'.format(contract_name)
    contract_paths = [
        "{dir}/{alias}{path}".format(dir=V2_PACKAGES,
                                     alias=alias,
                                     path=path[1:]) for path in paths
    ]
    compiled_source = compile_files(contract_paths)
    compiled_source_bin = compiled_source[
        "{dir}/{alias}/contracts/{id}".format(dir=V2_PACKAGES,
                                              alias=alias,
                                              id=bin_id)]['bin']
    return compiled_source_bin
Exemplo n.º 31
0
 def __init__(self, contract_address, account=None):
     self.web3 = Web3(HTTPProvider(settings.NODE_URL))
     self.web3.middleware_stack.inject(geth_poa_middleware, layer=0)
     self.account = account or settings.WEB_ETH_COINBASE
     self.contract_address = contract_address
     self.__password = settings.COINBASE_PASSWORD_SECRET
     try:
         with open(settings.ABI_PATH + 'Candidate.abi.json', 'r') as ad:
             self.abi = json.load(ad)
     except FileNotFoundError:
         path = 'dapp/contracts/Candidate.sol'
         compiled = compile_files([path, ],
                                  output_values=("abi", "ast", "bin", "bin-runtime",))
         with open(settings.ABI_PATH + 'Candidate.abi.json', 'w+') as ad:
             ad.write(json.dumps(compiled[path + ':Candidate']['abi']))
             self.abi = compiled[path + ':Candidate']['abi']
     self.contract = self.web3.eth.contract(abi=self.abi, address=self.contract_address)
Exemplo n.º 32
0
def deploy_contract():
    # get accounts
    accounts = web3.eth.accounts

    # contract stuff
    contract = compile_files(['./dragonstone.sol']).popitem()[1]
    abi = contract.get('abi')
    bytecode = contract.get('bin')
    web3_contract = web3.eth.contract(abi=abi, bytecode=bytecode)
    transaction = {'from': accounts[0], 'gas': 500000}
    trans_hash = web3_contract.deploy(transaction=transaction)
    txn_receipt = web3.eth.getTransactionReceipt(trans_hash)
    contract_address = txn_receipt['contractAddress']
    instance = web3_contract.call({'to': contract_address})
    i = instance.create(accounts[1], 1 * 10**18)
    print(web3.eth.getBalance(accounts[0]))
    print(web3.eth.getBalance(accounts[1]))
Exemplo n.º 33
0
    def compile(self) -> dict:
        """Executes the compiler with parameters specified in the json config"""

        source_paths = set()
        source_walker = os.walk(top=self._solidity_source_dir, topdown=True)
        if self._test_solidity_source_dir:
            test_source_walker = os.walk(top=self._test_solidity_source_dir,
                                         topdown=True)
            source_walker = itertools.chain(source_walker, test_source_walker)

        for root, dirs, files in source_walker:
            for filename in files:
                if filename.endswith('.sol'):
                    source_paths.add(os.path.join(root, filename))

        # Compile with remappings: https://github.com/ethereum/py-solc
        project_root = dirname(self._solidity_source_dir)

        remappings = (
            "contracts={}".format(self._solidity_source_dir),
            "zeppelin={}".format(os.path.join(project_root, 'zeppelin')),
            "proxy={}".format(os.path.join(project_root, 'proxy')),
        )
        try:
            compiled_sol = compile_files(source_files=source_paths,
                                         import_remappings=remappings,
                                         allow_paths=project_root,
                                         optimize=10)
        except FileNotFoundError:
            raise RuntimeError(
                "The solidity compiler is not at the specified path. "
                "Check that the file exists and is executable.")
        except PermissionError:
            raise RuntimeError(
                "The solidity compiler binary at {} is not executable. "
                "Check the file's permissions.".format(self.__sol_binary_path))

        except SolcError:
            raise

        # Cleanup the compiled data keys
        interfaces = {
            name.split(':')[-1]: compiled_sol[name]
            for name in compiled_sol
        }
        return interfaces
Exemplo n.º 34
0
    def get_compiled_contract_data(self, source_file_paths, import_remappings):
        self.logger.debug("Compiler Settings: %s", pprint.pformat(self.compiler_settings))

        try:
            compiled_contracts = compile_files(source_file_paths, **self.compiler_settings)
        except ContractsNotFound:
            return {}

        normalized_compiled_contracts = dict(
            (
                _get_contract_name(name_from_compiler),
                _normalize_combined_json_contract_data(data_from_compiler),
            )
            for name_from_compiler, data_from_compiler
            in compiled_contracts.items()
        )

        return normalized_compiled_contracts
def test_contract_factories(project):
    from solc import compile_files
    from populus.utils.filesystem import (
        recursive_find_files,
    )
    from populus.compilation import (
        find_project_contracts,
    )

    base_tests_dir = os.path.dirname(__file__)

    test_source_files = [
        os.path.relpath(source_path, project.project_dir)
        for source_path in recursive_find_files(base_tests_dir, 'Test*.sol')
    ]
    all_source_files = test_source_files + list(find_project_contracts(
        project.project_dir, project.contracts_dir,
    ))
    compiled_contracts = compile_files(all_source_files)
    for contract_name, contract_data in compiled_contracts.items():
        project.compiled_contracts.setdefault(contract_name, contract_data)
Exemplo n.º 36
0
def compile_files_cwd(*args, **kwargs):
    """change working directory to contract's dir in order to avoid symbol
    name conflicts"""
    # get root directory of the contracts
    compile_wd = os.path.commonprefix(args[0])
    # edge case - compiling a single file
    if os.path.isfile(compile_wd):
        compile_wd = os.path.dirname(compile_wd)
    # remove prefix from the files
    if compile_wd[-1] is not '/':
        compile_wd += '/'
    file_list = [
        x.replace(compile_wd, '')
        for x in args[0]
    ]
    cwd = os.getcwd()
    try:
        os.chdir(compile_wd)
        compiled_contracts = compile_files(file_list, **kwargs)
    finally:
        os.chdir(cwd)
    return compiled_contracts
def test_source_files_compilation(contracts_dir):
    SOURCE = "contract Foo { function Foo() {} function return13() returns (uint) { return 13; } }"

    source_file_path = os.path.join(contracts_dir, 'Foo.sol')
    with open(source_file_path, 'w') as source_file:
        source_file.write(SOURCE)

    output = compile_files([source_file_path])

    assert output
    assert 'Foo' in output

    foo_contract_data = output['Foo']
    assert 'code' in foo_contract_data
    assert 'code_runtime' in foo_contract_data
    assert 'source' in foo_contract_data
    assert 'meta' in foo_contract_data
    assert 'compilerVersion' in foo_contract_data['meta']

    # TODO: figure out how to include source.
    assert foo_contract_data['source'] is None
    assert foo_contract_data['meta']['compilerVersion'] == get_solc_version()
Exemplo n.º 38
0
    def get_compiled_contracts(self, source_file_paths, import_remappings):
        self.logger.debug("Import remappings: %s", import_remappings)
        self.logger.debug("Compiler Settings: %s", pprint.pformat(self.compiler_settings))

        if 'import_remappings' in self.compiler_settings and import_remappings is not None:
            self.logger.warn("Import remappings setting will be overridden by backend settings")

        try:
            compilation_result = compile_files(
                source_file_paths,
                import_remappings=import_remappings,
                **self.compiler_settings
            )
        except ContractsNotFound:
            return {}

        compiled_contracts = pipe(
            compilation_result,
            normalize_compilation_result,
            post_process_compiled_contracts,
        )

        return compiled_contracts
Exemplo n.º 39
0
def test_compile_empty_folder():
    """Execute compile on a folder without contracts."""

    with pytest.raises(ContractsNotFound):
        compile_files([])