def test_compile_source_output_dir(tmp_path, foo_source): solcx.compile_source(foo_source, output_dir=tmp_path) output_path = tmp_path.joinpath("combined.json") with output_path.open() as fp: output = json.load(fp)["contracts"] assert "<stdin>:Foo" in output
def deploy_wrapper(self): compiled_interface = compile_source(ERC20_INTERFACE_SOURCE) interface_id, interface = compiled_interface.popitem() self.interface = interface compiled_wrapper = compile_source(ERC20_CONTRACT_SOURCE) wrapper_id, wrapper_interface = compiled_wrapper.popitem() self.wrapper = wrapper_interface erc20 = self.proxy.eth.contract(abi=self.wrapper['abi'], bytecode=wrapper_interface['bin']) nonce = self.proxy.eth.get_transaction_count( self.proxy.eth.default_account) tx = {'nonce': nonce} tx_constructor = erc20.constructor( self.name, self.symbol, bytes(self.token.pubkey)).buildTransaction(tx) tx_deploy = self.proxy.eth.account.sign_transaction( tx_constructor, self.admin.key) tx_deploy_hash = self.proxy.eth.send_raw_transaction( tx_deploy.rawTransaction) self.debug(f'tx_deploy_hash: {tx_deploy_hash.hex()}') tx_deploy_receipt = self.proxy.eth.wait_for_transaction_receipt( tx_deploy_hash) self.debug(f'tx_deploy_receipt: {tx_deploy_receipt}') self.debug(f'deploy status: {tx_deploy_receipt.status}') self.neon_contract_address = tx_deploy_receipt.contractAddress self.solana_contract_address = self.get_neon_account_address( self.neon_contract_address)
def test_get_combined_json_outputs_defaults(mocker, foo_source): # verify we get the correct combined json outputs for different # compiler versions spy = mocker.spy(solcx.main, "_get_combined_json_outputs") solcx.compile_source(foo_source, solc_version="0.4.12") assert "function-debug" not in spy.spy_return solcx.compile_source(foo_source, solc_version="0.8.9") assert "function-debug" in spy.spy_return
def test_compile_source_with_optimization(foo_source): output = solcx.compile_source(foo_source, optimize=True, optimize_runs=10000) assert "<stdin>:Foo" in output for value in combined_json_values: assert value in output["<stdin>:Foo"]
def deploy_contract(self): compiled_sol = compile_source(TEST_RETRY_BLOCKED_365) contract_id, contract_interface = compiled_sol.popitem() storage = proxy.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) trx_deploy = proxy.eth.account.sign_transaction(dict( nonce=proxy.eth.get_transaction_count(proxy.eth.default_account), chainId=proxy.eth.chain_id, gas=987654321, gasPrice=1000000002, to='', value=0, data=storage.bytecode), eth_account.key ) trx_deploy_hash = proxy.eth.send_raw_transaction(trx_deploy.rawTransaction) print('trx_deploy_hash:', trx_deploy_hash.hex()) trx_deploy_receipt = proxy.eth.wait_for_transaction_receipt(trx_deploy_hash) print('trx_deploy_receipt:', trx_deploy_receipt) self.contractAddress = trx_deploy_receipt.contractAddress self.abi = storage.abi self.storage_contract = proxy.eth.contract( address=trx_deploy_receipt.contractAddress, abi=storage.abi )
def deploy_storage_147_solidity_contract(self): compiled_sol = compile_source(STORAGE_SOLIDITY_SOURCE_147) contract_id, contract_interface = compiled_sol.popitem() storage = proxy.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) trx_deploy = proxy.eth.account.sign_transaction(dict( nonce=proxy.eth.get_transaction_count(proxy.eth.default_account), chainId=proxy.eth.chain_id, gas=987654321, gasPrice=2000000000, to='', value=0, data=storage.bytecode), eth_account.key ) print('trx_deploy:', trx_deploy) trx_deploy_hash = proxy.eth.send_raw_transaction(trx_deploy.rawTransaction) print('trx_deploy_hash:', trx_deploy_hash.hex()) trx_deploy_receipt = proxy.eth.wait_for_transaction_receipt(trx_deploy_hash) print('trx_deploy_receipt:', trx_deploy_receipt) self.deploy_block_hash = trx_deploy_receipt['blockHash'] self.deploy_block_num = trx_deploy_receipt['blockNumber'] print('deploy_block_hash:', self.deploy_block_hash) print('deploy_block_num:', self.deploy_block_num) self.storage_contract = proxy.eth.contract( address=trx_deploy_receipt.contractAddress, abi=storage.abi )
def test_deploy_cost(self): print("\n\ntest_deploy_cost") compiled = compile_source(CONTRACT) id, interface = compiled.popitem() contract = proxy.eth.contract(abi=interface['abi'], bytecode=interface['bin']) trx = proxy.eth.account.sign_transaction( dict(nonce=proxy.eth.get_transaction_count(self.account.address), chainId=proxy.eth.chain_id, gas=987654321, gasPrice=1000000000, to='', value=0, data=contract.bytecode), self.account.key) print("trx_hash", trx.hash.hex()[2:]) balance_pre = int( self.client.get_balance(self.acc.public_key(), commitment=Confirmed)['result']['value']) print("incoming balance {:,}".format(balance_pre).replace(',', ' ')) signature = proxy.eth.send_raw_transaction(trx.rawTransaction) receipt = proxy.eth.wait_for_transaction_receipt(signature) # self.contract = proxy.eth.contract( # address=receipt.contractAddress, # abi=contract.abi # ) balance_post = int( self.client.get_balance(self.acc.public_key(), commitment=Confirmed)['result']['value']) print("outgoing balance {:,}".format(balance_post).replace(',', ' ')) print("cost {:,}".format(balance_pre - balance_post).replace(',', ' '))
def setUpClass(self): print( "\n\nhttps://app.zenhub.com/workspaces/solana-evm-6007c75a9dc141001100ccb8/issues/neonlabsorg/proxy-model.py/233" ) self.account = proxy.eth.account.create() print('account.address:', self.account.address) request_airdrop(self.account.address) compiled = compile_source(INCREAZE_STORAGE_CONTRACT) id, interface = compiled.popitem() contract = proxy.eth.contract(abi=interface['abi'], bytecode=interface['bin']) trx = proxy.eth.account.sign_transaction( dict(nonce=proxy.eth.get_transaction_count(self.account.address), chainId=proxy.eth.chain_id, gas=987654321, gasPrice=1000000000, to='', value=0, data=contract.bytecode), self.account.key) signature = proxy.eth.send_raw_transaction(trx.rawTransaction) receipt = proxy.eth.wait_for_transaction_receipt(signature) self.contract = proxy.eth.contract(address=receipt.contractAddress, abi=contract.abi, bytecode=interface['bin'])
def get_abi(contract_source: str) -> Dict: """Given a contract source, returns a dict of {name: abi}""" version = find_best_solc_version({"<stdin>": contract_source}) set_solc_version(version) compiled = solcx.compile_source(contract_source, allow_empty=True, output_values=["abi"]) return {k.rsplit(":")[-1]: v["abi"] for k, v in compiled.items()}
def compile_contract(self, solidity_source_code: str) -> ContractCompiledInfo: """Returns tuple of """ compile_result = solcx.compile_source(solidity_source_code) _, contract_interface = compile_result.popitem() contract = self._web3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) return ContractCompiledInfo(contract_interface, contract)
def compiled_contract(): contract_path = os.path.join(os.getcwd(), '..', 'Contract', 'KYCWallet_Contract_UPDATED.sol') with open(contract_path, 'r') as f: source = f.read() return compile_source(source)
def solCompileFile(file_path): from solcx import compile_source try: with open(file_path, 'r') as f: source = f.read() return compile_source(source) except Exception as err: log.debug(str(err))
def compile_contract(self): data = open(self.contract_file, "r").read() contract = compile_source(data) for key in contract.keys(): self.contract = contract[key] self.abi = self.contract['abi'] self.bin = self.contract['bin']
def compile_source_file(self, file_path): """ Compile solidity contract file and returns contract instance object """ if not exists(file_path): raise FileNotFoundError("File not found at path: {0}".format( realpath(file_path))) with open(file_path, 'r') as f: source = f.read() return compile_source(source)
def get_abi(contract_source: str, allow_paths: Optional[str] = None) -> Dict: """ Given a contract source, returns a dict of {name: abi} This function is deprecated in favor of `brownie.project.compiler.get_abi` """ version = find_best_solc_version({"<stdin>": contract_source}) set_solc_version(version) compiled = solcx.compile_source( contract_source, allow_empty=True, allow_paths=allow_paths, output_values=["abi"] ) return {k.rsplit(":")[-1]: v["abi"] for k, v in compiled.items()}
def compileContract(contract_source_file): """ Reads file, compiles, returns contract name and interface """ with open(contract_source_file, "r") as f: contract_source_code = f.read() compiled_sol = compile_source(contract_source_code) # Compiled source code assert (len(compiled_sol) == 1 ) # assert source file has only one contract object contractName = list(compiled_sol.keys())[0] contract_interface = compiled_sol[contractName] return contractName.replace("<stdin>:", ""), contract_interface
def test_abi2solc(abi_path, version): if version == "0.4.17" and abi_path.parent.stem == "tuples": return abi = json.load(abi_path.open()) solcx.set_solc_version(version) interface = abi2solc.generate_interface(abi, "Test", version.startswith("0.4")) generated_abi = solcx.compile_source(interface)["<stdin>:Test"]["abi"] if next((i for i in abi if i["type"] == "constructor"), False): assert len(abi) == len(generated_abi) + 1 else: assert len(abi) == len(generated_abi) for item in generated_abi: assert item in abi
def compile_contract(self, contract_source_file, contractName=None): """ Reads file, compiles, returns contract name and interface """ with open(contract_source_file, "r") as f: contract_source_code = f.read() compiled_sol = compile_source(contract_source_code) if not contractName: contractName = list(compiled_sol.keys())[0] contract_interface = compiled_sol[contractName] else: contract_interface = compiled_sol['<stdin>:' + contractName] return contractName, contract_interface
def test_compile_source_import_remapping(foo_path, bar_path, baz_source): import_remappings = { "contracts": foo_path.parent, "other": bar_path.parent } output = solcx.compile_source(baz_source, import_remappings=import_remappings) assert set(output) == { f"{foo_path.as_posix()}:Foo", f"{bar_path.as_posix()}:Bar", "<stdin>:Baz", }
def __init__(self, contract_name, contracts_folder=contracts_directory, provider=infura_provider): Connector.__init__(self, provider) self.contract_file = f"{contracts_folder + contract_name}.sol" with open(self.contract_file, 'r') as contract_code: self.source_code = contract_code.read() self.compiled = compile_source(self.source_code) self.abi = self.compiled[f'<stdin>:{contract_name}']['abi'] self.bin = self.compiled[f'<stdin>:{contract_name}']['bin']
def deploy_contract_v3(private_key): from solcx import compile_source from web3 import Web3 # Read in LUCE contract code with open(SOLIDITY_CONTRACT_FILE, 'r') as file: # Adjust file_path for use in Jupyter/Django contract_source_code = file.read() # Compile & Store Compiled source code compiled_sol = compile_source(contract_source_code) # Extract full interface as dict from compiled contract contract_interface = compiled_sol['<stdin>:Dataset'] # Extract abi and bytecode abi = contract_interface['abi'] bytecode = contract_interface['bin'] # Establish web3 connection w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:8545")) #Obtain user so we know his address for the 'from' field user = w3.eth.account.privateKeyToAccount(private_key) # Construct raw transaction nonce = w3.eth.getTransactionCount(user.address) transaction = { 'from': user.address, 'gas': 2000000, 'data': bytecode, 'chainId': 3, 'gasPrice': w3.toWei('40', 'gwei'), 'nonce': nonce, } # Sign transaction signed_txn = w3.eth.account.signTransaction(transaction, private_key) # Deploy tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) # Wait for the transaction to be mined, and get the transaction receipt tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) # Obtain address of freshly deployed contract contractAddress = tx_receipt.contractAddress return contractAddress
def deploy_contract_with_data(user, description, license, link=""): from solcx import compile_source from web3 import Web3 # Read in LUCE contract code with open(SOLIDITY_CONTRACT_FILE, 'r') as file: contract_source_code = file.read() # Compile & Store Compiled source code compiled_sol = compile_source(contract_source_code) # Extract full interface as dict from compiled contract contract_interface = compiled_sol['<stdin>:Dataset'] # Extract abi and bytecode abi = contract_interface['abi'] bytecode = contract_interface['bin'] # Establish web3 connection w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:8545")) # Obtin user current_user = user # Set sender w3.eth.defaultAccount = current_user.ethereum_public_key # Create contract blueprint Luce = w3.eth.contract(abi=abi, bytecode=bytecode) # Submit the transaction that deploys the contract tx_hash = Luce.constructor().transact() # Wait for the transaction to be mined, and get the transaction receipt tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) # Obtain address of freshly deployed contract contract_address = tx_receipt.contractAddress # Create python instance of deployed contract luce = w3.eth.contract( address=contract_address, abi=contract_interface['abi'], ) # Store dataset information in contract tx_hash = luce.functions.publishData(description, link, license).transact() return contract_address
def compile_source_file(file_path): """Read and compile the source file with the solc Solidity compiler. If the compiler is not available, it will be installed. """ # Check if solc compiler is available otherwise install try: print(solcx.get_solc_version()) except solcx.exceptions.SolcNotInstalled as e: print(e) version = solcx.install_solc('0.7.4') print(f'Installed version: {version}') with open(file_path, 'r') as f: source = f.read() return solcx.compile_source(source)
def deploy_contract(self, contract_path): compiled_contract = None with open(contract_path, u'r') as f: source = f.read() compiled_contract = compile_source(source) contract_id, contract_interface = compiled_contract.popitem() tx_hash = self.web3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']).constructor().transact() time.sleep(10) address = self.web3.eth.getTransactionReceipt(tx_hash)['contractAddress'] return self.web3.eth.contract(address=address, abi=contract_interface["abi"])
def deploy_contract(self): compiled_sol = compile_source(STORAGE_SOLIDITY_SOURCE) contract_id, contract_interface = compiled_sol.popitem() storage = proxy.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) trx_deploy = proxy.eth.account.sign_transaction(dict( nonce=proxy.eth.get_transaction_count(eth_account.address), chainId=proxy.eth.chain_id, gas=987654321, gasPrice=1000000000, to='', value=0, data=storage.bytecode), eth_account.key ) trx_deploy_hash = proxy.eth.send_raw_transaction(trx_deploy.rawTransaction) return proxy.eth.wait_for_transaction_receipt(trx_deploy_hash)
def deploy_contract(self): compiled = compile_source(CONTRACT_SOURCE) id, interface = compiled.popitem() self.contract = interface contract = proxy.eth.contract(abi=self.contract['abi'], bytecode=self.contract['bin']) nonce = proxy.eth.get_transaction_count(proxy.eth.default_account) tx = {'nonce': nonce} tx_constructor = contract.constructor().buildTransaction(tx) tx_deploy = proxy.eth.account.sign_transaction(tx_constructor, admin.key) tx_deploy_hash = proxy.eth.send_raw_transaction( tx_deploy.rawTransaction) tx_deploy_receipt = proxy.eth.wait_for_transaction_receipt( tx_deploy_hash) self.contract_address = tx_deploy_receipt.contractAddress print('contract address:', self.contract_address)
def deploy_test_contract(self): compiled = compile_source(CONTRACT) id, interface = compiled.popitem() contract = proxy.eth.contract(abi=interface['abi'], bytecode=interface['bin']) trx = proxy.eth.account.sign_transaction( dict(nonce=proxy.eth.get_transaction_count(admin.address), chainId=proxy.eth.chain_id, gas=987654321, gasPrice=1000000000, to='', value=0, data=contract.bytecode), admin.key) signature = proxy.eth.send_raw_transaction(trx.rawTransaction) receipt = proxy.eth.wait_for_transaction_receipt(signature) self.contract = proxy.eth.contract(address=receipt.contractAddress, abi=contract.abi)
def _compile_contract(self): install_solc('v0.6.2') set_solc_version('v0.6.2') ''' Compiles smart contract, creates bytecode and abi ''' # loading contract file data with open(tools.get_contr_path(), "r") as source_file: source_raw = source_file.read() # loading configuration data with open(tools.get_compile_data_path()) as opt_file: raw_opt = opt_file.read() opt = json.loads(raw_opt) #opt["sources"]["ResearchCertificate.sol"]["content"] = source_raw compiled_sol = compile_source(source_raw) contract_interface = compiled_sol['<stdin>:' + 'ResearchCertificate'] self.bytecode = contract_interface['bin'] self.abi = contract_interface['abi'] logging.info("Succesfully compiled contract")
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 test_compile_source_overwrite(tmp_path, foo_source): output_path = tmp_path.joinpath("combined.json") with output_path.open("w") as fp: fp.write("foobar") with pytest.raises(FileExistsError): solcx.compile_source(foo_source, output_dir=tmp_path) with pytest.raises(FileExistsError): solcx.compile_source(foo_source, output_dir=tmp_path.joinpath("combined.json")) solcx.compile_source(foo_source, output_dir=tmp_path, overwrite=True) with output_path.open() as fp: output = json.load(fp)["contracts"] assert "<stdin>:Foo" in output