def compile(endpoint): if endpoint not in ['compile', 'compile-k']: abort(500) source = request.form.get('source', '') try: if endpoint == 'compile': abi = compiler.mk_full_signature(source) abi_code = 200 else: raise Exception('Not available') except Exception as e: abi = str(e) abi_code = 500 try: if endpoint == 'compile': json_abi = json.dumps(compiler.mk_full_signature(source)) json_abi_code = 200 else: raise Exception('Not available') except Exception as e: json_abi = str(e) json_abi_code = 500 try: if endpoint == 'compile': bytecode = '0x' + compiler.compile(source).hex() bytecode_code = 200 else: raise Exception('Not available') except Exception as e: bytecode = str(e) bytecode_code = 500 try: if endpoint == 'compile': ir = optimizer.optimize(parse_to_lll(source)) ir = str(ir) ir_code = 200 else: raise Exception('Not available') #ast = parse(source) #print("lala") #print(ast) #ir = viper2lll(ast) #ir_code = 200 except Exception as e: ir = str(e) ir_code = 500 r_dict = { 'result': { 'abi': abi, 'abi_code': abi_code, 'json': json_abi, 'json_code': json_abi_code, 'bytecode': bytecode, 'bytecode_code': bytecode_code, 'lll': ir, 'lll_code': ir_code } } return make_response(jsonify(r_dict), 200)
def transpile(clss, target="deploy"): if target not in ["deploy", "abi", "bytecode", "lll", "vyper", "vy"]: raise ValueError("Unrecognized target for transpilation") if type(clss) is Lll: #todo: need to rework this if target == "bytecode": asm = compile_to_assembly(clss.node) return '0x' + assembly_to_evm(asm).hex() raise ValueError("lll can only be compiled to bytecode for now") vyp = python_to_vyper(clss) if target == "vyper" or target == "vy": return vyp if target == "bytecode": return Bytecode('0x' + compiler.compile(str(vyp)).hex()) if target == "abi": return Abi(compiler.mk_full_signature(str(vyp))) if target == "deploy": abi = Abi(compiler.mk_full_signature(str(vyp))) bytecode = Bytecode('0x' + compiler.compile(str(vyp)).hex()) return Deploy(abi, bytecode) return Lll(optimizer.optimize(parse_to_lll(str(vyp))))
def test_only_init_function(): code = """ x: num @public def __init__(): self.x = 1 """ code_init_empty = """ x: num @public def __init__(): pass """ empty_sig = [{ 'name': '__init__', 'outputs': [], 'inputs': [], 'constant': False, 'payable': False, 'type': 'constructor' }] assert mk_full_signature(code) == empty_sig assert mk_full_signature(code_init_empty) == empty_sig
def get_compiled_contracts(self, source_file_paths, import_remappings): try: from vyper import compiler except ImportError: raise ImportError( 'vyper needs to be installed to use VyperBackend' + ' as compiler backend.') self.logger.debug("Compiler Settings: %s", pprint.pformat(self.compiler_settings)) compiled_contracts = [] for contract_path in source_file_paths: code = open(contract_path).read() abi = compiler.mk_full_signature(code) bytecode = '0x' + compiler.compile(code).hex() bytecode_runtime = '0x' + compiler.compile( code, bytecode_runtime=True).hex() compiled_contracts.append({ 'name': os.path.basename(contract_path).split('.')[0], 'abi': abi, 'bytecode': bytecode, 'bytecode_runtime': bytecode_runtime, 'linkrefs': [], 'linkrefs_runtime': [], 'source_path': contract_path }) return compiled_contracts
def test_struct_abi(): code = """ struct MyStruct: a: address b: uint256 @public @constant def foo(s: MyStruct) -> MyStruct: return s """ abi = mk_full_signature(code) func_abi = abi[0] assert func_abi["name"] == "foo" expected = { 'type': 'tuple', 'name': '', 'components': [{ 'type': 'address', 'name': 'a' }, { 'type': 'uint256', 'name': 'b' }] } assert func_abi["outputs"][0] == expected expected['name'] = "s" assert func_abi["inputs"][0] == expected
def modified_registration_contract( request, w3, tester, chain_start_full_deposit_thresholds): # Set CHAIN_START_FULL_DEPOSIT_THRESHOLD to different threshold t registration_code = get_deposit_contract_code() t = str(chain_start_full_deposit_thresholds[request.param]) modified_registration_code = re.sub( r'CHAIN_START_FULL_DEPOSIT_THRESHOLD: constant\(uint256\) = [0-9]+', 'CHAIN_START_FULL_DEPOSIT_THRESHOLD: constant(uint256) = ' + t, registration_code, ) assert modified_registration_code != registration_code contract_bytecode = compiler.compile_code(modified_registration_code)['bytecode'] contract_abi = compiler.mk_full_signature(modified_registration_code) registration = w3.eth.contract( abi=contract_abi, bytecode=contract_bytecode) tx_hash = registration.constructor().transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) registration_deployed = w3.eth.contract( address=tx_receipt.contractAddress, abi=contract_abi ) setattr( registration_deployed, 'chain_start_full_deposit_threshold', chain_start_full_deposit_thresholds[request.param] ) return registration_deployed
def _get_contract(w3, source_code, *args, **kwargs): abi = compiler.mk_full_signature(source_code) bytecode = '0x' + compiler.compile(source_code).hex() contract = w3.eth.contract(abi=abi, bytecode=bytecode) value = kwargs.pop('value', 0) value_in_eth = kwargs.pop('value_in_eth', 0) value = value_in_eth * 10**18 if value_in_eth else value # Handle deploying with an eth value. gasPrice = kwargs.pop('gasPrice', 0) deploy_transaction = { 'from': w3.eth.accounts[0], 'data': contract._encode_constructor_data(args, kwargs), 'value': value, 'gasPrice': gasPrice, } tx = w3.eth.sendTransaction(deploy_transaction) address = w3.eth.getTransactionReceipt(tx)['contractAddress'] contract = w3.eth.contract(address, abi=abi, bytecode=bytecode, ContractFactoryClass=VyperContract) # Filter logs. contract._logfilter = w3.eth.filter({ 'fromBlock': w3.eth.blockNumber - 1, 'address': contract.address }) return contract
def create_contract(w3, path): wd = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(wd, os.pardir, path)) as f: source = f.read() bytecode = '0x' + compiler.__compile(source).hex() abi = compiler.mk_full_signature(source) return w3.eth.contract(abi=abi, bytecode=bytecode)
def test_compile_deposit_contract(): compiled_deposit_contract_json = get_deposit_contract_json() deposit_contract_code = get_deposit_contract_code() abi = compiler.mk_full_signature(deposit_contract_code) bytecode = compiler.compile_code(deposit_contract_code)['bytecode'] assert abi == compiled_deposit_contract_json["abi"] assert bytecode == compiled_deposit_contract_json["bytecode"]
def registration_contract(w3, tester, registration_code): contract_bytecode = compiler.compile_code(registration_code)['bytecode'] contract_abi = compiler.mk_full_signature(registration_code) registration = w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode) tx_hash = registration.constructor().transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) registration_deployed = w3.eth.contract(address=tx_receipt.contractAddress, abi=contract_abi) return registration_deployed
def test_compile_smc(): compiled_smc_json = get_smc_json() vmc_code = get_smc_source_code() abi = compiler.mk_full_signature(vmc_code) bytecode = compiler.compile(vmc_code) bytecode_hex = '0x' + bytecode.hex() assert abi == compiled_smc_json["abi"] assert bytecode_hex == compiled_smc_json["bytecode"]
def create_raw_asset_data(source: str) -> Dict[str, Any]: return { "abi": compiler.mk_full_signature(source), "evm": { "bytecode": { "object": to_hex(compiler.compile(source)), "linkReferences": {}, } }, }
def test_default_abi(): default_code = """ @payable @public def __default__(): pass """ assert mk_full_signature(default_code) == [{ 'constant': False, 'payable': True, 'type': 'fallback' }]
def generate_compiled_json(file_path: str): deposit_contract_code = open(file_path).read() abi = compiler.mk_full_signature(deposit_contract_code) bytecode = compiler.compile_code(deposit_contract_code)['bytecode'] contract_json = { 'abi': abi, 'bytecode': bytecode, } # write json basename = os.path.basename(file_path) dirname = os.path.dirname(file_path) contract_name = basename.split('.')[0] with open(dirname + "/{}.json".format(contract_name), 'w') as f_write: json.dump(contract_json, f_write)
def deploy(w3): with open(contract_name, 'r') as f: contract_code = f.read() contract_bytecode = compiler.compile(contract_code).hex() contract_abi = compiler.mk_full_signature(contract_code) w3.eth.defaultAccount = w3.eth.accounts[0] Contract = w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode) tx_hash = Contract.constructor().transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) contract = w3.eth.contract(address=tx_receipt.contractAddress, abi=contract_abi) return contract
def generate_compiled_json(file_path: str) -> None: vmc_code = open(file_path).read() abi = compiler.mk_full_signature(vmc_code) bytecode = compiler.compile(vmc_code) bytecode_hex = '0x' + bytecode.hex() contract_json = { 'abi': abi, 'bytecode': bytecode_hex, } # write json basename = os.path.basename(file_path) dirname = os.path.dirname(file_path) contract_name = basename.split('.')[0] with open(dirname + "/{}.json".format(contract_name), 'w') as f_write: json.dump(contract_json, f_write)
def casper_abi(casper_code): return compiler.mk_full_signature(casper_code)
def erc20_flash_abi(): wd = os.path.dirname(os.path.realpath(__file__)) code = open(os.path.join(wd, os.pardir, 'contracts/uniflash_erc20.vy')).read() return compiler.mk_full_signature(code)
def exchange_abi(): return compiler.mk_full_signature(EXCHANGE_CODE)
def pool_abi(pool_code): return compiler.mk_full_signature(pool_code)
'type': 'address' }], 'outputs': [{ 'name': 'out', 'type': 'bool' }] }] # noqa: E501 viper_rlp_decoder_address = viper_rlp_decoder_tx.creates sig_hasher_address = sig_hasher_tx.creates _casper_contract_path = '/'.join( ('..', 'casper', 'casper', 'contracts', 'simple_casper.v.py')) casper_code = str( pkg_resources.resource_string('ethereum', _casper_contract_path), 'utf-8') casper_bytecode = compiler.compile(casper_code) casper_abi = compiler.mk_full_signature(casper_code) casper_ct = ContractTranslator(casper_abi) def mk_initializers(config, sender_privkey, starting_nonce=0): o = [] nonce = starting_nonce # Create transactions for instantiating RLP decoder, sig hasher and purity checker, plus transactions for feeding the # one-time accounts that generate those transactions for tx in (viper_rlp_decoder_tx, sig_hasher_tx, purity_checker_tx): o.append( Transaction(nonce, gasprice, 90000, tx.sender, tx.startgas * tx.gasprice + tx.value, '').sign(sender_privkey)) o.append(tx) nonce += 1
from vyper import compiler from eth_utils import function_abi_to_4byte_selector import binascii casper_abi = compiler.mk_full_signature( open("../casper/casper/contracts/simple_casper.v.py").read()) for item in casper_abi: b = ''.join( [f'\\x{l:02x}' for l in list(function_abi_to_4byte_selector(item))]) print(item["name"], '\t', b)
print('Address of owner: ',default_account) # every time we write to the chain it's considered a "transaction". every time a transaction # is made we need to send with it at a minimum the info of the account that is paying for the gas transaction_details = { 'from': default_account, } #Deploy tokens token_to_deploy = open('./vypercoin.vy','r') token_read = token_to_deploy.read() token_d = {'token_name':'DARF', 'token_symbol':'DRF', 'token_decimal':18, 'token_initialSupply':1000000} token_abi = compiler.mk_full_signature(token_read) token_bytecode = '0x' + compiler.compile(token_read).hex() token_factory = eth_provider.contract( abi=token_abi, bytecode=token_bytecode, ) token_constructor = token_factory.constructor(token_d['token_name'].encode('utf-8'),token_d['token_symbol'].encode('utf-8'),\ token_d['token_decimal'],token_d['token_initialSupply']) token_transaction_hash = token_constructor.transact(transaction_details) transaction_receipt_token = eth_provider.getTransactionReceipt(token_transaction_hash) token_address = transaction_receipt_token['contractAddress'] token_instance = eth_provider.contract( abi=token_abi, address=token_address, ) print(token_instance)
def exchange_abi(): wd = os.path.dirname(os.path.realpath(__file__)) code = open(os.path.join(wd, os.pardir, 'contracts/uniswap_exchange.vy')).read() return compiler.mk_full_signature(code)
def contract_factory(w3, source): bytecode = '0x' + compiler.compile(source).hex() abi = compiler.mk_full_signature(source) return w3.eth.contract(abi=abi, bytecode=bytecode)
from sputnik.engine import Sputnik from sputnik.parser import Parser from vyper import compiler if __name__ == '__main__': #2 # Setup Sputnik and deploy vyper contract SputnikParser = Parser('contracts/otp.sputnik') proggy = SputnikParser.get_program() sputnik = Sputnik(proggy, None) with open('contracts/hasheater.vy', 'r') as f: contract_code = f.read() contract_bytecode = compiler.compile(contract_code).hex() contract_abi = compiler.mk_full_signature(contract_code) w3.eth.defaultAccount = w3.eth.accounts[0] Contract = w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode) tx_hash = Contract.constructor().transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) contract = w3.eth.contract(address=tx_receipt.contractAddress, abi=contract_abi) #3 # Setup numpy (insecure, but it's a hackathon...) rng = numpy.random.RandomState() #4 # Setup NuFHE secret_key, bootstrap_key = nufhe.make_key_pair(sputnik.thr,