def test_compile_standard_invalid_source(INVALID_SOURCE):
    with pytest.raises(SolcError):
        compile_standard({
            'language': 'Solidity',
            'sources': {
                'contracts/Foo.sol': {
                    'content': INVALID_SOURCE,
                },
            },
            'outputSelection': {
                "*": {"*": ["evm.bytecode.object"]},
            },
        })
示例#2
0
def test_compile_standard_invalid_source(INVALID_SOURCE):
    with pytest.raises(SolcError):
        compile_standard({
            'language': 'Solidity',
            'sources': {
                'contracts/Foo.sol': {
                    'content': INVALID_SOURCE,
                },
            },
            'outputSelection': {
                "*": {
                    "*": ["evm.bytecode.object"]
                },
            },
        })
示例#3
0
 def compileSolidity(relativeFilePath):
     absoluteFilePath = resolveRelativePath(relativeFilePath)
     filename = path.basename(relativeFilePath)
     contractName = path.splitext(filename)[0]
     print absoluteFilePath
     compilerParameter = {
         'language': 'Solidity',
         'sources': {
             absoluteFilePath: {
                 'urls': [absoluteFilePath]
             }
         },
         'settings': {
             # TODO: Remove 'remappings' line below and update 'sources' line above
             'remappings': [
                 '=%s/' % resolveRelativePath("../source/contracts"),
                 'TEST=%s/' % resolveRelativePath("solidity_test_helpers")
             ],
             'optimizer': {
                 'enabled': True,
                 'runs': 500
             },
             'outputSelection': {
                 '*': ['metadata', 'evm.bytecode', 'evm.sourceMap']
             }
         }
     }
     return compile_standard(
         compilerParameter, allow_paths=resolveRelativePath(
             "../"))['contracts'][absoluteFilePath][contractName]
示例#4
0
def get_compiled_contract():
    sol_name = "hackfs"
    with open(os.path.dirname(os.getcwd()) + "\contract\eth.sol",
              "r",
              encoding="utf-8") as f:  # 设置文件对象
        source = f.read()
    # sol should like this
    sol = {"name": "eth.sol", "body": source}
    compiled_sol = compile_standard({
        "language": "Solidity",
        "sources": {
            sol.get("name"): {
                "content": sol.get("body")
            }
        },
        "settings": {
            "outputSelection": {
                "*": {
                    "*":
                    ["metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                }
            }
        }
    })
    return compiled_sol
示例#5
0
    def _compile_contract(self):
        '''
        Compiles smart contract, creates bytecode and abi
        '''
        # loading contract file data
        with open(tools.get_contr_path()) 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"]["CertificateStore.sol"]["content"] = source_raw
        compiled_sol = compile_standard(opt)

        # defining bytecode and abi
        self.bytecode = compiled_sol['contracts']['CertificateStore.sol'][
            'CertificateStore']['evm']['bytecode']['object']
        self.abi = json.loads(
            compiled_sol['contracts']['CertificateStore.sol']
            ['CertificateStore']['metadata'])['output']['abi']

        with open(tools.get_contr_info_path(), "w+") as f:
            json.dump(self.abi, f)

        logging.info("Succesfully compiled contract")
示例#6
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', help="Solidity source code")
    parser.add_argument('-f', '--file', help="solidity file name with full path. Like ~/examplefolder/test.solc")
    parser.add_argument('-p', '--procedure', help="Solidity function name.")
    parsed = parser.parse_args()

    compile_path = Path("../output/compiled")
    if not compile_path.is_dir():
        command = 'mkdir -p ../output/compiled'.split()
        for line in run_command(command):
            print(line)

    if parsed.source:
        solidity_source = parsed.source
        output = compile_standard({
            'language': 'Solidity',
            'sources': {'standard.sol': {'content': solidity_source}}
        })
        print "abi save to output / compiled / abi file"
         save_abi (findDict (output ['contracts'], 'abi'))
         print "bincode save to output / compiled / bytecode"
        save_bincode(str(findDict(output, 'object')))

        save_functions(findDict(output, 'methodIdentifiers'))
示例#7
0
def compile_contract(contract_name):
    contract_source = os.path.join(CONTRACTS_DIR, f'{contract_name}.sol')
    if not os.path.isfile(contract_source):
        raise FileNotFoundError(f'Expected {contract_source} to exist.')

    compiled = compile_standard(
        {
            'language': 'Solidity',
            'sources': {
                contract_name: {
                    'urls': [contract_source]
                }
            },
            'settings': {
                'remappings': [
                    "openzeppelin-solidity=%s" %
                    os.path.join(SOLIDITY_DIR, 'openzeppelin-solidity')
                ],
                'outputSelection': {
                    contract_name: {
                        contract_name: ['abi', 'evm.bytecode.object']
                    }
                }
            }
        },
        allow_paths=SOLIDITY_DIR)

    abi = compiled['contracts'][contract_name][contract_name]['abi']
    bytecode = compiled['contracts'][contract_name][contract_name]['evm'][
        'bytecode']['object']

    output_filename = os.path.join(CONTRACTS_DIR, f'{contract_name}.json')

    with open(output_filename, 'w') as f:
        json.dump({'abi': abi, 'bin': bytecode}, f)
示例#8
0
 def compileSolidity(self, relativeFilePath):
     absoluteFilePath = resolveRelativePath(relativeFilePath)
     filename = path.basename(relativeFilePath)
     contractName = path.splitext(filename)[0]
     compilerParameter = {
         'language': 'Solidity',
         'sources': {
             absoluteFilePath: {
                 'urls': [ absoluteFilePath ]
             }
         },
         'settings': {
             # TODO: Remove 'remappings' line below and update 'sources' line above
             'remappings': [ 'ROOT=%s/' % resolveRelativePath(self.relativeContractsPath), 'TEST=%s/' % resolveRelativePath(self.relativeTestContractsPath) ],
             'optimizer': {
                 'enabled': True,
                 'runs': 200,
                 "details": {
                     "yul": True,
                     "deduplicate": True,
                     "cse": True,
                     "constantOptimizer": True
                 }
             },
             'outputSelection': {
                 "*": {
                     '*': [ 'metadata', 'evm.bytecode', 'evm.sourceMap', 'abi' ]
                 }
             }
         }
     }
     return compile_standard(compilerParameter, allow_paths=resolveRelativePath("../"))['contracts'][absoluteFilePath][contractName]
示例#9
0
    def getCompiledSol(self, path):
        with open(path, 'r') as f:
            source = f.read()

        fileName = path.split('/')[-1]
        contractName = fileName.replace('.sol', '')

        compiled_sol = compile_standard({
            "language": "Solidity",
            "sources": {
                fileName: {
                    "content": source
                }
            },
            "settings": {
                "outputSelection": {
                    "*": {
                        "*":
                        ["metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                    }
                }
            }
        })

        bytecode = compiled_sol['contracts'][fileName][contractName]['evm'][
            'bytecode']['object']
        abi = loads(compiled_sol['contracts'][fileName][contractName]
                    ['metadata'])['output']['abi']

        return bytecode, abi
示例#10
0
def test_compile_standard_with_file_paths(FOO_SOURCE, is_new_key_format,
                                          contracts_dir):
    source_file_path = os.path.join(contracts_dir, 'Foo.sol')
    with open(source_file_path, 'w') as source_file:
        source_file.write(FOO_SOURCE)

    result = compile_standard(
        {
            'language': 'Solidity',
            'sources': {
                'contracts/Foo.sol': {
                    'urls': [source_file_path],
                },
            },
            'settings': {
                'outputSelection': {
                    "*": {
                        "*": ["evm.bytecode.object"]
                    },
                },
            }
        },
        allow_paths=contracts_dir)

    assert isinstance(result, dict)
    assert 'contracts' in result
    assert contract_in_output_map('Foo', result['contracts'])
示例#11
0
 def _compile_source_deprecated(self):
     """
     Finished.
     Compiles the source solidity code and returns the
         binary, abi, runtime opcode in a dictionary format.
     Returns:
         dictionary containing the above info.
     """
     filename = self.source_dir.split('/')[-1]
     compiled_sol = compile_standard({
         "language": "Solidity",
         "sources": {
             filename: {
                 "content": self.source_code
             }
         },
         "settings": {
             "outputSelection": {
                 "*": {
                     "*": ["abi", "evm.bytecode", "evm.deployedBytecode"]
                 }
             }
         }
     })
     return compiled_sol['contracts'][filename][self.name]
示例#12
0
 def compile_contract(self, path, args=()):
     file_name = path.split('/')[1]
     contract_name = file_name.split('.')[0]
     path, contracts = self.get_dirs(path)
     compiled_sol = compile_standard(
         {
             'language': 'Solidity',
             'sources': {
                 **{
                     path.split('/')[-1]: {
                         'urls': [path]
                     }
                 },
                 **contracts
             }
         },  # Noqa E999
         allow_paths=OWN_DIR + "/contracts")
     abi = compiled_sol['contracts'][file_name][contract_name]['abi']
     bytecode = compiled_sol['contracts'][file_name][contract_name]['evm'][
         'bytecode']['object']
     contract_file = open(
         "contract_data/%s.json" % (file_name.split('.')[0]), "w+")
     json.dump(abi, contract_file)
     contract_file.close()
     return abi, bytecode
示例#13
0
def deploy_solidity_contract(chain, solc_config_sources, allow_paths,
                             contract_file, contract_name, startgas):
    compiled = compile_standard(
        {
            'language': 'Solidity',
            'sources': solc_config_sources,
            'settings': {
                'evmVersion': 'byzantium',
                'outputSelection': {
                    '*': {
                        '*': ['abi', 'evm.bytecode']
                    }
                },
            },
        },
        allow_paths=allow_paths)

    abi = compiled['contracts'][contract_file][contract_name]['abi']
    binary = compiled['contracts'][contract_file][contract_name]['evm'][
        'bytecode']['object']
    address = chain.contract(utils.decode_hex(binary),
                             language='evm',
                             value=0,
                             startgas=startgas,
                             sender=tester.k0)
    contract = tester.ABIContract(chain, abi, address)
    return contract
示例#14
0
def deploy_solidity_contract_with_args(chain,
                                       solc_config_sources,
                                       allow_paths,
                                       contract_file,
                                       contract_name,
                                       startgas,
                                       args=[]):
    compiled = compile_standard(
        {
            'language': 'Solidity',
            'sources': solc_config_sources,
            'settings': {
                'evmVersion': 'byzantium',
                'outputSelection': {
                    '*': {
                        '*': ['abi', 'evm.bytecode']
                    }
                },
            },
        },
        allow_paths=allow_paths)

    abi = compiled['contracts'][contract_file][contract_name]['abi']
    binary = compiled['contracts'][contract_file][contract_name]['evm'][
        'bytecode']['object']
    ct = ContractTranslator(abi)
    address = chain.contract(
        (utils.decode_hex(binary) +
         ct.encode_constructor_arguments(args) if args else b''),
        language='evm',
        value=0,
        startgas=startgas,
        sender=tester.k0)
    contract = tester.ABIContract(chain, ct, address)
    return contract
示例#15
0
def compile_contract(contract_name):
    with open(f"contracts/sol/{contract_name}.sol", 'r') as file:
        contract_name = file.name
        contract_content = file.read()
        file.close()
    
    options = {}
    options['language'] = 'Solidity'
    options['sources'] = {
        contract_name: {
            'content': contract_content,
        },
    }

    options['settings'] = {
        "outputSelection": {
            "*": {
                "*": [
                    "metadata", "evm.bytecode", 
                    "evm.bytecode.sourceMap"]
                }
            }
        }

    return compile_standard(options)
示例#16
0
    def compile_all(self):
        """Compiles all of the contracts in the /contracts directory

        Creates {contract name}.json files in /build that contain
        the build output for each contract.
        """

        # Solidity input JSON
        solc_input = self.get_solc_input()

        # Compile the contracts
        compilation_result = compile_standard(solc_input,
                                              allow_paths=CONTRACTS_DIR)

        # Create the output folder if it doesn't already exist
        os.makedirs(OUTPUT_DIR, exist_ok=True)

        # Write the contract ABI to output files
        compiled_contracts = compilation_result['contracts']
        for contract_file in compiled_contracts:
            for contract in compiled_contracts[contract_file]:
                contract_name = contract.split('.')[0]
                contract_data = compiled_contracts[contract_file][
                    contract_name]

                contract_data_path = OUTPUT_DIR + '/{0}.json'.format(
                    contract_name)
                with open(contract_data_path, "w+") as contract_data_file:
                    json.dump(contract_data, contract_data_file)
示例#17
0
 def compileSolidity(self, relativeFilePath):
     absoluteFilePath = resolveRelativePath(relativeFilePath)
     filename = path.basename(relativeFilePath)
     contractName = path.splitext(filename)[0]
     print absoluteFilePath
     compilerParameter = {
         'language': 'Solidity',
         'sources': {
             absoluteFilePath: {
                 'urls': [ absoluteFilePath ]
             }
         },
         'settings': {
             # TODO: Remove 'remappings' line below and update 'sources' line above
             'remappings': [ '=%s/' % resolveRelativePath(self.relativeContractsPath), 'TEST=%s/' % resolveRelativePath(self.relativeTestContractsPath) ],
             'optimizer': {
                 'enabled': True,
                 'runs': 500
             },
             'outputSelection': {
                 "*": {
                     '*': [ 'metadata', 'evm.bytecode', 'evm.sourceMap', 'abi' ]
                 }
             }
         }
     }
     return compile_standard(compilerParameter, allow_paths=resolveRelativePath("../"))['contracts'][absoluteFilePath][contractName]
示例#18
0
def compile_contract(source_filepath, outputs, contracts_path,
                     test_contracts_path):
    compiler_parameter = {
        'language': 'Solidity',
        'sources': {
            source_filepath: {
                'urls': [source_filepath]
            }
        },
        'settings': {
            # TODO: Remove 'remappings' line below and update 'sources' line above
            'remappings': [
                '=%s/' % contracts_path,
            ],
            'optimizer': {
                'enabled': True,
                'runs': 200
            },
            'outputSelection': {
                "*": {
                    '*': outputs
                }
            }
        }
    }
    if test_contracts_path:
        # TODO: Remove 'remappings' line below and update 'sources' line above
        compiler_parameter['settings']['remappings'].append(
            'TEST=%s/' % test_contracts_path)

    return compile_standard(compiler_parameter,
                            allow_paths=resolve_relative_path("../../"))
示例#19
0
def main():
    """ Compile the Solidity contract using the set options and 
        write it to a file JSON file

    """
    compiled_sol = compile_standard(create_options('contracts/Tester.sol'))

    # Test intstance
    w3 = Web3(IPCProvider(NODE_ADDRESS))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)

    # Pre funded account
    w3.eth.defaultAccount = w3.eth.accounts[0]

    # To deploy a Solidity Contract on Ethereum you need the contract's
    # bytecode and ABI
    bytecode = compiled_sol['contracts']['contracts/Tester.sol']['Tester'][
        'evm']['bytecode']['object']
    abi = json.loads(compiled_sol['contracts']['contracts/Tester.sol']
                     ['Tester']['metadata'])['output']['abi']
    SolContract = w3.eth.contract(abi=abi, bytecode=bytecode)

    tx_hash = SolContract.constructor().transact()
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print(tx_receipt.contractAddress)

    contract_ = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)

    tx_hash = contract_.functions.setMessage('Nihao').transact()
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print(contract_.functions.getMessage().call())
示例#20
0
def compile_ast(src_path):
    # We need to use absolute paths
    src_path = os.path.join(os.getcwd(), src_path)
    _, src_name = os.path.split(src_path)

    # We are only interested in the AST
    output_selection = {"*": {"": ["ast"]}}

    # Define settings for compilation
    compile_input = {
        'language': 'Solidity',
        'sources': {
            src_name: {
                'urls': [src_path]
            }
        },
        'settings': {
            'outputSelection': output_selection
        }
    }

    # Call solc compiler using json input
    compile_output = compile_standard(compile_input, allow_paths='/')
    ast = compile_output['sources'][os.path.basename(src_path)]['ast']

    with open(src_path, 'rb') as file:
        ast["source"] = codecs.utf_8_decode(file.read())[0]

    ast["_solc_version"] = compiler_version()

    return ast
示例#21
0
文件: test.py 项目: zhiiker/orchid
def deploy(filename, contractName, *args):
    filename = os.path.abspath(filename)
    path = os.path.dirname(filename)

    compiled = compile_standard(
        {
            'language': 'Solidity',
            'sources': {
                filename: {
                    'urls': [os.path.abspath(filename)],
                },
            },
            'settings': {
                'outputSelection': {
                    '*': {
                        '*': ['evm.bytecode', 'abi'],
                    }
                },
            },
        },
        allow_paths=os.path.abspath(os.path.join(path, '..')) + ',' + path)

    contract = compiled['contracts'][filename][contractName]

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

    transaction_hash = web3.eth.contract(
        abi=abi, bytecode=bytecode).constructor(*args).transact()
    address = web3.eth.waitForTransactionReceipt(
        transaction_hash).contractAddress
    deployed = web3.eth.contract(abi=abi, address=address)

    return deployed
示例#22
0
    def deploy_contract(web3, sol_path, address):
        from solc import compile_standard
        file_name = get_file_name(sol_path)
        clz_name = file_name.replace('.sol', '')
        sol_content = read_file_content(sol_path)

        # 編譯
        compiled_sol = compile_standard({
            'language': 'Solidity',
            'sources': {
                file_name: {
                    'content': sol_content
                }
            },
            'settings': {
                'outputSelection': {
                    "*": {
                        "*":
                        ["metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                    }
                }
            }
        })

        bytecode = compiled_sol['contracts'][file_name][clz_name]['evm'][
            'bytecode']['object']

        abi = json.loads(compiled_sol['contracts'][file_name][clz_name]
                         ['metadata'])['output']['abi']
        #
        # pre_contract = web3.eth.contract(abi=abi, bytecode=bytecode)
        #
        # # 設定部署的帳號
        # pri_key = '413AE44638D2CECC9B5137EC4A9657083C2DF0BBDD1E1105574A3F8EB75F0C81'
        # account = web3.eth.account.privateKeyToAccount(pri_key)
        #
        # # 傳遞建構式參數
        # transaction = pre_contract.constructor(10000, 'WToken3', 'WToken3').buildTransaction(
        #     {
        #         'gasPrice': web3.toWei('10', 'gwei'),
        #         'from': account.address,
        #         'nonce': web3.eth.getTransactionCount(account.address)
        #     }
        # )
        #
        # signed_txn = web3.eth.account.signTransaction(transaction, private_key=pri_key)
        # data = web3.eth.sendRawTransaction(signed_txn.rawTransaction)
        #
        # print(data)
        # print(data.hex())

        contract = web3.eth.contract(
            address=
            '890e85693d7060d7277bb51facb2d2b69311198e3d5157db59cfc0f8e210c426',
            abi=abi)

        functions = Web3Client.get_functions(contract)
        print(functions)
        pass
def main():
    """ Compile the Solidity contract using the set options and 
        write it to a file JSON file

    """
    compiled_sol = compile_standard(create_options('contracts/Tester.sol'))

    # Test intstance
    w3 = Web3(HTTPProvider(INFURA_URL))

    # Pre funded account
    #w3.eth.defaultAccount = w3.eth.accounts[0]

    # Get account from private key
    account = w3.eth.account.privateKeyToAccount(ETH_PK)

    # To deploy a Solidity Contract on Ethereum you need the contract's
    # bytecode and ABI
    bytecode = compiled_sol['contracts']['contracts/Tester.sol']['Tester'][
        'evm']['bytecode']['object']
    abi = json.loads(compiled_sol['contracts']['contracts/Tester.sol']
                     ['Tester']['metadata'])['output']['abi']
    SolContract = w3.eth.contract(abi=abi, bytecode=bytecode)

    construct_txn = SolContract.constructor().buildTransaction({
        'from':
        account.address,
        'nonce':
        w3.eth.getTransactionCount(account.address),
        'gas':
        1728712,
        'gasPrice':
        w3.toWei('21', 'gwei')
    })

    signed = account.signTransaction(construct_txn)
    tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print(tx_receipt.contractAddress)

    sol_contract = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)

    tx = sol_contract.functions.setMessage("Hello, World!").buildTransaction({
        'from':
        account.address,
        'nonce':
        w3.eth.getTransactionCount(account.address),
        'gas':
        100000,
        'gasPrice':
        w3.toWei('21', 'gwei')
    })
    signed = account.signTransaction(tx)
    tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    time.sleep(10)
    print(sol_contract.functions.getMessage().call())
示例#24
0
文件: deploy.py 项目: n1056722/Note
def deploy():
    url = 'https://ropsten.infura.io/v3/'
    sol_path = '/Users/ryan/Desktop/python/MarkDocStatusContract/MarkDocStatus.sol'
    pri_key = ''

    web3 = Web3(HTTPProvider(url))

    from solc import compile_standard
    file_name = get_file_name(sol_path)
    clz_name = file_name.replace('.sol', '')
    sol_content = read_file_content(sol_path)

    # 編譯
    compiled_sol = compile_standard({
        'language': 'Solidity',
        'sources': {
            file_name: {
                'content': sol_content
            }
        },
        'settings': {
            'outputSelection': {
                "*": {
                    "*":
                    ["metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                }
            }
        }
    })

    bytecode = compiled_sol['contracts'][file_name][clz_name]['evm'][
        'bytecode']['object']

    abi = json.loads(compiled_sol['contracts'][file_name][clz_name]
                     ['metadata'])['output']['abi']

    pre_contract = web3.eth.contract(abi=abi, bytecode=bytecode)

    # 設定部署的帳號
    account = web3.eth.account.privateKeyToAccount(pri_key)

    transaction = pre_contract.constructor().buildTransaction({
        'gasPrice':
        web3.toWei('50', 'gwei'),
        'from':
        account.address,
        'nonce':
        web3.eth.getTransactionCount(account.address)
    })

    signed_txn = web3.eth.account.signTransaction(transaction,
                                                  private_key=pri_key)
    data = web3.eth.sendRawTransaction(signed_txn.rawTransaction)

    print(f'Create contract tx_id={data.hex()}')
示例#25
0
def compileSolidity(chain, name, code):
    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'uint256.sol': { 'content': uint256 },
            'int256.sol': { 'content': int256 },
            name: { 'content': code },
        },
        'settings': {
            'outputSelection': { '*': [ 'metadata', 'evm.bytecode', 'evm.sourceMap' ] }
        }
    })
    return result
示例#26
0
def compileSolidity(chain, name, code):
    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'uint256.sol': { 'content': uint256 },
            'int256.sol': { 'content': int256 },
            name: { 'content': code },
        },
        'settings': {
            'outputSelection': { '*': [ 'metadata', 'evm.bytecode', 'evm.sourceMap' ] }
        }
    })
    return result
def test_compile_standard(FOO_SOURCE):
    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'contracts/Foo.sol': {
                'content': FOO_SOURCE,
            },
        },
        'outputSelection': {
            "*": {"*": ["evm.bytecode.object"]},
        },
    })

    assert isinstance(result, dict)
    assert 'contracts' in result
    assert contract_in_output_map('Foo', result['contracts'])
示例#28
0
def compile_sol(sol_file, sol_content):
    return compile_standard({
        'language': 'Solidity',
        'sources': {
            sol_file: {
                'content': sol_content
            }
        },
        'settings': {
            'outputSelection': {
                '*': {
                    '*': ['metadata', 'evm.bytecode', 'evm.bytecode.sourceMap']
                }
            }
        }
    })
示例#29
0
def compile_contract():
    # cf. http://tinyurl.com/yap75nl8
    sol_map = {
        "language": "Solidity",
        "sources": {},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi", "evm.bytecode"]
                }
            }
        }
    }
    d = sol_map["sources"]["contract"] = {}
    d["content"] = contract_source_code
    output = compile_standard(sol_map)
    return output['contracts']['contract']['Greeter']
示例#30
0
    def compile_contract(self, path, args=()):
        file_name = path.split('/')[1]
        contract_name = file_name.split('.')[0]
        path, contracts = self.get_dirs(path)
        compiled_sol = compile_standard({
            'language': 'Solidity',
            'sources': {**{path.split('/')[-1]: {'urls': [path]}}, **contracts}
        }, allow_paths=OWN_DIR + "/contracts")
        abi = compiled_sol['contracts'][file_name][contract_name]['abi']
        bytecode = compiled_sol['contracts'][file_name][contract_name]['evm']['bytecode']['object']

        # Create the contract_data folder if it doesn't already exist
        os.makedirs('contract_data', exist_ok=True)

        contract_file = open('contract_data/%s.json' % (file_name.split('.')[0]), "w+")
        json.dump(abi, contract_file)
        contract_file.close()
        return abi, bytecode, contract_name
示例#31
0
def test_compile_standard(FOO_SOURCE):
    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'contracts/Foo.sol': {
                'content': FOO_SOURCE,
            },
        },
        'outputSelection': {
            "*": {
                "*": ["evm.bytecode.object"]
            },
        },
    })

    assert isinstance(result, dict)
    assert 'contracts' in result
    assert contract_in_output_map('Foo', result['contracts'])
示例#32
0
def get_contract_code(path, name=None):
    from solc import compile_standard
    with open(path) as f:
        content = f.read()
        data = compile_standard({
            'language': 'Solidity',
            'sources': {
                'Contract.sol': {
                    'content': content
                }
            }
        })
        print(data)
        if name is None and len(data) > 1:
            raise ValueError('Please select contract name: ({})'.format(
                data.keys()))
        if name is None:
            name = data.keys()[0]
        return data[name]['bin']
示例#33
0
def compile_contract(chalid,
                     solidity_source,
                     test_func_source,
                     args=[],
                     starting_ether=0,
                     flag=None):
    # add flag
    if flag == None:
        flag = challenges[chalid]['flag']
    else:
        challenges[chalid] = {}
        challenges[chalid]['flag'] = flag

    # add test function
    # TODO: Make better
    challenges[chalid]['python_check'] = test_func_source
    # To use: lambda contract: eval(challenges[chalid]['python_check'])
    # Set solidity sources
    challenges[chalid]['solidity'] = {}
    challenges[chalid]['solidity']['source'] = solidity_source
    challenges[chalid]['starting_value'] = 0
    challenges[chalid]['starting_value'] = int(starting_ether) * int(
        1000000000000000000)  # Ether to wei conversion
    challenges[chalid]['args'] = args

    try:
        # Compile Solidity
        contracts = compile_standard({
            'language': 'Solidity',
            'sources': {
                chalid: {
                    'content': challenges[chalid]['solidity']['source']
                }
            }
        })['contracts']

        challenges[chalid]['solidity']['compiled'] = contracts[chalid]

        save_challenges()
        return True
    except Exception as e:
        return False
示例#34
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 'remappings' in self.compiler_settings and import_remappings is not None:
            self.logger.warn(
                "Import remappings setting will by overridden by backend settings"
            )

        sources = build_standard_input_sources(source_file_paths)

        std_input = {
            'language': 'Solidity',
            'sources': sources,
            'settings': {
                'remappings': import_remappings
            }
        }

        # solc command line options as passed to solc_wrapper()
        # https://github.com/pipermerriam/py-solc/blob/3a6de359dc31375df46418e6ffd7f45ab9567287/solc/wrapper.py#L20
        command_line_options = self.compiler_settings.get(
            "command_line_options", {})

        # Get Solidity Input Description settings section
        # http://solidity.readthedocs.io/en/develop/using-the-compiler.html#input-description
        std_input_settings = self.compiler_settings.get("stdin", {})
        std_input['settings'].update(std_input_settings)

        self.logger.debug("std_input sections: %s", std_input.keys())
        self.logger.debug("Input Description JSON settings are: %s",
                          std_input["settings"])
        self.logger.debug("Command line options are: %s", command_line_options)
        try:
            compilation_result = compile_standard(std_input,
                                                  **command_line_options)
        except ContractsNotFound:
            return {}

        compiled_contracts = normalize_compilation_result(compilation_result)
        return compiled_contracts
def test_compile_standard_with_file_paths(FOO_SOURCE, is_new_key_format, contracts_dir):
    source_file_path = os.path.join(contracts_dir, 'Foo.sol')
    with open(source_file_path, 'w') as source_file:
        source_file.write(FOO_SOURCE)

    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'contracts/Foo.sol': {
                'urls': [source_file_path],
            },
        },
        'outputSelection': {
            "*": {"*": ["evm.bytecode.object"]},
        },
    }, allow_paths=contracts_dir)

    assert isinstance(result, dict)
    assert 'contracts' in result
    assert contract_in_output_map('Foo', result['contracts'])
def test_compile_standard_with_dependency(BAR_SOURCE, BAZ_SOURCE):
    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'contracts/Bar.sol': {
                'content': BAR_SOURCE,
            },
            'contracts/Baz.sol': {
                'content': BAZ_SOURCE,
            },
        },
        'outputSelection': {
            "*": {"*": ["evm.bytecode.object"]},
        },
    })

    assert isinstance(result, dict)
    assert 'contracts' in result
    assert contract_in_output_map('Bar', result['contracts'])
    assert contract_in_output_map('Baz', result['contracts'])
示例#37
0
def test_compile_standard_empty_sources():
    with pytest.raises(ContractsNotFound):
        compile_standard({'language': 'Solidity', 'sources': {}})