Exemplo n.º 1
0
def test_bool_fail(bad_code):

    if isinstance(bad_code, tuple):
        with raises(bad_code[1]):
            compiler.compile(bad_code[0])
    else:
        with raises(TypeMismatchException):
            compiler.compile(bad_code)
Exemplo n.º 2
0
def test_raw_call_fail(bad_code):

    if isinstance(bad_code, tuple):
        with raises(bad_code[1]):
            compiler.compile(bad_code[0])
    else:
        with raises(StructureException):
            compiler.compile(bad_code)
Exemplo n.º 3
0
def test_undef_toplevel():
    code = """
@public
def foo():
    x = bar(55)
    """
    with raises(StructureException) as ex:
        compiler.compile(code)
    assert "Not a top-level function: bar" in str(ex.value)
Exemplo n.º 4
0
def test_bytecode_runtime():
    code = """
@public
def a() -> bool:
    return true
    """

    bytecode = compiler.compile(code)
    bytecode_runtime = compiler.compile(code, bytecode_runtime=True)

    assert len(bytecode) > len(bytecode_runtime)
    assert bytecode_runtime in bytecode
Exemplo n.º 5
0
def test_undef_suggestion():
    code = """
@public
def bar(x: int128) -> int128:
    return 3 * x

@public
def foo() -> int128:
    return bar(20)
    """
    with raises(StructureException) as ex:
        compiler.compile(code)
    assert "Not a top-level function: bar" in str(ex.value)
    assert "Did you mean self.bar?" in str(ex.value)
Exemplo n.º 6
0
def tester(w3,
           base_tester,
           casper_args,
           casper_code,
           casper_abi,
           casper_address,
           deploy_rlp_decoder,
           deploy_msg_hasher,
           deploy_purity_checker,
           base_sender,
           initialize_contract=True):
    deploy_rlp_decoder()
    deploy_msg_hasher()
    deploy_purity_checker()

    # NOTE: bytecode cannot be compiled before RLP Decoder is deployed to chain
    # otherwise, vyper compiler cannot properly embed RLP decoder address
    casper_bytecode = compiler.compile(casper_code)

    Casper = w3.eth.contract(abi=casper_abi, bytecode=casper_bytecode)
    tx_hash = Casper.constructor().transact({'from': base_sender})
    tx_receipt = w3.eth.getTransactionReceipt(tx_hash)

    assert tx_receipt.contractAddress == casper_address

    # Casper contract needs money for its activity
    w3.eth.sendTransaction({'to': casper_address, 'value': 10**21})

    if initialize_contract:
        casper_contract = casper(w3, base_tester, casper_abi, casper_address)
        casper_contract.functions.init(*casper_args).transact()

    return base_tester
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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"]
Exemplo n.º 11
0
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": {},
            }
        },
    }
Exemplo n.º 12
0
def casper_chain(test_chain,
                 casper_args,
                 casper_code,
                 casper_abi,
                 casper_ct,
                 casper_address,
                 dependency_transactions,
                 msg_hasher_address,
                 purity_checker_address,
                 base_sender_privkey,
                 initialize_contract=True):
    init_transactions = []
    nonce = 0
    # Create transactions for instantiating RLP decoder, msg hasher and purity checker,
    # plus transactions for feeding the one-time accounts that generate those transactions
    for tx in dependency_transactions:
        fund_gas_tx = Transaction(nonce, GAS_PRICE, 500000, tx.sender,
                                  tx.startgas * tx.gasprice + tx.value,
                                  '').sign(base_sender_privkey)
        init_transactions.append(fund_gas_tx)
        init_transactions.append(tx)
        nonce += 1

    for tx in init_transactions:
        if test_chain.head_state.gas_used + tx.startgas > test_chain.head_state.gas_limit:
            test_chain.mine(1)
        test_chain.direct_tx(tx)

    test_chain.mine(1)

    # NOTE: bytecode cannot be compiled before RLP Decoder is deployed to chain
    # otherwise, vyper compiler cannot properly embed RLP decoder address
    casper_bytecode = compiler.compile(casper_code)

    deploy_code = casper_bytecode
    casper_tx = Transaction(nonce, GAS_PRICE, 7000000, b'', 0,
                            deploy_code).sign(base_sender_privkey)
    test_chain.direct_tx(casper_tx)
    nonce += 1

    test_chain.mine(1)

    # Casper contract needs money for its activity
    casper_fund_tx = Transaction(nonce, GAS_PRICE, 5000000, casper_tx.creates,
                                 10**21, b'').sign(base_sender_privkey)
    test_chain.direct_tx(casper_fund_tx)

    test_chain.mine(1)

    if initialize_contract:
        casper_contract = casper(test_chain, casper_abi, casper_address)
        casper_contract.init(*casper_args)

    return test_chain
Exemplo n.º 13
0
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
Exemplo n.º 14
0
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)
Exemplo n.º 15
0
    def next_contract_address(sender):
        snapshot_id = base_tester.take_snapshot()
        bytecode = compiler.compile(fake_contract_code)
        hex_bytecode = Web3.toHex(bytecode)
        tx_hash = w3.eth.sendTransaction({
            'from': sender,
            'to': '',
            'gas': 7000000,
            'data': hex_bytecode
        })
        contract_address = w3.eth.getTransactionReceipt(
            tx_hash).contractAddress

        base_tester.revert_to_snapshot(snapshot_id)
        return contract_address
Exemplo n.º 16
0
def tester(w3,
           base_tester,
           casper_args,
           casper_code,
           casper_abi,
           casper_address,
           deploy_rlp_decoder,
           deploy_msg_hasher,
           deploy_purity_checker,
           base_sender,
           initialize_contract=True):
    deploy_rlp_decoder()
    deploy_msg_hasher()
    deploy_purity_checker()

    # NOTE: bytecode cannot be compiled before RLP Decoder is deployed to chain
    # otherwise, vyper compiler cannot properly embed RLP decoder address
    casper_bytecode = compiler.compile(casper_code, bytecode_runtime=True)

    chain = base_tester.backend.chain
    vm = chain.get_vm()

    vm.state.account_db.set_code(Web3.toBytes(hexstr=casper_address),
                                 casper_bytecode)
    vm.state.account_db.persist()
    new_state_root = vm.state.account_db.state_root

    new_header = chain.header.copy(state_root=new_state_root)
    chain.header = new_header

    # mine block to ensure we don't have mismatched state
    base_tester.mine_block()

    # Casper contract needs money for its activity
    w3.eth.sendTransaction({'to': casper_address, 'value': 10**21})

    if initialize_contract:
        casper_contract = casper(w3, base_tester, casper_abi, casper_address)
        casper_contract.functions.init(*casper_args).transact()

    return base_tester
Exemplo n.º 17
0
def test_invalid_type_exception(bad_code):
    with raises(InvalidTypeException):
        compiler.compile(bad_code)
Exemplo n.º 18
0
def test_exponent_success(good_code):
    assert compiler.compile(good_code) is not None
Exemplo n.º 19
0
def test_exponent_fail(bad_code):

    with raises(TypeMismatchException):
        compiler.compile(bad_code)
Exemplo n.º 20
0
def test_block_success(good_code):
    assert compiler.compile(good_code) is not None
Exemplo n.º 21
0
def test_raw_call_success(good_code):
    assert compiler.compile(good_code) is not None
Exemplo n.º 22
0
def test_invalid_literal_exception(bad_code):
    with raises(InvalidLiteralException):
        compiler.compile(bad_code)
Exemplo n.º 23
0
def test_block_fail(bad_code):
        with raises(TypeMismatchException):
            compiler.compile(bad_code)
Exemplo n.º 24
0
def exchange_bytecode():
    return '0x' + compiler.compile(EXCHANGE_CODE).hex()
Exemplo n.º 25
0
def test_tuple_return_fail(bad_code):

    with raises(StructureException):
        compiler.compile(bad_code)
Exemplo n.º 26
0
def test_constancy_violation_exception(bad_code):
    with raises(ConstancyViolationException):
        compiler.compile(bad_code)
Exemplo n.º 27
0
def test_public_success(good_code):
    assert compiler.compile(good_code) is not None
Exemplo n.º 28
0
def test_variable_decleration_exception(bad_code):
    with raises(VariableDeclarationException):
        compiler.compile(bad_code)
Exemplo n.º 29
0
def test_rlplist_success(good_code):
    assert compiler.compile(good_code) is not None
Exemplo n.º 30
0
def test_invalid_type_exception(bad_code):
    with raises(VariableDeclarationException):
        compiler.compile(bad_code)