Esempio n. 1
0
def compile_contract(bidding_time=10, reveal_time=15):
    global Auction
    # compile all contract files
    sol_contracts = compile_files([SOL_PATH])
    contract = sol_contracts[SOL_PATH + ':' + CONTRACT_NAME]
    # separate main file and link file
    Auction = w3.eth.contract(abi=contract['abi'], bytecode=contract['bin'])

    # Get transaction hash from deployed contract
    w3.eth.default_account = w3.eth.accounts[0]
    tx_hash = Auction.constructor(bidding_time, reveal_time,
                                  SELLER_ADDRESS).transact(
                                      {'from': w3.eth.accounts[0]})
    # Get tx receipt to get contract address
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    # print("hash ", tx_hash)
    # print("rec ", tx_receipt)
    print("contract ", tx_receipt['contractAddress'])
    return (Auction, tx_receipt['contractAddress'])
Esempio n. 2
0
def compile_contract():
    # compile all contract files
    sol_contracts = compile_files([SOL_PATH])
    # print(sol_contracts)
    contract = sol_contracts[SOL_PATH + ':' + CONTRACT_NAME]
    # separate main file and link file
    Storage =  w3.eth.contract(
        abi=contract['abi'], bytecode=contract['bin'])

    # print(contract)
    # print(w3.eth.accounts[1])
    
    # Get transaction hash from deployed contract
    w3.eth.default_account = w3.eth.accounts[0]
    tx_hash = Storage.constructor().transact({'from':w3.eth.accounts[0]})
    # Get tx receipt to get contract address
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print("hash ", tx_hash)
    print("rec ", tx_receipt)
    return tx_receipt['contractAddress']
Esempio n. 3
0
    def compile_source_files(self):
        """Compiles 'contract_to_deploy' from specified contract.

        Loops through contracts in 'contract_directory' and creates a list of
        absolute paths to be passed to the py-solc-x's 'compile_files' method.

        Returns:
            self.all_compiled_contracts (dict): all the compiler outputs (abi, bin, ast...)
            for every contract in contract_directory
        """

        deployment_list = []

        for contract in os.listdir(self.contract_directory):
            deployment_list.append(
                os.path.join(self.contract_directory, contract))

        self.all_compiled_contracts = compile_files(deployment_list)

        print("Compiled contract keys:\n{}".format('\n'.join(
            self.all_compiled_contracts.keys())))
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)

    # print (contract_interface)
    
    # first deploy all link libraries
    # here link is refers to the second contarct "stringUtils.sol"
    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']
Esempio n. 5
0
    def _compile_contract(self):
        install_solc("v" + self.app_config.compiler_version)
        set_solc_version("v" + self.app_config.compiler_version)
        '''
        Compiles smart contract, creates bytecode and abi
        '''
        # loading contract file data
        with open(tools.get_contr_path(), "r") as source_file:
            source_raw = source_file.read()

        # loading configuration data
        with open(tools.get_compile_data_path()) as opt_file:
            raw_opt = opt_file.read()
            opt = json.loads(raw_opt)
        #opt["sources"]["ResearchCertificate.sol"]["content"] = source_raw
        #compiled_sol = compile_source(source_raw)
        compiled_sol = compile_files([tools.get_contr_path()], output_values=["abi", "bin"])
        contract_interface = compiled_sol[tools.get_contr_path() + ":ResearchCertificate"]
        self.bytecode = contract_interface['bin']
        self.abi = contract_interface['abi']

        logging.info("Succesfully compiled contract")
Esempio n. 6
0
def compiler(sol_file_name):
    with open('%s' % sol_file_name, 'r', encoding="utf-8") as sol_file:
        if_pragma = False
        while True:
            pragma_line = sol_file.readline()
            #print(pragma_line)
            pragma_pattern = r'(pragma)[\s]+(solidity)[\s]+(.+);[\s]*(/+.*)*'
            match_pragma_pattern = re.match(pragma_pattern, pragma_line)
            if match_pragma_pattern:
                pragmas = match_pragma_pattern.groups()
                pragma = pragmas[2]
                #print('pragma: %s' % pragma)
                install_solc_pragma(pragma)
                set_solc_version_pragma(pragma)
                if_pragma = True
                break
            if not pragma_line:
                break
        if not if_pragma:  # no pragma
            install_solc('v0.4.25')
            set_solc_version('v0.4.25')
    compiled_sol = compile_files([sol_file_name])
    file_name_key_list = list(compiled_sol.keys())
    contract_name_list = list()
    for k in file_name_key_list:
        contract_name = k.split(':')[-1]
        contract_name_list.append(contract_name)
        with open('%s.bin.txt' % contract_name, 'w',
                  encoding="utf-8") as outfile:
            json.dump(compiled_sol[k]['bin'], outfile, ensure_ascii=False)
        with open('%s.asm.json' % contract_name, 'w',
                  encoding="utf-8") as outfile:
            json.dump(compiled_sol[k]['asm'], outfile, ensure_ascii=False)
    with open('ast.json', 'w', encoding="utf-8") as outfile:
        json.dump(compiled_sol[file_name_key_list[0]]['ast'],
                  outfile,
                  ensure_ascii=False)

    return (if_pragma, contract_name_list)
Esempio n. 7
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.
        """
        solcx.install.install_solc(SOLC_VERSION)
        solcx.set_solc_version(SOLC_VERSION)
        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 = solcx.compile_files(
                    [str(relativise(file)) for file in contracts_dir.glob("*.sol")],
                    output_values=PRECOMPILED_DATA_FIELDS,
                    import_remappings=import_dir_map,
                    optimize=True,
                    optimize_runs=200,
                )

                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
Esempio n. 8
0
def compile_contracts(
        zksnark: IZKSnarkProvider) -> Tuple[Interface, Interface, Interface]:
    contracts_dir = get_contracts_dir()
    (proof_verifier_name, mixer_name) = zksnark.get_contract_names()
    otsig_verifier_name = constants.SCHNORR_VERIFIER_CONTRACT

    path_to_proof_verifier = os.path.join(contracts_dir,
                                          proof_verifier_name + ".sol")
    path_to_otsig_verifier = os.path.join(contracts_dir,
                                          otsig_verifier_name + ".sol")
    path_to_mixer = os.path.join(contracts_dir, mixer_name + ".sol")

    compiled_sol = compile_files(
        [path_to_proof_verifier, path_to_otsig_verifier, path_to_mixer])

    proof_verifier_interface = \
        compiled_sol[path_to_proof_verifier + ':' + proof_verifier_name]
    otsig_verifier_interface = \
        compiled_sol[path_to_otsig_verifier + ':' + otsig_verifier_name]
    mixer_interface = compiled_sol[path_to_mixer + ':' + mixer_name]

    return (proof_verifier_interface, otsig_verifier_interface,
            mixer_interface)
Esempio n. 9
0
def prepare_contracts(solidity_files):
    compiled = solcx.compile_files(
        solidity_files,
        optimize=True,
        allow_paths=
        "/Users/hkalodner/Documents/OffchainLabs/Github/arbitrum-python/contracts"
    )
    contracts = {}
    for contractName in compiled:
        name = contractName.split(":")[-1]
        contract = compiled[contractName]

        address_bytes = hashlib.sha224(
            bytes.fromhex(contract['bin-runtime'][2:])).hexdigest()[:40]
        address_string = web3.Web3.toChecksumAddress(address_bytes)

        contracts[name] = {
            'address': address_string,
            'abi': contract['abi'],
            'name': name,
            'code': contract['bin'],
        }
    return contracts
Esempio n. 10
0
def deploy_intervention_manager():

    compiledInterventionManager = solcx.compile_files(
        [CONTRACT_SOURCES_FOLDER + CONTRACT_IM_SOURCES_FILENAME])
    interventionManagerId, interventionManagerInterface = compiledInterventionManager.popitem(
    )
    deployTransactionHash = tools.w3.eth.contract(
        abi=interventionManagerInterface['abi'],
        bytecode=interventionManagerInterface['bin']).constructor().transact()

    console(
        LOG_FLAG_INFO,
        "intervention manager contract transaction sent, waiting validation")

    interventionManagerDeployWaitingThread = threading.Thread(
        target=deploy_waiting,
        name="interventionManager",
        args=(
            deployTransactionHash,
            interventionManagerInterface['abi'],
        ),
        daemon=True)
    interventionManagerDeployWaitingThread.start()
Esempio n. 11
0
    def compile_source_files(self):
        """Compiles 'contract_to_deploy' from specified contract.

        Loops through contracts in 'contract_directory' and creates a list of
        absolute paths to be passed to the py-solc-x's 'compile_files' method.

        Returns:
            self.all_compiled_contracts (dict): all the compiler outputs (abi, bin, ast...)
            for every contract in contract_directory
        """

        deployment_list = []
        for root, directories, files in os.walk(self.contract_directory):
            for file in files:
                print('ADDED : ', os.path.abspath(os.path.join(root, file)))

                deployment_list.append(
                    os.path.abspath(os.path.join(root, file)))

        kwargs = {'--allowed-paths': '*'}
        self.all_compiled_contracts = compile_files(deployment_list, **kwargs)

        print("Compiled contract keys:\n{}".format('\n'.join(
            self.all_compiled_contracts.keys())))
Esempio n. 12
0
def get_contract_instance(contract_dict=None,
                          source=None,
                          contract_name=None,
                          address=None,
                          abi_file=None,
                          bytecode_file=None):
    w3 = web3.Web3()
    contract = None
    if source and contract_name:
        output = solcx.compile_files([source])
        if platform == "win32":
            source = os.path.abspath(source).replace("\\", "/")
        contract_dict = output[f"{source}:{contract_name}"]
        if "bin" in contract_dict:
            contract_dict["bytecode"] = contract_dict.pop("bin")
        elif "code" in contract_dict:
            contract_dict["bytecode"] = contract_dict.pop("code")
    if contract_dict:
        contract = w3.eth.contract(abi=contract_dict['abi'],
                                   bytecode=contract_dict['bytecode'],
                                   address=address)
    elif abi_file:
        with open(abi_file, 'r') as abi_file:
            abi = json.loads(abi_file.read())
        if address:
            contract = w3.eth.contract(abi=abi, address=address)
        elif bytecode_file:
            bytecode = None
            if bytecode_file:
                with open(bytecode_file, 'r') as bytecode_file:
                    bytecode = bytecode_file.read()
                contract = w3.eth.contract(abi=abi, bytecode=bytecode)
            else:
                raise ValueError(
                    "The bytecode or the address must be provided")
    return contract
Esempio n. 13
0
def generate_solidity_payload(
    file: str,
    version: Optional[str],
    contracts: List[str] = None,
    remappings: Tuple[str] = None,
) -> Dict:
    """Generate a MythX analysis request from a given Solidity file.

    This function will open the file, try to detect the used solc version from
    the pragma definition, and automatically compile it. If the given solc
    version is not installed on the client's system, it will be automatically
    downloaded.

    From the solc output, the following data is sent to the MythX API for
    analysis:

    * :code:`abi`
    * :code:`ast`
    * :code:`bin`
    * :code:`bin-runtime`
    * :code:`srcmap`
    * :code:`srcmap-runtime`

    :param file: The path pointing towards the Solidity file
    :param version: The solc version to use for compilation
    :param contracts: The contract name(s) to submit
    :param remappings: Import remappings to pass to solcx
    :return: The payload dictionary to be sent to MythX
    """

    with open(file) as f:
        solc_version = re.findall(PRAGMA_PATTERN, f.read())
    LOGGER.debug(f"solc version matches in {file}: {solc_version}")

    if not (solc_version or version):
        # no pragma found, user needs to specify the version
        raise click.exceptions.UsageError(
            "No pragma found - please specify a solc version with --solc-version"
        )

    solc_version = f"v{version or solc_version[0]}"

    if solc_version not in solcx.get_installed_solc_versions():
        try:
            LOGGER.debug(f"Installing solc {solc_version}")
            solcx.install_solc(solc_version)
        except Exception as e:
            raise click.exceptions.UsageError(
                f"Error installing solc version {solc_version}: {e}")

    solcx.set_solc_version(solc_version, silent=True)
    try:
        cwd = str(Path.cwd().absolute())
        LOGGER.debug(f"Compiling {file} under allowed path {cwd}")
        result = solcx.compile_files(
            [file],
            output_values=(
                "abi",
                "ast",
                "bin",
                "bin-runtime",
                "srcmap",
                "srcmap-runtime",
            ),
            import_remappings=remappings or [
                f"openzeppelin-solidity/={cwd}/node_modules/openzeppelin-solidity/",
                f"openzeppelin-zos/={cwd}/node_modules/openzeppelin-zos/",
                f"zos-lib/={cwd}/node_modules/zos-lib/",
            ],
            allow_paths=cwd,
        )
    except solcx.exceptions.SolcError as e:
        raise click.exceptions.UsageError(
            f"Error compiling source with solc {solc_version}: {e}")

    # sanitize solcx keys
    new_result = {}
    for key, value in result.items():
        new_key = key.split(":")[1]
        LOGGER.debug(f"Sanitizing solc key {key} -> {new_key}")
        new_result[new_key] = value
    result = new_result

    payload = {"sources": {}, "solc_version": solc_version}

    bytecode_max = 0
    for contract_name, contract_data in result.items():
        ast = contract_data["ast"]
        source_path = str(Path(ast.get("attributes", {}).get("absolutePath")))
        creation_bytecode = contract_data["bin"]
        deployed_bytecode = contract_data["bin-runtime"]
        source_map = contract_data["srcmap"]
        deployed_source_map = contract_data["srcmap-runtime"]
        with open(source_path) as source_f:
            source = source_f.read()
            LOGGER.debug(
                f"Loaded contract source with {len(source)} characters")

        # always add source and AST, even if dependency
        payload["sources"][source_path] = {"source": source, "ast": ast}
        if (contracts and contract_name not in contracts) or (
                not contracts and len(creation_bytecode) < bytecode_max):
            LOGGER.debug(
                f"Found dependency contract {contract_name} - continung")
            continue

        bytecode_max = len(creation_bytecode)
        LOGGER.debug(f"Updaing main payload for {contract_name}")
        payload.update({
            "contract_name":
            contract_name,
            "main_source":
            source_path,
            "source_list": [source_path],
            "bytecode":
            patch_solc_bytecode(creation_bytecode),
            "source_map":
            zero_srcmap_indices(source_map),
            "deployed_source_map":
            zero_srcmap_indices(deployed_source_map),
            "deployed_bytecode":
            patch_solc_bytecode(deployed_bytecode),
            "solc_version":
            solc_version,
        })

    return payload
Esempio n. 14
0
import solcx

# If you haven't already installed the Solidity compiler, uncomment the following line
# solcx.install_solc()

# Compile contract
temp_file = solcx.compile_files('Incrementer.sol')

# Export contract data
abi = temp_file['Incrementer.sol:Incrementer']['abi']
bytecode = temp_file['Incrementer.sol:Incrementer']['bin']
Esempio n. 15
0
import os
from web3 import Web3
from solcx import compile_files

dir_path = os.path.dirname(os.path.realpath(__file__))
greeter_path = os.path.join(dir_path, 'greeter.sol')
# complie
complied_greeter = compile_files([greeter_path])

greeter_key = greeter_path + ":Greeter"
greeter_abi = complied_greeter[greeter_key]['abi']
greeter_bytecode = complied_greeter[greeter_key]['bin']

ganeche_url = "HTTP://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganeche_url))
web3.eth.defaultAccount = web3.eth.accounts[0]

# deploy contract
Greeter = web3.eth.contract(abi=greeter_abi, bytecode=greeter_bytecode)
tx_hash = Greeter.constructor().transact()
tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)

# interact contract
greeter = web3.eth.contract(address=tx_receipt.contractAddress,
                            abi=greeter_abi)
print(greeter.functions.greet().call())
tx_hash = greeter.functions.setGreeting("안녕!").transact()
tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
print(greeter.functions.greet().call())
def test_compile_multiple_files_fails_bad_path(baz_path):
    with pytest.raises(SolcError):
        solcx.compile_files([baz_path])
listOfCandidates = ['A', 'B', 'C']

hex_array = [
    Web3.toHex(str.encode(bytes_data)) for bytes_data in listOfCandidates
]


def deploy_contract(contract_interface):

    tx_hash = w3.eth.contract(
        abi=contract_interface['abi'],
        bytecode=contract_interface['bin']).constructor(hex_array).transact(
            {'from': w3.eth.accounts[1]})

    address = w3.eth.getTransactionReceipt(tx_hash)['contractAddress']
    return address


# compile all contract files
contracts = compile_files(['x.sol'])
# separate main file and link file
main_contract = contracts.pop("x.sol:Election")

with open('data.json', 'w') as outfile:
    data = {
        "abi": main_contract['abi'],
        "contract_address": deploy_contract(main_contract)
    }
    json.dump(data, outfile, indent=4, sort_keys=True)
Esempio n. 18
0
import sys
sys.path.append('../../..')

from solcx import compile_files
from ammolite import (Cli, HTTPProvider, Account)
from utils import wait_for_receipts

# frontend = 'http://localhost:8080'
# private_key = 'cfac4f5fa828072ba8313b0686f02f576fa0fc8caba947569429e88968577865'
frontend = sys.argv[1]
private_key = sys.argv[2]

compiled_sol = compile_files(
    ['./contract/MainService.sol', './contract/ConcurrentLibInterface.sol'],
    output_values=['abi', 'bin'])

storage_svc = compiled_sol['./contract/MainService.sol:StorageService']
computing_svc = compiled_sol['./contract/MainService.sol:ComputingService']
main_svc = compiled_sol['./contract/MainService.sol:MainService']

cli = Cli(HTTPProvider(frontend))
storage_svc_contract = cli.eth.contract(abi=storage_svc['abi'],
                                        bytecode=storage_svc['bin'])
computing_svc_contract = cli.eth.contract(abi=computing_svc['abi'],
                                          bytecode=computing_svc['bin'])
main_svc_contract = cli.eth.contract(abi=main_svc['abi'],
                                     bytecode=main_svc['bin'])

account = Account(private_key)
raw_tx, tx_hash = account.sign(
    storage_svc_contract.constructor().buildTransaction({
def test_compile_files_allow_empty(empty_path):
    assert solcx.compile_files([empty_path], allow_empty=True) == {}
Esempio n. 20
0
def compileContracts(files):
    return compile_files(files)
Esempio n. 21
0
sys.path.append('../../..')
from solcx import compile_files
from ammolite import (Cli, HTTPProvider, Account)
from rich.console import Console

sol_dir = sys.argv[1]
frontend = sys.argv[2]
owner_key = sys.argv[3]

sols = []
for root, _, files in os.walk(sol_dir):
    for f in files:
        if f.endswith('.sol'):
            sols.append(os.path.join(root, f))

compiled_sols = compile_files(sols, output_values = ['abi', 'bin'])
ds_token = compiled_sols[sol_dir + 'token.sol:DSToken']

cli = Cli(HTTPProvider(frontend))
ds_token_contract = cli.eth.contract(
    abi = ds_token['abi'],
    bytecode = ds_token['bin'],
)

contract_owner = Account(owner_key)

console = Console()
with console.status('[bold green]Working on tasks...') as status:
    raw_tx, tx_hash = contract_owner.sign(ds_token_contract.constructor(b'DST').buildTransaction({
        'nonce': 1,
        'gas': 10000000000,
Esempio n. 22
0
import sys
sys.path.append('../../..')

import time
from solcx import compile_files
from ammolite import (Cli, HTTPProvider, Account)

frontend = sys.argv[1]
account_file = sys.argv[2]
contract_address = sys.argv[3]

compiled_sol = compile_files(
    ['./contract/PhoneBook.sol', './contract/ConcurrentLibInterface.sol'],
    output_values=['abi'])
phone_book = compiled_sol['./contract/PhoneBook.sol:PhoneBook']

cli = Cli(HTTPProvider(frontend))
contract = cli.eth.contract(
    abi=phone_book['abi'],
    address=contract_address,
)

accounts = []
with open(account_file, 'r') as f:
    lines = f.readlines()
    for l in lines:
        parts = l.split(',')
        accounts.append(Account(parts[0]))

txs = {}
for acc in accounts:
def test_compile_files_output_types(foo_path, key):
    output = solcx.compile_files([foo_path], output_values=[key])
    assert list(output[f"{foo_path.as_posix()}:Foo"]) == [key]
def test_solc_binary(wrapper_mock, foo_path):
    wrapper_mock.expect(solc_binary=Path("path/to/solc"))
    solcx.compile_files([foo_path], ["abi"],
                        solc_binary=Path("path/to/solc"),
                        allow_empty=True)
Esempio n. 25
0
    def compile(self,
                contract_filepaths: List[Path],
                base_path: Optional[Path] = None) -> List[ContractType]:
        # TODO: move this to solcx
        contract_types = []
        files = []
        solc_version = None

        for path in contract_filepaths:
            files.append(path)
            source = path.read_text()
            pragma_spec = get_pragma_spec(source)
            # check if we need to install specified compiler version
            if pragma_spec:
                if pragma_spec is not pragma_spec.select(
                        self.installed_versions):
                    solc_version = pragma_spec.select(self.available_versions)
                    if solc_version:
                        solcx.install_solc(solc_version, show_progress=False)
                    else:
                        raise CompilerError(
                            f"Solidity version '{solc_version}' is not available."
                        )
                else:
                    solc_version = pragma_spec.select(self.installed_versions)
            else:
                solc_version = max(self.installed_versions)

        if not base_path:
            # Does support base_path
            from ape import config

            base_path = config.contracts_folder

        cli_base_path = base_path if solc_version >= Version("0.6.9") else None
        import_remappings = self.get_import_remapping(base_path=cli_base_path)

        kwargs = {
            "output_values": [
                "abi",
                "bin",
                "bin-runtime",
                "devdoc",
                "userdoc",
            ],
            "solc_version": solc_version,
            "import_remappings": import_remappings,
            "optimize": self.config.optimize,
        }

        if cli_base_path:
            kwargs["base_path"] = cli_base_path

        output = solcx.compile_files(files, **kwargs)

        def load_dict(data: Union[str, dict]) -> Dict:
            return data if isinstance(data, dict) else json.loads(data)

        for contract_name, contract_type in output.items():
            contract_id_parts = contract_name.split(":")
            contract_path = Path(contract_id_parts[0])
            contract_type["contractName"] = contract_id_parts[-1]
            contract_type["sourceId"] = (
                str(get_relative_path(base_path /
                                      contract_path, base_path)) if base_path
                and contract_path.is_absolute() else str(contract_path))
            contract_type["deploymentBytecode"] = {
                "bytecode": contract_type["bin"]
            }
            contract_type["runtimeBytecode"] = {
                "bytecode": contract_type["bin-runtime"]
            }
            contract_type["userdoc"] = load_dict(contract_type["userdoc"])
            contract_type["devdoc"] = load_dict(contract_type["devdoc"])

            contract_types.append(ContractType.parse_obj(contract_type))

        # Fix source IDs for when compiler did not account for base_path,
        # such as solidity<0.6.9.
        for contract_type in contract_types:
            if contract_type.source_id:
                source_id_path = Path(contract_type.source_id)
                if source_id_path.is_absolute():
                    contract_type.source_id = str(
                        get_relative_path(source_id_path, base_path))

        return contract_types
def test_compile_single_file_no_sequence(foo_path):
    output = solcx.compile_files(foo_path)
    assert f"{foo_path.as_posix()}:Foo" in output
    for value in combined_json_values:
        assert value in output[f"{foo_path.as_posix()}:Foo"]
Esempio n. 27
0
    def _compile(self, root_source_dir: str, other_source_dirs: [str]) -> dict:
        """Executes the compiler with parameters specified in the json config"""

        # Allow for optional installation
        from solcx import compile_files
        from solcx.exceptions import SolcError

        self.log.info("Using solidity compiler binary at {}".format(
            self.__sol_binary_path))
        contracts_dir = os.path.join(root_source_dir,
                                     self.__compiled_contracts_dir)
        self.log.info(
            "Compiling solidity source files at {}".format(contracts_dir))

        source_paths = set()
        source_walker = os.walk(top=contracts_dir, topdown=True)
        if other_source_dirs is not None:
            for source_dir in other_source_dirs:
                other_source_walker = os.walk(top=source_dir, topdown=True)
                source_walker = itertools.chain(source_walker,
                                                other_source_walker)

        for root, dirs, files in source_walker:
            for filename in files:
                if filename.endswith('.sol'):
                    path = os.path.join(root, filename)
                    source_paths.add(path)
                    self.log.debug(
                        "Collecting solidity source {}".format(path))

        # Compile with remappings: https://github.com/ethereum/py-solc
        zeppelin_dir = os.path.join(root_source_dir,
                                    self.__zeppelin_library_dir)
        aragon_dir = os.path.join(root_source_dir, self.__aragon_library_dir)

        remappings = (
            "contracts={}".format(contracts_dir),
            "zeppelin={}".format(zeppelin_dir),
            "aragon={}".format(aragon_dir),
        )

        self.log.info("Compiling with import remappings {}".format(
            ", ".join(remappings)))

        optimization_runs = self.optimization_runs

        try:
            compiled_sol = compile_files(source_files=source_paths,
                                         solc_binary=self.__sol_binary_path,
                                         import_remappings=remappings,
                                         allow_paths=root_source_dir,
                                         optimize=True,
                                         optimize_runs=optimization_runs)

            self.log.info(
                "Successfully compiled {} contracts with {} optimization runs".
                format(len(compiled_sol), optimization_runs))

        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
def test_compile_files_empty(empty_path):
    with pytest.raises(ContractsNotFound):
        solcx.compile_files([empty_path])
Esempio n. 29
0
from typing import Dict, List, Tuple, Optional, Any

AttributeDict = Dict[str, Any]

GAS_LIMIT = int(os.getenv("GAS_LIMIT", 4712388))

LOG = logging.getLogger("hmt_escrow.eth_bridge")
HMTOKEN_ADDR = Web3.toChecksumAddress(
    os.getenv("HMTOKEN_ADDR", "0x9b0ff099c4e8df24ec077e0ccd46571f915afb25"))

CONTRACT_FOLDER = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                               "contracts")
CONTRACTS = compile_files([
    "{}/Escrow.sol".format(CONTRACT_FOLDER),
    "{}/EscrowFactory.sol".format(CONTRACT_FOLDER),
    "{}/HMToken.sol".format(CONTRACT_FOLDER),
    "{}/HMTokenInterface.sol".format(CONTRACT_FOLDER),
    "{}/SafeMath.sol".format(CONTRACT_FOLDER),
])

# See more details about the eth-kvstore here: https://github.com/hCaptcha/eth-kvstore
KVSTORE_CONTRACT = Web3.toChecksumAddress(
    os.getenv("KVSTORE_CONTRACT",
              "0xbcF8274FAb0cbeD0099B2cAFe862035a6217Bf44"))
WEB3_POLL_LATENCY = float(os.getenv("WEB3_POLL_LATENCY", 5))
WEB3_TIMEOUT = int(os.getenv("WEB3_TIMEOUT", 240))


def get_w3() -> Web3:
    """Set up the web3 provider for serving transactions to the ethereum network.
def test_solc_version(wrapper_mock, all_versions, foo_path):
    solc_binary = solcx.install.get_executable(all_versions)
    wrapper_mock.expect(solc_binary=solc_binary)
    solcx.compile_files([foo_path], ["abi"],
                        solc_version=all_versions,
                        allow_empty=True)