def compile(self, optimize=False, optimize_runs=200): '''Compile & get Contract's Application Binary Interface & Bytecode''' src = open(self.fname).read() if optimize: compiled_sol = compile_source(src, optimize=optimize, optimize_runs=optimize_runs) else: compiled_sol = compile_source(src, optimize=optimize) interface = compiled_sol['<stdin>:{}'.format( basename(self.fname.rstrip('.sol')))] self.bytecode = interface['bin'] self.abi = interface['abi'] return self
def cobra_file(self, file_name, import_remapping=None): import_remappings = ["=", "-"] if import_remapping is not None: for remapping in import_remapping: if not remapping.startswith("="): import_remappings.append("=" + remapping) else: import_remappings.append(remapping) if file_name.endswith(".sol"): compiled_json = compile_source( self.file_reader(file_name), import_remappings=import_remappings) convert_json = self.cobra_converter(compiled_json) self.cobra_test_json(convert_json) elif file_name.endswith(".json"): read_json = self.file_reader(file_name) load_json = self.json_loader(read_json) convert_json = self.cobra_converter(load_json) self.cobra_test_json(convert_json) elif file_name.endswith(".yaml"): read_yaml = self.file_reader(file_name) load_yaml = self.yaml_loader(read_yaml) self.cobra_test_yaml(load_yaml) else: with pytest.raises(FileNotFoundError, message="[Cobra] Can't find this type of extension ['.sol', '.json' or '.yaml']"): pass return self.contracts
def setUp(self): self.contract_source_code = ''' pragma solidity ^0.4.0; contract Greeter { string public greeting; function Greeter() { greeting = 'Hello there'; } function setGreeting(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } } ''' compiled_sol = compile_source( self.contract_source_code) # Compiled source code self.contract_interface = compiled_sol['<stdin>:Greeter'] # web3.py instance self.w3 = Web3(EthereumTesterProvider()) # Instantiate and deploy contract self.contract = self.w3.eth.contract( abi=self.contract_interface['abi'], bytecode=self.contract_interface['bin']) # Get transaction hash from deployed contract self.tx_hash = self.contract.deploy(transaction={ 'from': self.w3.eth.accounts[0], 'gas': 410000 })
def initHandler(self): contract_source_code = self.getSourceCode('GreenElephantContract.sol') compiled_sol = compile_source( contract_source_code) # Compiled source code contract_interface = compiled_sol['<stdin>:GreenElephantContract'] self.w3 = Web3(HTTPProvider("http://127.0.0.1:8545")) DefaultAddres = self.w3.eth.accounts[0] print(DefaultAddres) print("Eth value: " + str( int( self.w3.fromWei( self.w3.eth.getBalance( '0x12890D2cce102216644c59daE5baed380d84830c'), 'ether')))) self.w3.personal.unlockAccount(self.w3.eth.accounts[0], 'password') self.w3.eth.defaultAccount = self.w3.eth.accounts[0] GreenElephantContract = self.w3.eth.contract( abi=contract_interface['abi'], bytecode=contract_interface['bin']) # Submit the transaction that deploys the contract tx_hash = GreenElephantContract.constructor().transact() tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash) # Create the contract instance with the newly-deployed address self.greenElephantContract = self.w3.eth.contract( address=tx_receipt.contractAddress, abi=contract_interface['abi'], ) self.register('admin', 'admin') self.giveAdmin('admin') self.setDefaultAccount() return
def get_contract(self): with open(self.sol_path) as f: contract_source_code = f.read() compiled_sol = compile_source( contract_source_code) # Compiled source code contract_interface = compiled_sol['<stdin>:Lottery'] w3 = Web3(web3.HTTPProvider(config["url"])) self.w3 = w3 # set pre-funded account as sender acct = None if not self.account_key: if config["one_ether"].get("account"): w3.eth.defaultAccount = account.address else: w3.eth.defaultAccount = w3.eth.accounts[0] print("use the default accounts[0]") else: acct = w3.eth.account.privateKeyToAccount(self.account_key) w3.eth.defaultAccount = acct.address # Instantiate and deploy contract compiled = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) # deploy contract if not self.contract_address: if not acct: raise Exception( "account key should be set when there is no contract!") contract_ = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) construct_txn = contract_.constructor().buildTransaction({ 'from': acct.address, 'nonce': w3.eth.getTransactionCount(acct.address), 'gasPrice': self.w3.eth.gasPrice }) signed = acct.signTransaction(construct_txn) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) print("waiting for contract receipted", end="", flush=True) count = 0 tx_receipt = None while not tx_receipt and (count < 300): time.sleep(1) tx_receipt = w3.eth.getTransactionReceipt(tx_hash) print(".", end="", flush=True) print() if not tx_receipt: raise Exception("timeout for contract receipted!") self.contract_address = tx_receipt.contractAddress # Create the contract instance with the newly-deployed address self.contract = w3.eth.contract( address=self.contract_address, abi=contract_interface['abi'], ) print("contract address: {}".format(self.contract_address))
def stoken(token,reciver,supply,name): filename = os.path.join( os.path.dirname(__file__), 'chalicelib', 'STOken.sol') contractfile = open(filename) contract = contractfile.read() replaced_contents = contract.replace('[ISUPPLY]', str(int(supply))) # total supply replaced_contents = replaced_contents.replace('[UNLOCKTIME]', str(1546412481)) #lockout time replaced_contents = replaced_contents.replace('[TOKENNAME]', str(name)) #name of token replaced_contents = replaced_contents.replace('[TOKENSYMBOL]', str(token)) # symbol replaced_contents = replaced_contents.replace('[TOKENRECIVER]', tron.address.to_hex(str(reciver))) #hex compiled_sol = compile_source(replaced_contents) contract_interface = compiled_sol['<stdin>:STOken'] contract_byte_code = contract_interface['bin'] hello = tron.trx.contract( abi=contract_interface['abi'], bytecode=contract_byte_code, ) # Submit the transaction that deploys the contract tx_data = hello.deploy( fee_limit=10**9, call_value=0, consume_user_resource_percent=1 ) #print (compiled_sol) sign = tron.trx.sign(tx_data) result = tron.trx.broadcast(sign) #result["easyaddress"] = #app.log.debug("work statement\n========="+json.dumps(result)) result["contract_address"] = tron.address.from_hex(result["transaction"]["contract_address"]).decode() return result
def call_function(web3, private_key, to, value, call_func, *argv): name, code = parse_code(web3, to) compiled_sol = compile_source(Web3.toText(code)) contract_interface = compiled_sol["<stdin>:" + Web3.toText(name)] contract = web3.eth.contract(abi=contract_interface["abi"], bytecode=contract_interface["bin"]) acct = web3.eth.account.privateKeyToAccount(private_key) fun = contract.functions[call_func] tx = fun(*argv).buildTransaction({ "from": acct.address, "to": to, "value": value, "nonce": web3.eth.getTransactionCount(acct.address) }) signed = acct.signTransaction(tx) print("Tx Hash : " + web3.eth.sendRawTransaction(signed.rawTransaction).hex())
def get_contract_interface(filepath, contract_name): contract_code_file = open(filepath, "r") contract_source_code = contract_code_file.read() compiled_sol = compile_source(contract_source_code) # Compiled source code contract_interface = compiled_sol[f'<stdin>:{contract_name}'] return contract_interface
def deploy(contract_source_code, w3): # 编译合约源码 compiled_sol = compile_source(contract_source_code) contract_interface = compiled_sol['<stdin>:Greeter'] # 生成合约对象 Contract = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) # 部署合约 tx_hash = Contract.constructor().transact() # 等待合约部署交易完成 tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) # print(tx_receipt) # 将合约地址和abi进行json化保存到本地文件 contractInfo = { 'address': tx_receipt.contractAddress, 'abi': contract_interface['abi'] } with open('./cinfo.json', 'w') as wf: wf.write(json.dumps(contractInfo)) return contractInfo
def register(self): if (self.address == None) or (self.abi == None): contract_source_code = None try: contract_source_code = self.__readContract() except IOError: return -1 compiled = compile_source(contract_source_code,import_remappings=["-"]) # Compiled source code contract_interface = compiled['<stdin>:Log'] #Instantiate and deploy contract Log = self.w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) salt = self.__generateSalt() pk = None while pk == None: try: pk = self.__getPrivateKey() except ValueError: pass ivs = self.__generateIvs() salt = cipher.encrypt(salt,pk,ivs) # Submit the transaction that deploys the contract tx_hash = Log.constructor(salt).transact() # Wait for the transaction to be mined, and get the transaction receipt tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash) # Create the contract instance with the newly-deployed address self.contract = self.w3.eth.contract( address=tx_receipt.contractAddress, abi=contract_interface['abi'], ) if self.contract.functions.getElem().call() == 0: self.address = tx_receipt.contractAddress self.abi = contract_interface['abi'] my_file = Path(self.pathInfo) with open(my_file,'w') as f: f.write(tx_receipt.contractAddress + '\n') f.write(str(contract_interface['abi']) + '\n') my_file = Path(self.pathIvs) with open(my_file,'wb') as f: for i in range(len(ivs)): f.write(ivs[i]) return 0 else: return -1 else: return 1
def compile(): global contract_interface global producer global w3 global contract compiled_sol = compile_source(contract_source_code) # Compiled source code s = json.dumps(compiled_sol["<stdin>:Greeter"], sort_keys=False, indent=4, separators=(',', ': ')) # print(s) contract_interface = compiled_sol['<stdin>:Greeter'] #print(contract_interface) # web3.py instance #w3 = Web3(TestRPCProvider()) #w3 = Web3(HTTPProvider()) address = w3.eth.accounts[0] # Instantiate and deploy contract contract = w3.eth.contract(contract_interface['abi'], bytecode=contract_interface['bin']) #print(contract_interface['abi']) print(contract_interface['bin']) json.dumps(contract_interface['abi'], sort_keys=False, indent=4, separators=(',', ': ')) print('+++++++++w3.eth.accounts[0]:', address) print('+++++++++w3.eth.blockNumber:', w3.eth.blockNumber)
def compiler(source, output, java, mode='file'): # 读取合约 contracts = [] if mode != 'file': compileSol = compile_source(source) else: try: compiledSol = compile_files(source.split(" ")) except Exception as ex: print('compile file error: ' + str(ex)) try: # 编译合约源码 # contractId, contractInterface = compiledSol.popitem() for contractId, contractInterface in compiledSol.items(): ctt = {} ast = contractInterface['ast']['children'] for item in ast: if len(item['attributes'].keys()) > 2: if str(contractId).split(':')[-1] == str( item['attributes']['name']): # ctt['name'] = contractId ctt['name'] = str(contractId).split(':')[-1] ctt['type'] = item['attributes']['contractKind'] ctt['abi'] = contractInterface['abi'] ctt['bytecode'] = contractInterface['bin'] contracts.append(ctt) if abigen != '': abigen(contracts[-1], output, abigen) if output != '': with open(output, 'w', encoding='utf-8') as wf: wf.write(json.dumps({'contracts': contracts})) except Exception as ex: print('compile error: ' + str(ex)) return contracts
def deploy_contracts(w3: Web3, account: str, total_storage: int): pp = pprint.PrettyPrinter(indent=4) with open(os.path.dirname(os.path.abspath(__file__)) + '/../contracts/token.sol', 'r') as tokenContract: # Read the files and return the ConsiseContracts token_source = tokenContract.read() compiled_token = compile_source(token_source) # Get the compiled contracts ready for deployment token_interface = compiled_token['<stdin>:IoToken'] # Create contract Token = w3.eth.contract( abi = token_interface['abi'], bytecode = token_interface['bin']) # Deploy the Token (We configure storage available as 1TB) tx_hash = Token.constructor(total_storage, 210000,account).transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) # Create contract instance iot_token = w3.eth.contract( address = tx_receipt.contractAddress, abi = token_interface['abi']) pp.pprint(token_interface['abi']) print('Contract address', tx_receipt.contractAddress) return iot_token
def compile_contract(contract_name): """ compiles the given contract (from the ./contracts folder) and returns its ABI interface """ path = os.getcwd() if path.endswith('client'): path = f'../contracts/{contract_name}.sol' else: path = f'./contracts/{contract_name}.sol' h = filehash(path) interface = cache.get(h) if interface: return interface with open(path) as f: src = f.read() for i in solc.compile_source(src, optimize=True).values(): interface = i break cache[h] = interface return interface
def create_contract(): provider = Web3.IPCProvider(os.path.join(os.path.dirname(__file__), '../DesignNode/geth.ipc')) w3 = Web3(provider) with open('../contracts/Designdb.sol', 'r') as source_file: contract_source = source_file.read() compiled_sol = compile_source(contract_source) contract_interface = compiled_sol['<stdin>:DesignDB'] w3.eth.defaultAccount = w3.eth.accounts[0] Agreement = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) passphrase = getpass.getpass("Enter passphrase: ") w3.personal.unlockAccount(w3.eth.accounts[0], passphrase) w3.miner.start(4) tx_hash = Agreement.constructor().transact() print("\nTransaction hash: ", Web3.toHex(tx_hash)) print("Waiting for transaction to be mined...") tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) print("Contract successfully deployed!!") print("Contract address: ", tx_receipt.contractAddress) with open('contract_address','w') as file: file.write(tx_receipt.contractAddress) return
def create_vote_contract_definition(): with open(app.config['VOTE_CONTRACT_SOURCE_PATH']) as f: source_code = f.read() compiled_sol = compile_source(source_code) contract_interface = compiled_sol['<stdin>:Vote'] return web3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
def make_contract(arguments): w3.eth.defaultAccount = Account.privateKeyToAccount( settings.INFURA_ETH_KEY).address nonce = w3.eth.getTransactionCount(w3.eth.defaultAccount) gasprice = w3.eth.gasPrice compiled_sol = compile_source(arguments.contract) contract_interface = compiled_sol['<stdin>:%s' % arguments.name] Sol = w3.eth.contract( abi=contract_interface['abi'], bytecode=contract_interface['bin'], ) if arguments.constructors: deploy = Sol.constructor(**arguments.constructors).buildTransaction( dict(nonce=nonce, gasPrice=gasprice)) else: deploy = Sol.constructor().buildTransaction( dict(nonce=nonce, gasPrice=gasprice)) signed = w3.eth.account.signTransaction(deploy, settings.INFURA_ETH_KEY) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash, timeout=300) gas = tx_receipt.gasUsed #gas = w3.eth.estimateGas(deploy) address = tx_receipt.contractAddress return (address, tx_hash, gas)
def deploy_contract(contract_source_code, contract_name): compiled_sol = compile_source(contract_source_code) interface_key = '<stdin>:' + contract_name contract_interface = compiled_sol[interface_key] acct = w3.eth.account.privateKeyToAccount(wallet_privateKey) nonce = w3.eth.getTransactionCount(wallet_address) contract = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) tx_dict = contract.constructor().buildTransaction({ 'from': acct.address, 'chainId': chain_id, 'gas': 3000000, 'gasPrice': 1000000000, 'nonce': nonce }) print('\n \n DEPLOYING CONTRACT: {}'.format(contract_name)) tx = complete_transaction(tx_dict) if (tx['status'] == 'failed'): print( '\n Contract deployment failed. Error: {}. Exiting script.'.format( tx['error'])) exit() address = tx['txn_receipt']['contractAddress'] contract_instance = w3.eth.contract(address=address, abi=contract_interface['abi']) return {'contract': contract_instance, 'address': address}
def _select_fn(self): contract_path = self.browser_value() contract_source_code = open(contract_path, 'r').read() try: compiled_sol = compile_source(contract_source_code, optimize=True) # Compiled source code except FileNotFoundError: self.dapp.add_message_dialog("Compile failed. Do you have solc installed?") self.close() #contract_interface = compiled_sol['<stdin>:SLoader'] compiled_sol_values = list(compiled_sol.values()) contract_interface = compiled_sol_values[0] new_contract = self.dapp.node.w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) # copy abi to the clipboard pyperclip.copy(str(contract_interface['abi'])) self.dapp.add_transaction_dialog( lambda: new_contract.constructor(), title="Deploy", gas_limit=900000 ) self.dapp.add_message_dialog("The contract ABI has been copied to your clipboard") self.close()
def compiler(source, mode='file'): # 读取合约 csc = '' contracts = [] if mode != 'file': csc = source else: try: with open(source, 'r', encoding='utf-8') as rf: csc = rf.read() except Exception as ex: print('read file error: ' + str(ex)) try: # 编译合约源码 compiledSol = compile_source(csc) # contractId, contractInterface = compiledSol.popitem() for contractId, contractInterface in compiledSol.items(): ctt = {} ast = contractInterface['ast']['children'] for item in ast: if len(item['attributes'].keys()) > 2: if str(contractId).split(':')[-1] == str( item['attributes']['name']): # ctt['name'] = contractId ctt['name'] = str(contractId).split(':')[-1] ctt['type'] = item['attributes']['contractKind'] ctt['abi'] = contractInterface['abi'] ctt['bytecode'] = contractInterface['bin'] contracts.append(ctt) except Exception as ex: print('compile error: ' + str(ex)) return contracts
def setUp(self): self.contract_source_code = solidity_source compiled_sol = compile_source( self.contract_source_code) # Compiled source code self.contract_interface = compiled_sol['<stdin>:Lottery'] # web3.py instance self.w3 = Web3(EthereumTesterProvider()) # Instantiate and deploy contract self.contract = self.w3.eth.contract( abi=self.contract_interface['abi'], bytecode=self.contract_interface['bin']) # Get transaction hash from deployed contract self.tx_hash = self.contract.deploy(transaction={ 'from': self.w3.eth.accounts[0], 'gas': 4000000 }) # Get tx receipt to get contract address # Contract instance in concise mode tx_receipt = self.w3.eth.getTransactionReceipt(self.tx_hash) contract_address = tx_receipt['contractAddress'] # define it like this is an easier way to call methods, but with less power. e.g can't change from address self.contract_instance_concise = self.w3.eth.contract( self.contract_interface['abi'], contract_address, ContractFactoryClass=ConciseContract) self.contract_instance = self.w3.eth.contract( self.contract_interface['abi'], contract_address)
def printer_friendly_contract(w3): with open('../contracts/Print_Friendly_Agreement.sol', 'r') as source_file: contract_source = source_file.read() compiled_sol = compile_source(contract_source) contract_interface = compiled_sol['<stdin>:Print_Friendly_Agreement'] w3.eth.defaultAccount = w3.eth.accounts[0] Agreement = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) quantity = input("Enter agreement quantity: ") quantity = int(quantity) amount = input("Enter agreement amount: ") amount = int(amount) passphrase = getpass.getpass("Enter passphrase: ") w3.personal.unlockAccount(w3.eth.accounts[0], passphrase) tx_hash = Agreement.constructor(quantity, amount).transact() print("\nTransaction hash: ", Web3.toHex(tx_hash)) w3.miner.start(4) print("Waiting for transaction to be mined...") tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) w3.miner.stop() print("Contract successfully deployed!!") print("Contract address: ", tx_receipt.contractAddress) return
def initiate_task(self, file_path): template = loadJsonFile(path=file_path) task = Task(template) task.description["initiator"] = self.xmpp_id task.description["identifier"] = str(hex(uuid.getnode())) raw_contract_source = requests.get(task.description["contract"]).text compiled_contract = compile_source(raw_contract_source) task_contract_interface = compiled_contract['<stdin>:' + task.description["task"]] w3 = Web3(Web3.HTTPProvider(task.description["blockchain_node"])) task_contract = w3.eth.contract( abi=task_contract_interface['abi'], bytecode=task_contract_interface['bin']) # have to come up with a better method to handle accounts. tx_hash = task_contract.constructor().transact( transaction={ 'from': w3.eth.accounts[0], 'gas': 1000000 }) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) task_contract_address = tx_receipt.contractAddress # set up an event listener on the block chain network_delegation_event = task_contract.eventFilter('network_delegate_registered',\ {'fromBlock':0, 'toBlock':'latest'}) self.blockChainEvents.append(network_delegation_event) print("address of deployed task contract is {}".format( task_contract_address)) task.description["task_contract_address"] = task_contract_address payload = dict(setup="resource_solicitation", msg_type="task_template", \ payload=json.dumps(template)) self.broadcast_queue.put(payload)
def deploy_contract(): compiled_sol = compile_source(contract_source_code) # Compiled source code contract_interface = compiled_sol['<stdin>:CarrierRegistry'] # web3.py instance w3 = Web3(HTTPProvider('http://localhost:8545')) # Instantiate and deploy contract contract = w3.eth.contract(contract_interface['abi'], bytecode=contract_interface['bin']) # Get transaction hash from deployed contract tx_hash = contract.deploy(transaction={ 'from': w3.eth.accounts[0], 'gas': 4100000 }, args=[0, 0]) # print(tx_hash) time.sleep(30) # Get tx receipt to get contract address tx_receipt = w3.eth.getTransactionReceipt(tx_hash) # print(tx_receipt) contract_address = tx_receipt['contractAddress'] # Contract instance in concise mode contract_instance = w3.eth.contract(contract_interface['abi'], contract_address, ContractFactoryClass=ConciseContract) print( str(np.datetime64(datetime.datetime.now())) + " New Contract deployed successfully") return contract_instance, tx_receipt
def cobra_file(self, file_name, import_remappings=None, allow_paths=None): # Import remapping None to empty array if import_remappings is None: import_remappings = [] # Allow path None to current working directory path if allow_paths is None: allow_paths = str() # Fetching solidity file extension if file_name.endswith(".sol"): _import_remappings = ["-"] _import_remappings.extend(import_remappings) compiled_json = compile_source( self.file_reader(file_name), import_remappings=_import_remappings, allow_paths=allow_paths) convert_json = self.cobra_converter(compiled_json) self.cobra_test_json(convert_json) # Fetching compiled json file extension elif file_name.endswith(".json"): read_json = self.file_reader(file_name) load_json = self.json_loader(read_json) convert_json = self.cobra_converter(load_json) self.cobra_test_json(convert_json) # Fetching yaml from cobra framework file extension elif file_name.endswith(".yaml"): read_yaml = self.file_reader(file_name) load_yaml = self.yaml_loader(read_yaml) self.cobra_test_yaml(load_yaml) else: with pytest.raises(FileNotFoundError, message="[ERROR] Can't find this type of extension ['.sol', '.json' or '.yaml']"): pass return self.contracts
def get_contract(): base_url = "https://raw.githubusercontent.com/adriamb/bettingon/96e26fa6faa883119c425c526a20cc542636c7a9/contracts" contract_addr = "0x7B77eBD4760D80A12586097ec1527ff8367a067f" src = "pragma solidity ^0.4.11;\n" + \ get_and_filter(base_url+'/Directory.sol') + \ get_and_filter(base_url+'/PriceUpdater.sol') + \ get_and_filter(base_url+'/Bettingon.sol') compiled = solc.compile_source(src) w3 = web3.Web3(web3.HTTPProvider('http://localhost:8546')) contract_factory = web3.contract.construct_contract_factory( web3=w3, abi=compiled['<stdin>:Bettingon']['abi']) contract = contract_factory(contract_addr) try: contract.call().boat() except web3.exceptions.BadFunctionCallOutput: raise RuntimeError( 'Cannot continue, seems that blockchain node is not yet sync.') return contract
def contract_ready(request): print ('ready section') if 'w3' not in globals(): ethereum_login(request) if 'auction' not in globals(): print ('auction not in globals section') #Find contract addreess pwd = os.path.dirname(__file__) f = open(pwd + '/../contract/address','r') contractAddress = f.read() f.close() #Find abi (TODO; can't find ABI file parsing, so read .sol & compile again) #f = open(pwd + '/../contract/abi.json','r') #aabi = f.read(); f.close() f = open(pwd + '/../contract/Auction.sol','r') contract_source_code = f.read() f.close() compiled_sol = compile_source(contract_source_code,import_remappings=['=','-']) contract_interface = compiled_sol["<stdin>:Auction"] abi = contract_interface['abi'] #Connect Deployed contract global auction auction = w3.eth.contract( address = contractAddress, abi = abi, ) #Check print('Cheapest Price: {}'.format(auction.functions.queueTop_sell().call())) return auction.address
def compile_test_ident(self): source_code = ''' pragma solidity ^0.4.24; contract TestIdentity{ address target; constructor() public{ target = address(msg.sender); } function set_target(address _target) public { target = _target; } function() public payable { require(target.call.value(msg.value)(msg.data)); } }''' compiled_sol = compile_source(source_code) contract_interface = compiled_sol['<stdin>:TestIdentity'] abi = contract_interface["abi"] bytecode = contract_interface["bin"] return abi,bytecode
def deploy(contract_source_code, w3): # 编译合约源码 compiledSol = compile_source(contract_source_code) contractInterface = compiledSol['<stdin>:Exchange'] # 生成合约对象 Contract = w3.eth.contract(abi=contractInterface['abi'], bytecode=contractInterface['bin']) # with open('./test.json', 'w') as wf: # wf.write(contractInterface['bin']) # print(contractInterface['bin']) # print(Contract.constructor().estimateGas(params)) # 部署合约 txhash = Contract.constructor().transact(params) # 等待合约部署交易完成 txreceipt = w3.eth.waitForTransactionReceipt(txhash) print(txreceipt) if txreceipt['status'] != 1: return None # 将合约地址和abi进行json化保存到本地文件 contractInfo = { 'address': txreceipt.contractAddress, 'abi': contractInterface['abi'] } with open('./cinfo.json', 'w') as wf: wf.write(json.dumps(contractInfo)) return contractInfo
def deploy_contract(self, file_sol, priv_key): with open(self.DIR_CONTRACTS + file_sol, "r") as f: source = f.read() compiled_sol = compile_source(source) contract_id, contract_interface = compiled_sol.popitem() abi = contract_interface['abi'] bytecode = contract_interface['bin'] contract = self.w3.eth.contract(abi=abi, bytecode=bytecode) acct = self.w3.eth.account.privateKeyToAccount(priv_key) self.logger.info("\tDeploying...") tx_hash = contract.constructor().buildTransaction({ 'from': acct.address, 'nonce': self.w3.eth.getTransactionCount(acct.address), 'gas': 1728712, 'gasPrice': self.w3.eth.gasPrice }) signed = acct.signTransaction(tx_hash) trans = self.w3.eth.sendRawTransaction(signed.rawTransaction) address = self.get_transaction_info(trans.hex())["contractAddress"] with open(FOLDERS["abi"] + file_sol.replace("sol", "abi"), "w") as f: abi_json = json.dumps(abi, indent=4) f.write(abi_json) self.logger.info( "\tSuccessfully deployed {0} to: {1} and saved ABI".format( file_sol, address))
def compile_solidity(name, source): contract_source_code = source compiled_sol = compile_source(contract_source_code) # SuperSimpleSale contract_interface = compiled_sol['<stdin>:{}'.format(name)] abi = contract_interface['abi'] bytecode = contract_interface['bin'] return abi, bytecode
def test_source_code_compilation(FOO_SOURCE, is_new_key_format): output = compile_source(FOO_SOURCE, optimize=True) assert output if is_new_key_format: contact_key = '<stdin>:Foo' else: contact_key = 'Foo' assert contact_key in output foo_contract_data = output[contact_key] assert 'bin' in foo_contract_data assert 'bin-runtime' in foo_contract_data
function Greeter() { greeting = 'Hello'; } function setGreeting(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } } ''' compiled_sol = compile_source(contract_source_code) # Compiled source code contract_interface = compiled_sol['<stdin>:Greeter'] # web3.py instance w3 = Web3(TestRPCProvider()) # Instantiate and deploy contract contract = w3.eth.contract(contract_interface['abi'], bytecode=contract_interface['bin']) # Get transaction hash from deployed contract tx_hash = contract.deploy(transaction={'from': w3.eth.accounts[0], 'gas': 410000}) # Get tx receipt to get contract address tx_receipt = w3.eth.getTransactionReceipt(tx_hash) contract_address = tx_receipt['contractAddress']