def abi_contract( self, sourcecode, sender=DEFAULT_KEY, endowment=0, # pylint: disable=too-many-arguments language='serpent', log_listener=None, listen=True, libraries=None, path=None, constructor_parameters=None, **kwargs): # pylint: disable=too-many-locals compiler = languages[language] contract_interface = compiler.mk_full_signature(sourcecode, path=path, **kwargs) translator = ContractTranslator(contract_interface) encoded_parameters = None if constructor_parameters is not None: encoded_parameters = translator.encode_constructor_arguments( constructor_parameters) address = self.contract(sourcecode, sender, endowment, language, libraries, path, constructor_call=encoded_parameters, **kwargs) return ABIContract( self, translator, address, listen=listen, log_listener=log_listener, )
def upload(self, relativeFilePath, lookupKey=None, signatureKey=None, constructorArgs=[]): resolvedPath = resolveRelativePath(relativeFilePath) if self.coverageMode: resolvedPath = resolvedPath.replace("tests", "coverageEnv").replace( "source/", "coverageEnv/") lookupKey = lookupKey if lookupKey else path.splitext( path.basename(resolvedPath))[0] signatureKey = signatureKey if signatureKey else lookupKey if lookupKey in self.contracts: return (self.contracts[lookupKey]) compiledCode = self.getCompiledCode(resolvedPath) # abstract contracts have a 0-length array for bytecode if len(compiledCode) == 0: if ("libraries" in relativeFilePath or lookupKey.startswith("I") or lookupKey.startswith("Base") or lookupKey.startswith("DS")): pass #print "Skipping upload of " + lookupKey + " because it had no bytecode (likely a abstract class/interface)." else: raise Exception( "Contract: " + lookupKey + " has no bytecode, but this is not expected. It probably doesn't implement all its abstract methods" ) return None if signatureKey not in ContractsFixture.signatures: ContractsFixture.signatures[signatureKey] = self.generateSignature( resolvedPath) signature = ContractsFixture.signatures[signatureKey] contractTranslator = ContractTranslator(signature) if len(constructorArgs) > 0: compiledCode += contractTranslator.encode_constructor_arguments( constructorArgs) contractAddress = bytesToHexString( self.chain.contract(compiledCode, language='evm')) contract = ABIContract(self.chain, contractTranslator, contractAddress) self.contracts[lookupKey] = contract return (contract)
def upload(self, relativeFilePath, lookupKey = None, signatureKey = None, constructorArgs=[]): resolvedPath = resolveRelativePath(relativeFilePath) lookupKey = lookupKey if lookupKey else path.splitext(path.basename(resolvedPath))[0] signatureKey = signatureKey if signatureKey else lookupKey if lookupKey in self.contracts: return(self.contracts[lookupKey]) compiledCode = ContractsFixture.getCompiledCode(resolvedPath) # abstract contracts have a 0-length array for bytecode if len(compiledCode) == 0: print "Skipping upload of " + lookupKey + " because it had no bytecode (likely a abstract class/interface)." return None if signatureKey not in ContractsFixture.signatures: ContractsFixture.signatures[signatureKey] = ContractsFixture.generateSignature(resolvedPath) signature = ContractsFixture.signatures[signatureKey] contractTranslator = ContractTranslator(signature) if len(constructorArgs) > 0: compiledCode += contractTranslator.encode_constructor_arguments(constructorArgs) contractAddress = bytesToHexString(self.chain.contract(compiledCode, language='evm', startgas=long(6.7 * 10**6))) contract = ABIContract(self.chain, contractTranslator, contractAddress) self.contracts[lookupKey] = contract return(contract)
def __init__( self, sender, abi, contract_address, call_function, transact_function, estimate_function=None): sender = normalize_address(sender) contract_address = normalize_address(contract_address) translator = ContractTranslator(abi) self.abi = abi self.call_function = call_function self.contract_address = contract_address self.estimate_function = estimate_function self.sender = sender self.transaction_function = transact_function self.translator = translator self.valid_kargs = {'gasprice', 'startgas', 'value'}
def deploy_solidity_contract_with_args(chain, solc_config_sources, allow_paths, contract_file, contract_name, startgas, args=[], contract_creator=tester.k0): 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=contract_creator ) contract = tester.ABIContract(chain, ct, address) return contract
def register_registry(self, registry): """ Register the registry and intialize all the related assets and channels. """ translator = ContractTranslator(REGISTRY_ABI) assetadded = registry.assetadded_filter() all_manager_addresses = registry.manager_addresses() self.start_event_listener( 'Registry {}'.format(pex(registry.address)), assetadded, translator, ) self.registries.append(registry) for manager_address in all_manager_addresses: channel_manager = self.chain.manager(manager_address) self.register_channel_manager(channel_manager)
def setup(host, port, contract, gas, gas_price, private_key): gas = int(gas) gas_price = int(gas_price) json_rpc = EthJsonRpc(host, port) coinbase = json_rpc.eth_coinbase()["result"] if private_key: print "Your address for your private key: {}".format( privtoaddr(private_key.decode('hex')).encode('hex')) else: print "Your coinbase: {}".format(coinbase) contract_abi = json.loads( '[{"inputs": [], "constant": true, "type": "function", "name": "startDate", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "CROWDFUNDING_PERIOD", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "emergencyCall", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [{"type": "address", "name": "singularDTVFundAddress"}, {"type": "address", "name": "singularDTVTokenAddress"}], "constant": false, "type": "function", "name": "setup", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "withdrawFunding", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "fundBalance", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "singularDTVFund", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "baseValue", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "TOKEN_TARGET", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "singularDTVToken", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "owner", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [{"type": "uint256", "name": "valueInWei"}], "constant": false, "type": "function", "name": "changeBaseValue", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [{"type": "address", "name": ""}], "constant": true, "type": "function", "name": "investments", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "fund", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "stage", "outputs": [{"type": "uint8", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "updateStage", "outputs": [{"type": "uint8", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "valuePerShare", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "TOKEN_LOCKING_PERIOD", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "campaignEndedSuccessfully", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "workshopWaited2Years", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "CAP", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "withdrawForWorkshop", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "type": "constructor"}]' ) translator = ContractTranslator(contract_abi) data = translator.encode("emergencyCall", ()).encode("hex") bc_return_val = json_rpc.eth_call(to_address=contract, data=data)["result"] result_decoded = translator.decode("emergencyCall", bc_return_val[2:].decode("hex"))[0] if result_decoded: if private_key: address = privtoaddr(private_key.decode('hex')) nonce = int( json_rpc.eth_getTransactionCount('0x' + address.encode('hex')) ["result"][2:], 16) tx = Transaction(nonce, gas_price, gas, contract, 0, data.decode('hex')) tx.sign(private_key.decode('hex')) raw_tx = rlp.encode(tx).encode('hex') transaction_hash = json_rpc.eth_sendRawTransaction( "0x" + raw_tx)["result"] else: transaction_hash = json_rpc.eth_sendTransaction( coinbase, to_address=contract, data=data, gas=gas, gas_price=gas_price)["result"] wait_for_transaction_receipt(json_rpc, transaction_hash) print 'Transaction {} for contract {} completed.'.format( "emergencyCall", contract)
def register_channel_manager(self, channel_manager): """ Discover and register the channels for the given asset. """ translator = ContractTranslator(CHANNEL_MANAGER_ABI) # To avoid missing changes, first create the filter, call the # contract and then start polling. channelnew = channel_manager.channelnew_filter() all_netting_contracts = channel_manager.channels_by_participant( self.address) task_name = 'ChannelManager {}'.format(pex(channel_manager.address)) channel_listener = LogListenerTask( task_name, channelnew, self.on_event, translator, ) channel_listener.start() self.event_listeners.append(channel_listener) asset_address_bin = channel_manager.asset_address() channel_manager_address_bin = channel_manager.address edges = channel_manager.channels_addresses() channel_graph = ChannelGraph(edges) asset_manager = AssetManager( self, asset_address_bin, channel_manager_address_bin, channel_graph, ) self.managers_by_asset_address[asset_address_bin] = asset_manager self.managers_by_address[channel_manager_address_bin] = asset_manager for netting_contract_address in all_netting_contracts: asset_manager.register_channel_by_address( netting_contract_address, self.config['reveal_timeout'], )
def contract(self, sourcecode, args=[], sender=k0, value=0, language=None, l=None, startgas=STARTGAS, gasprice=GASPRICE): assert not (l and language) language = l or language if language == 'evm': assert len(args) == 0 return self.tx(sender=sender, to=b'', value=value, data=sourcecode, startgas=startgas, gasprice=gasprice) else: compiler = languages[language] interface = compiler.mk_full_signature(sourcecode) ct = ContractTranslator(interface) code = compiler.compile( sourcecode) + (ct.encode_constructor_arguments(args) if args else b'') addr = self.tx( sender=sender, to=b'', value=value, data=code, startgas=startgas, gasprice=gasprice) return ABIContract(self, ct, addr)
def send_transaction(self, contract, name, params): contract_address = self.replace_address(contract) contract_abi = self.contract_abis[contract] translator = ContractTranslator(contract_abi) data = translator.encode(name, [self.replace_address(p) for p in params]).encode("hex") logging.info('Try to send {} transaction to contract {}.'.format( name, contract)) if self.private_key: raw_tx = self.get_raw_transaction(data, contract_address) tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx) while 'error' in tx_response: logging.info('Transaction failed with error {}. Retry!'.format( tx_response['error'])) time.sleep(5) tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx) else: tx_response = self.json_rpc.eth_sendTransaction( self.user_address, to_address=contract_address, data=data, gas=self.gas, gas_price=self.gas_price) while 'error' in tx_response: logging.info('Transaction failed with error {}. Retry!'.format( tx_response['error'])) time.sleep(5) tx_response = self.json_rpc.eth_sendTransaction( self.user_address, to_address=contract_address, data=data, gas=self.gas, gas_price=self.gas_price) transaction_hash = tx_response['result'] self.wait_for_transaction_receipt(transaction_hash) logging.info('Transaction {} for contract {} completed.'.format( name, contract))
def __init__(self, sender, abi, address, call_func, transact_func, estimate_function=None): sender = normalize_address(sender) self.abi = abi self.address = address = normalize_address(address) self.translator = ContractTranslator(abi) for function_name in self.translator.function_data: function_proxy = MethodProxy( sender, address, function_name, self.translator, call_func, transact_func, estimate_function, ) type_argument = self.translator.function_data[function_name][ 'signature'] arguments = [ '{type} {argument}'.format(type=type_, argument=argument) for type_, argument in type_argument ] function_signature = ', '.join(arguments) function_proxy.__doc__ = '{function_name}({function_signature})'.format( function_name=function_name, function_signature=function_signature, ) setattr(self, function_name, function_proxy)
def all_contract_events( rpc: JSONRPCClient, contract_address: str, abi, start_block: Union[str, int] = 0, end_block: Union[str, int] = 'latest') -> List[Dict]: """Find and decode all events for a deployed contract given its `contract_address` and `abi`. Args: rpc: client instance. contract_address: hex encoded contract address. abi: the contract's ABI. start_block: read event-logs starting from this block number (default: 0). end_block: read event-logs up to this block number (default: 'latest'). Returns: A list of all events from the given contract. """ translator = ContractTranslator(abi) events_raw = all_contract_events_raw( rpc, contract_address, start_block=start_block, end_block=end_block ) events = list() for event_encoded in events_raw: topics_ids = [ topic_decoder(topic) for topic in event_encoded['topics'] ] event_data = data_decoder(event_encoded['data']) event = translator.decode_event(topics_ids, event_data) events.append(event) return events
def register_registry(self, registry): """ Register the registry and intialize all the related assets and channels. """ translator = ContractTranslator(REGISTRY_ABI) assetadded = registry.assetadded_filter() all_manager_addresses = registry.manager_addresses() asset_listener = LogListenerTask( assetadded, self.on_event, translator, ) asset_listener.start() self.event_listeners.append(asset_listener) self.registries.append(registry) for manager_address in all_manager_addresses: channel_manager = self.chain.manager(manager_address) self.register_channel_manager(channel_manager)
def init_contracts(nodes): result = dict() tester_state = Chain() for address, contract in CONTRACTS.iteritems(): contract_path = path.join(CONTRACTS_DIR, contract['file']) simple_compiled = compile_file(contract_path) simple_data = solidity_get_contract_data( simple_compiled, contract_path, contract['name'], ) ct = ContractTranslator(simple_data['abi']) if (address == '0x00000000000000000000000000000000013241a3'): extra = (ct.encode_constructor_arguments([nodes[address]]) if nodes[address] else b'') else: extra = (ct.encode_constructor_arguments([nodes[address][0], nodes[address][1]]) if nodes[address] else b'') print(binascii.hexlify(simple_data['bin'] + extra)) abi_address = tester_state.contract(simple_data['bin'] + extra) tester_state.mine() account = tester_state.chain.state.account_to_dict(abi_address) result[address] = {'code': account['code'], 'storage': account['storage'], 'nonce': account['nonce']} return result
def init_normal_contracts(self): """Compile normal contracts from files and construct by arguments. """ flags = [ 'checkCallPermission', 'checkSendTxPermission', 'checkCreateContractPermission', 'checkQuota', 'checkFeeBackPlatform', 'autoExec' ] ncinfo = self.contracts_list['NormalContracts'] for name, info in ncinfo.items(): addr = info['address'] path = os.path.join(self.contracts_dir, info['file']) data = self.compile_to_data(name, path) self.write_docs(name, data) ctt = ContractTranslator(data['abi']) args = self.contracts_args.get(name) if name == 'SysConfig': args['flags'] = [] for flag in flags: args['flags'].append(args[flag]) args.pop(flag) extra = b'' if not args else ctt.encode_constructor_arguments( [arg for arg in args.values()]) self.mine_contract_on_chain_tester(addr, data['bin'] + extra)
def createYesNoMarket(self, universe, endTime, feeDivisor, denominationToken, oracle, sender=tester.k0, topic="", description="description", extraInfo=""): marketAddress = universe.createYesNoMarket(endTime, feeDivisor, denominationToken.address, oracle, topic, description, extraInfo, sender=sender) assert marketAddress market = ABIContract( self.chain, ContractTranslator(ContractsFixture.signatures['Market']), marketAddress) return market
def register_channel_manager(self, channel_manager): """ Discover and register the channels for the given token. """ translator = ContractTranslator(CHANNEL_MANAGER_ABI) # To avoid missing changes, first create the filter, call the # contract and then start polling. channelnew = channel_manager.channelnew_filter() all_netting_contracts = channel_manager.channels_by_participant( self.address) self.start_event_listener( 'ChannelManager {}'.format(pex(channel_manager.address)), channelnew, translator, ) token_address_bin = channel_manager.token_address() channel_manager_address_bin = channel_manager.address edges = channel_manager.channels_addresses() channel_graph = ChannelGraph(edges) token_manager = TokenManager( self, token_address_bin, channel_manager_address_bin, channel_graph, ) self.managers_by_token_address[token_address_bin] = token_manager self.managers_by_address[channel_manager_address_bin] = token_manager for netting_contract_address in all_netting_contracts: token_manager.register_channel_by_address( netting_contract_address, self.config['reveal_timeout'], )
def test_event(): event_abi = [{ 'name': 'Test', 'anonymous': False, 'inputs': [ { 'indexed': False, 'name': 'a', 'type': 'int256' }, { 'indexed': False, 'name': 'b', 'type': 'int256' }, ], 'type': 'event', }] contract_abi = ContractTranslator(event_abi) normalized_name = normalize_name('Test') encode_types = ['int256', 'int256'] id_ = event_id(normalized_name, encode_types) topics = [id_] data = encode_abi(encode_types, [1, 2]) result = contract_abi.decode_event(topics, data) assert result['_event_type'] == b'Test' assert result['a'] == 1 assert result['b'] == 2
def tester_deploy_contract( tester_state, private_key, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) all_contracts = _solidity.compile_file(contract_path, libraries=dict()) contract_key = solidity_get_contract_key(all_contracts, contract_path, contract_name) contract = all_contracts[contract_key] contract_interface = contract['abi'] log.info('Deploying "{}" contract'.format(contract_file)) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build(contract_key, dependencies) log.info('Deploying dependencies: {}'.format(str(deployment_order))) deployment_order.pop() # remove `contract_name` from the list libraries = dict() for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = _solidity.solidity_resolve_symbols( dependency_contract['bin_hex'], libraries, ) bytecode = decode_hex(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') libraries[deploy_contract] = encode_hex(contract_address) hex_bytecode = _solidity.solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = hex_bytecode.decode('hex') contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments(constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] log.info('Creating contract {}'.format(contract_name)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
def register_channel(self, netting_channel, reveal_timeout): """ Register a new channel. Args: netting_channel (network.rpc.client.NettingChannel): The netting channel proxy. reveal_timeout (int): Minimum number of blocks required by this node to see a secret. Raises: ValueError: - If raiden.address is not one of the participants in the netting channel. - If the contract's settle_timeout is smaller than the reveal_timeout. """ # pylint: disable=too-many-locals translator = ContractTranslator(NETTING_CHANNEL_ABI) # Race condition: # - If the filter is installed after the call to `details` a deposit # can be missed, to avoid this the listener is installed first. # - Because of the above a `ChannelNewBalance` event can be polled # after the `details` calls succeds so the effects must be # idempotent. netting_channel_events = netting_channel.all_events_filter() channel_details = netting_channel.detail(self.raiden.address) our_state = ChannelEndState( channel_details['our_address'], channel_details['our_balance'], netting_channel.opened, ) partner_state = ChannelEndState( channel_details['partner_address'], channel_details['partner_balance'], netting_channel.opened, ) external_state = ChannelExternalState( self.raiden.alarm.register_callback, self.register_channel_for_hashlock, self.raiden.get_block_number, netting_channel, ) channel = Channel( our_state, partner_state, external_state, self.token_address, reveal_timeout, channel_details['settle_timeout'], ) self.partneraddress_channel[partner_state.address] = channel self.address_channel[netting_channel.address] = channel self.raiden.start_event_listener( 'NettingChannel Event {}'.format(pex(netting_channel.address)), netting_channel_events, translator, )
def create_abi(path): path, extra_args = get_dirs(path) abi = _solidity.compile_last_contract(path, combined='abi', extra_args=extra_args)['abi'] return ContractTranslator(abi)
contract_instance = w3.eth.contract(abi['abi'], contract_address, ContractFactoryClass=ConciseContract) # check bumber of tokens # tokens = contract_instance.tokensOfOwner(badge_owner); # print('Tokens: {}'.format(tokens)) # Contract creates new badge transact = {"gas": gas, "from": sender_address} # Sending transaction # contract_instance.create(donation_tx, badge_title, badge_owner, transact=transact) # Send raw transaction ct = ContractTranslator(abi['abi']) txHash = Web3.toInt(hexstr=donation_tx) txdata = ct.encode_function_call("create", [txHash, challenge, badge_owner]) # Load data with configuration and nonce # data = json.load(open('data.txt', 'r')) # if 'nonce' not in data: # data['nonce'] = w3.eth.getTransactionCount(sender_address) # else: # nonce = data["nonce"] + 1 # nonce = max(nonce, w3.eth.getTransactionCount(sender_address)) nonce = w3.eth.getTransactionCount(sender_address, block_identifier="pending") tx = Transaction( nonce=nonce,
def purity_checker_ct(): return ContractTranslator(PURITY_CHECKER_ABI)
def casper_ct(casper_abi): return ContractTranslator(casper_abi)
def deploy_solidity_contract( self, # pylint: disable=too-many-locals sender, contract_name, all_contracts, libraries, constructor_parameters, contract_path=None, timeout=None, gasprice=GAS_PRICE): """ Deploy a solidity contract. Args: sender (address): the sender address contract_name (str): the name of the contract to compile all_contracts (dict): the json dictionary containing the result of compiling a file libraries (list): A list of libraries to use in deployment constructor_parameters (tuple): A tuple of arguments to pass to the constructor contract_path (str): If we are dealing with solc >= v0.4.9 then the path to the contract is a required argument to extract the contract data from the `all_contracts` dict. timeout (int): Amount of time to poll the chain to confirm deployment gasprice: The gasprice to provide for the transaction """ if contract_name in all_contracts: contract_key = contract_name elif contract_path is not None: _, filename = os.path.split(contract_path) contract_key = filename + ':' + contract_name if contract_key not in all_contracts: raise ValueError('Unknown contract {}'.format(contract_name)) else: raise ValueError( 'Unknown contract {} and no contract_path given'.format( contract_name)) libraries = dict(libraries) contract = all_contracts[contract_key] contract_interface = contract['abi'] symbols = solidity_unresolved_symbols(contract['bin_hex']) if symbols: available_symbols = map(solidity_library_symbol, all_contracts.keys()) unknown_symbols = set(symbols) - set(available_symbols) if unknown_symbols: msg = 'Cannot deploy contract, known symbols {}, unresolved symbols {}.'.format( available_symbols, unknown_symbols, ) raise Exception(msg) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build( contract_key, dependencies) deployment_order.pop() # remove `contract_name` from the list log.debug('Deploying dependencies: {}'.format( str(deployment_order))) for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = solidity_resolve_symbols( dependency_contract['bin_hex'], libraries) bytecode = unhexlify(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode transaction_hash_hex = self.send_transaction( sender, to='', data=bytecode, gasprice=gasprice, ) transaction_hash = unhexlify(transaction_hash_hex) self.poll(transaction_hash, timeout=timeout) receipt = self.eth_getTransactionReceipt(transaction_hash) contract_address = receipt['contractAddress'] # remove the hexadecimal prefix 0x from the address contract_address = contract_address[2:] libraries[deploy_contract] = contract_address deployed_code = self.eth_getCode(unhexlify(contract_address)) if deployed_code == '0x': raise RuntimeError( 'Contract address has no code, check gas usage.') hex_bytecode = solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = unhexlify(hex_bytecode) contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments( constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] transaction_hash_hex = self.send_transaction( sender, to='', data=bytecode, gasprice=gasprice, ) transaction_hash = unhexlify(transaction_hash_hex) self.poll(transaction_hash, timeout=timeout) receipt = self.eth_getTransactionReceipt(transaction_hash) contract_address = receipt['contractAddress'] deployed_code = self.eth_getCode(unhexlify(contract_address[2:])) if deployed_code == '0x': raise RuntimeError( 'Deployment of {} failed. Contract address has no code, check gas usage.' .format(contract_name, )) return self.new_contract_proxy( contract_interface, contract_address, )
def encode_transfer_data(recipient_address, amount: EthereumTokenAmount): translator = ContractTranslator(EIP20_ABI) encoded_data = translator.encode_function_call( "transfer", (recipient_address, amount.as_wei)) return f"0x{encoded_data.hex()}"
'inputs': [{ 'name': 'addr', 'type': 'address' }], 'outputs': [{ 'name': 'out', 'type': 'bool' }] }] viper_rlp_decoder_address = viper_rlp_decoder_tx.creates sig_hasher_address = sig_hasher_tx.creates casper_code = open('simple_casper.v.py').read() casper_bytecode = compiler.compile(casper_code) casper_abi = compiler.mk_full_signature(casper_code) casper_ct = ContractTranslator(casper_abi) def custom_chain(tester, alloc={}, genesis_gas_limit=4712388, min_gas_limit=5000, startgas=3141592): # alloc for i in range(9): alloc[utils.int_to_addr(i)] = {'balance': 1} # genesis from ethereum.genesis_helpers import mk_basic_state header = { "number": 0, "gas_limit": genesis_gas_limit,
from ethereum.abi import ContractTranslator GOLEM_FACTORY = '0x7da82C7AB4771ff031b66538D2fB9b0B047f6CF9' MIGRATION_MASTER = '0x7da82C7AB4771ff031b66538D2fB9b0B047f6CF9' START_BLOCK = 2607800 END_BLOCK = 2734100 version_info = subprocess.check_output(['solc', '--version']) print(version_info) contract = compile_contract('contracts/Token.sol', 'GolemNetworkToken') init = contract['bin_hex'] abi = contract['abi'] translator = ContractTranslator(abi) args = translator.encode_constructor_arguments( (GOLEM_FACTORY, MIGRATION_MASTER, START_BLOCK, END_BLOCK) ).encode('hex') print('\nGolem Network Token') print('- Factory: ' + GOLEM_FACTORY) print('- Migration Master: ' + MIGRATION_MASTER) print('- Start: ', START_BLOCK) print('- End: ', END_BLOCK) print() print('Deploy:') print(init + args) print() print('Args:') print(args)
def getOrCreateChildUniverse(self, parentUniverse, market, payoutDistribution): assert payoutDistributionHash childUniverseAddress = parentUniverse.getOrCreateChildUniverse(payoutDistribution) assert childUniverseAddress childUniverse = ABIContract(self.chain, ContractTranslator(ContractsFixture.signatures['Universe']), childUniverseAddress) return childUniverse
def getShareToken(self, market, outcome): shareTokenAddress = market.getShareToken(outcome) assert shareTokenAddress shareToken = ABIContract(self.chain, ContractTranslator(ContractsFixture.signatures['ShareToken']), shareTokenAddress) return shareToken