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.
12531
def _compile_all_contracts(self) -> Dict:
        
        ret = {}
        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()
        ]
        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)
        return ret
370712
def generate_contract_factory_kwargs(
    contract_data: Dict[str, Any]
) -> Generator[Tuple[str, Any], None, None]:
    
    if "abi" in contract_data:
        yield "abi", contract_data["abi"]

    if "deployment_bytecode" in contract_data:
        yield "bytecode", contract_data["deployment_bytecode"]["bytecode"]
        if "link_references" in contract_data["deployment_bytecode"]:
            yield "unlinked_references", tuple(
                contract_data["deployment_bytecode"]["link_references"]
            )

    if "runtime_bytecode" in contract_data:
        yield "bytecode_runtime", contract_data["runtime_bytecode"]["bytecode"]
        if "link_references" in contract_data["runtime_bytecode"]:
            yield "linked_references", tuple(
                contract_data["runtime_bytecode"]["link_references"]
            )
1247146
def compile(self, source, options={}):
    
    options = dict(options)
    if "paths" in options:
      options["paths"] += self.paths
    else:
      options["paths"] = self.paths

    if "compress" not in options:
      options["compress"] = self.compress

    return self.context.call("compiler", source, options, self.plugins, self.imports)
1104811
def normalize_contract_type(
    contract_type_data: Dict[str, Any]
) -> Iterable[Tuple[str, Any]]:
    
    yield "abi", contract_type_data["abi"]
    if "evm" in contract_type_data:
        if "bytecode" in contract_type_data["evm"]:
            yield "deployment_bytecode", normalize_bytecode_object(
                contract_type_data["evm"]["bytecode"]
            )
        if "deployedBytecode" in contract_type_data["evm"]:
            yield "runtime_bytecode", normalize_bytecode_object(
                contract_type_data["evm"]["deployedBytecode"]
            )
    if any(key in contract_type_data for key in NATSPEC_FIELDS):
        natspec = deep_merge_dicts(
            contract_type_data.get("userdoc", {}), contract_type_data.get("devdoc", {})
        )
        yield "natspec", natspec
    # make sure metadata isn't an empty string in solc output
    if "metadata" in contract_type_data and contract_type_data["metadata"]:
        yield "compiler", normalize_compiler_object(
            json.loads(contract_type_data["metadata"])
        )
1262123
def ImportContractAddr(wallet, contract_hash, pubkey_script_hash):
    

    contract = Blockchain.Default().GetContract(contract_hash)
    if not contract or not pubkey_script_hash:
        print("Could not find contract")
        return

    reedeem_script = contract.Code.Script.hex()

    # there has to be at least 1 param, and the first one needs to be a signature param
    param_list = bytearray(b'\x00')

    # if there's more than one param
    # we set the first parameter to be the signature param
    if len(contract.Code.ParameterList) > 1:
        param_list = bytearray(contract.Code.ParameterList)
        param_list[0] = 0

    verification_contract = Contract.Create(reedeem_script, param_list, pubkey_script_hash)

    address = verification_contract.Address

    wallet.AddContract(verification_contract)

    print(f"Added contract address {address} to wallet")
    return verification_contract
280692
def compile_rich(cls, code, path=None, extra_args=None):
        """"""

        return {
            contract_name: {
                'code': '0x' + contract.get('bin_hex'),
                'info': {
                    'abiDefinition': contract.get('abi'),
                    'compilerVersion': cls.compiler_version(),
                    'developerDoc': contract.get('devdoc'),
                    'language': 'Solidity',
                    'languageVersion': '0',
                    'source': code,
                    'userDoc': contract.get('userdoc')
                },
            }
            for contract_name, contract
            in cls.combined(code, path=path, extra_args=extra_args)
        }
875739
def get_solc_input(self):
        

        def legal(r, file_name):
            hidden = file_name[0] == '.'
            dotsol = len(file_name) > 3 and file_name[-4:] == '.sol'
            path = os.path.normpath(os.path.join(r, file_name))
            notfile = not os.path.isfile(path)
            symlink = Path(path).is_symlink()
            return dotsol and (not (symlink or hidden or notfile))

        solc_input = {
            'language': 'Solidity',
            'sources': {
                file_name: {
                    'urls': [os.path.realpath(os.path.join(r, file_name))]
                } for r, d, f in os.walk(self.contracts_dir) for file_name in f if legal(r, file_name)
            },
            'settings': {
                'optimizer': {
                    'enabled': 1,
                    'runs': 10000
                },
                'outputSelection': {
                    "*": {
                        "": [
                            "legacyAST",
                            "ast"
                        ],
                        "*": [
                            "abi",
                            "evm.bytecode.object",
                            "evm.bytecode.sourceMap",
                            "evm.deployedBytecode.object",
                            "evm.deployedBytecode.sourceMap"
                        ]
                    }
                }
            }
        }

        return solc_input
1066493
function compile(ast, opts) {
  opts = assign({}, config.defaultOpts, opts)
  debug('compile', opts, ast)
  var worker = makeWorker(opts)
  for (var i = 0, text = ast.value, len = text.length; i < len; i++) {
    compileLine(text[i], worker)
  }
  return worker.buf.join('')
}
77030
def _init_solc_binary(version):
        

        if not version:
            return os.environ.get("SOLC") or "solc"

        # tried converting input to semver, seemed not necessary so just slicing for now
        main_version = solc.main.get_solc_version_string()
        main_version_number = re.match(r"\d+.\d+.\d+", main_version)
        if main_version is None:
            raise CriticalError(
                "Could not extract solc version from string {}".format(main_version)
            )
        if version == main_version_number:
            log.info("Given version matches installed version")
            solc_binary = os.environ.get("SOLC") or "solc"
        else:
            solc_binary = util.solc_exists(version)
            if solc_binary:
                log.info("Given version is already installed")
            else:
                try:
                    solc.install_solc("v" + version)
                    solc_binary = util.solc_exists(version)
                    if not solc_binary:
                        raise SolcError()
                except SolcError:
                    raise CriticalError(
                        "There was an error when trying to install the specified solc version"
                    )

            log.info("Setting the compiler to %s", solc_binary)

        return solc_binary
324685
def get(contract_name):
        '''
        
        '''

        if not Catalog.path:
            return None, "path to catalog must be set before searching it"
        if not contract_name:
            return None, "contract name missing"

        abi_file = "{}/{}.abi".format(Catalog.path, contract_name)

        try:
            with open(abi_file, "r") as file:
                abi = file.read()
        except Exception as e:
            return None, "Catalog.get error: {}".format(e)
        return abi, None
42211
def compile(source, name):
    
    cache = os.path.join(pycbc._cache_dir_path, name)
    hash_file = cache + ".hash"
    lib_file = cache + ".so"
    obj_file = cache + ".o"

    try:
        if int(open(hash_file, "r").read()) == hash(source):
            return lib_file
        raise ValueError
    except:
        pass

    src_file = cache + ".cu"
    fsrc = open(src_file, "w")
    fsrc.write(source)
    fsrc.close()

    cmd = ["nvcc", "-ccbin", "g++", "-dc", "-m64",
           "--compiler-options", "'-fPIC'",
           "-o", obj_file,
           "-c", src_file]
    print(" ".join(cmd))
    subprocess.check_call(cmd)

    cmd = ["nvcc", "-shared", "-ccbin", "g++", "-m64",
       "-o", lib_file, obj_file, "-lcufft_static", "-lculibos"]
    print(" ".join(cmd))

    subprocess.check_call(cmd)

    hash_file = cache + ".hash"
    fhash = open(hash_file, "w")
    fhash.write(str(hash(source)))
    return lib_file
522561
def ToJson(self):
        
        jsn = super(PublishTransaction, self).ToJson()
        jsn['contract'] = {}
        jsn['contract']['code'] = self.Code.ToJson()
        jsn['contract']['needstorage'] = self.NeedStorage
        jsn['contract']['name'] = self.Name.decode('utf-8')
        jsn['contract']['version'] = self.CodeVersion.decode('utf-8')
        jsn['contract']['author'] = self.Author.decode('utf-8')
        jsn['contract']['email'] = self.Email.decode('utf-8')
        jsn['contract']['description'] = self.Description.decode('utf-8')
        return jsn
815604
def compile_files_cwd(*args, **kwargs):
    """"""
    # 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] != '/':
        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(
            source_files=file_list,
            # We need to specify output values here because py-solc by default
            # provides them all and does not know that "clone-bin" does not exist
            # in solidity >= v0.5.0
            output_values=('abi', 'asm', 'ast', 'bin', 'bin-runtime'),
            **kwargs,
        )
    finally:
        os.chdir(cwd)
    return compiled_contracts
700516
def call_contract_function(
        web3,
        address,
        normalizers,
        function_identifier,
        transaction,
        block_id=None,
        contract_abi=None,
        fn_abi=None,
        *args,
        **kwargs):
    
    call_transaction = prepare_transaction(
        address,
        web3,
        fn_identifier=function_identifier,
        contract_abi=contract_abi,
        fn_abi=fn_abi,
        transaction=transaction,
        fn_args=args,
        fn_kwargs=kwargs,
    )

    if block_id is None:
        return_data = web3.eth.call(call_transaction)
    else:
        return_data = web3.eth.call(call_transaction, block_identifier=block_id)

    if fn_abi is None:
        fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs)

    output_types = get_abi_output_types(fn_abi)

    try:
        output_data = decode_abi(output_types, return_data)
    except DecodingError as e:
        # Provide a more helpful error message than the one provided by
        # eth-abi-utils
        is_missing_code_error = (
            return_data in ACCEPTABLE_EMPTY_STRINGS and
            web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS
        )
        if is_missing_code_error:
            msg = (
                "Could not transact with/call contract function, is contract "
                "deployed correctly and chain synced?"
            )
        else:
            msg = (
                "Could not decode contract function call {} return data {} for "
                "output_types {}".format(
                    function_identifier,
                    return_data,
                    output_types
                )
            )
        raise BadFunctionCallOutput(msg) from e

    _normalizers = itertools.chain(
        BASE_RETURN_NORMALIZERS,
        normalizers,
    )
    normalized_data = map_abi_data(_normalizers, output_types, output_data)

    if len(normalized_data) == 1:
        return normalized_data[0]
    else:
        return normalized_data
1002520
def get_contract_data(self, contract_name):
        

        contract_data_path = self.output_dir + '/{0}.json'.format(contract_name)
        with open(contract_data_path, 'r') as contract_data_file:
            contract_data = json.load(contract_data_file)

        abi = contract_data['abi']
        bytecode = contract_data['evm']['bytecode']['object']

        return abi, bytecode
1361302
function compile() {
    swig.log.info('', 'Compiling module list...');

    const modulesPath = path.join(swig.temp, '/**/node_modules/@gilt-tech');
    const modPaths = glob.sync(modulesPath);
    let dirs;

    swig.log.verbose(`[compile] searching: ${modulesPath}`);
    swig.log.verbose(`[compile] found module directories: ${modPaths.length}`);

    modPaths.forEach((modPath) => {
      swig.log.verbose(`[compile] compiling: ${modPath}`);

      dirs = fs.readdirSync(modPath);

      _.each(dirs, (dir) => {
        const dirPath = path.join(modPath, dir);
        if (fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory()) {
          azModules.push({ name: dir, path: dirPath });
        }
      });
    });

    // group by basename, and take the 'topmost' module in the hierarchy
    azModules = _.groupBy(azModules, module => path.basename(module.path));

    // pull out the 'winning' module path, for each module
    azModules = _.map(azModules, (modulesList) => {
      // the modules arg will be [{ name:, path: }, ...]

      if (modulesList.length === 1) {
        return modulesList[0];
      }

      // glob will almost always return the right order,
      // but let's assert this to be safe. we can spare the cycles.
      return _.sortBy(modulesList, module => module.path.length)[0];
    });

    // and now we pretty sort a-z for various output
    // we dont reset azModules to the sorted array because we need it dirty for deps.less
    _.sortBy(azModules, mod => mod.name).forEach((mod) => {
      modules[mod.name] = mod.path;
    });

    swig.log.verbose('[compile] sorted modules: ');
    swig.log.verbose(modules);
  }
351323
def solidity_get_contract_key(all_contracts, filepath, contract_name):
    
    if contract_name in all_contracts:
        return contract_name
    else:
        if filepath is None:
            filename = '<stdin>'
        else:
            _, filename = os.path.split(filepath)
        contract_key = filename + ":" + contract_name
        return contract_key if contract_key in all_contracts else None