Example #1
0
def test_token_1(bank, registry, token_name):
    alice = accounts.add(
        'a8060afe2390bd0c00c7ef800f545d466b55cc84d4ad6d01e03220af03e97982')
    bob = accounts.add(
        '7b9009958a83807bbe38bf35f451ff0c4bf4d926cee63dd07658762db58ceba4')

    # bank.deposit({'from': bob, 'value': '0.1 ether', 'gas_price':1000000000})

    prevBNBBal = alice.balance()

    bank.work(
        0, registry[token_name]['goblin'], 10**17, 0,
        eth_abi.encode_abi(['address', 'bytes'], [
            registry[token_name]['two_side'].address,
            eth_abi.encode_abi(['address', 'uint256', 'uint256'],
                               [registry[token_name]['token'], 0, 0])
        ]), {
            'from': alice,
            'value': '0.05 ether',
            'gas_price': 1000000000
        })

    curBNBBal = alice.balance()

    print('∆ ht alice', curBNBBal - prevBNBBal)

    pos_id = bank.nextPositionID() - 1
    print('alice pos', bank.positionInfo(pos_id))
Example #2
0
def test_cake_2(bank, registry):
    alice = accounts[1]

    prevBNBBal = alice.balance()

    bank.work(
        0, registry['sashimi']['goblin'], 0, 0,
        eth_abi.encode_abi(['address', 'bytes'], [
            registry['sashimi']['two_side'].address,
            eth_abi.encode_abi(['address', 'uint256', 'uint256'],
                               [sashimi_address, 0, 0])
        ]), {
            'from': alice,
            'value': '1 ether'
        })

    curBNBBal = alice.balance()

    print('∆ ht alice', curBNBBal - prevBNBBal)
    print('alice pos', bank.positionInfo(1))

    assert almostEqual(curBNBBal - prevBNBBal,
                       -10**18), 'incorrect BNB input amount'

    # test reinvest
    chain.mine(10)

    goblin = interface.IAny(registry['sashimi']['goblin'])
    goblin.reinvest({'from': alice})
Example #3
0
def encode_dom_sep(inst):
    chain_id = brownie.network.chain.id
    preimg = encode_abi(['bytes32', 'uint256', 'uint256', 'address'], [
        bytes.fromhex(C.DOMAIN_SEPARATOR_TYPEHASH[2:]), chain_id,
        inst.tx.block_number, inst.address
    ])
    return web3.keccak(preimg).hex()
Example #4
0
 def encode_function_call(self, function_name, args):
     if function_name not in self.function_data:
         raise ValueError('Unkown function {}'.format(function_name))
     description = self.function_data[function_name]
     function_selector = zpad(encode_int(description['prefix']), 4)
     arguments = encode_abi(description['encode_types'], args)
     return function_selector + arguments
Example #5
0
    def _encode_abi(cls, abi, arguments, data=None):
        argument_types = get_abi_input_types(abi)

        if not check_if_arguments_can_be_encoded(abi, arguments, {}):
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type.  Expected types are: {0}".format(
                    ', '.join(argument_types),
                )
            )

        try:
            encoded_arguments = encode_abi(
                argument_types,
                force_obj_to_bytes(arguments),
            )
        except EncodingError as e:
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type: {0}".format(str(e))
            )

        if data:
            return add_0x_prefix(
                force_bytes(remove_0x_prefix(data)) +
                force_bytes(remove_0x_prefix(encode_hex(encoded_arguments)))
            )
        else:
            return encode_hex(encoded_arguments)
Example #6
0
def _encode_data(primaryType: str, data: any, types) -> str:
    encodedTypes = ['bytes32']
    encodedValues = [_type_hash(primaryType, types)]

    for field in types[primaryType]:
        value = data[field['name']]

        if field['type'] == 'string':
            hashValue = keccak(text=value)
            encodedTypes.append('bytes32')
            encodedValues.append(hashValue)

        elif field['type'] == 'bytes':
            hashValue = keccak(hexstr=value)
            encodedTypes.append('bytes32')
            encodedValues.append(hashValue)

        elif field['type'] in types:
            encodedTypes.append('bytes32')
            hashValue = keccak(
                _encode_data(field['type'], value, types).encode())
            encodedValues.append(hashValue)

        elif field['type'] == 'uint256':
            encodedTypes.append('uint256')
            encodedValues.append(int(value))

        else:
            encodedTypes.append(field['type'])
            normalizedValue = _normalize_value(field['type'], value)
            encodedValues.append(normalizedValue)

    return encode_abi(encodedTypes, encodedValues)
Example #7
0
def handle_offchain_lookup(
    offchain_lookup_payload: Dict[str, Any],
    transaction: TxParams,
) -> bytes:
    formatted_sender = to_hex_if_bytes(
        offchain_lookup_payload['sender']).lower()
    formatted_data = to_hex_if_bytes(
        offchain_lookup_payload['callData']).lower()

    if formatted_sender != to_hex_if_bytes(transaction['to']).lower():
        raise ValidationError(
            'Cannot handle OffchainLookup raised inside nested call. Returned `sender` value does '
            'not equal `to` address in transaction.')

    for url in offchain_lookup_payload['urls']:
        formatted_url = URI(
            str(url).replace('{sender}', str(formatted_sender)).replace(
                '{data}', str(formatted_data)))

        try:
            if '{data}' in url and '{sender}' in url:
                response = get_response_from_get_request(formatted_url)
            elif '{sender}' in url:
                response = get_response_from_post_request(formatted_url,
                                                          data={
                                                              "data":
                                                              formatted_data,
                                                              "sender":
                                                              formatted_sender,
                                                          })
            else:
                raise ValidationError('url not formatted properly.')
        except Exception:
            continue  # try next url if timeout or issues making the request

        if 400 <= response.status_code <= 499:  # if request returns 400 error, raise exception
            response.raise_for_status()
        if not 200 <= response.status_code <= 299:  # if not 400 error, try next url
            continue

        result = response.json()

        if 'data' not in result.keys():
            raise ValidationError(
                "Improperly formatted response for offchain lookup HTTP request - missing 'data' "
                "field.")

        encoded_data_with_function_selector = b''.join([
            # 4-byte callback function selector
            to_bytes_if_hex(offchain_lookup_payload['callbackFunction']),

            # encode the `data` from the result and the `extraData` as bytes
            encode_abi(['bytes', 'bytes'], [
                to_bytes_if_hex(result['data']),
                to_bytes_if_hex(offchain_lookup_payload['extraData']),
            ])
        ])

        return encoded_data_with_function_selector
    raise MultipleFailedRequests("Offchain lookup failed for supplied urls.")
Example #8
0
def play(contract_address, data):
    NONCE = web3.eth.getTransactionCount(RESOLVER_ADDRESS, "pending")
    gas_price = requests.get("https://ethgasstation.info/json/ethgasAPI.json").json()[
        "fast"
    ]
    last_data = bytes.fromhex(data[2:])
    func_sig = function_signature_to_4byte_selector("buy(uint64,bool,bytes)")
    signed = web3.eth.account.signTransaction(
        {
            "to": contract_address,
            "data": func_sig
            + encode_abi(
                ["uint64", "bool", "bytes"],
                [int(time.time()) + 345, random.randint(0, 1) == 0, last_data],
            ),
            "nonce": NONCE,
            "gasPrice": web3.toWei(str(gas_price / 10 + 5), "gwei"),
            "value": web3.toWei("0.104", "ether"),
            "gas": 350000,
        },
        RESOLVER_PK,
    )

    txhash = web3.eth.sendRawTransaction(signed.rawTransaction).hex()
    return txhash
def update_rewards(badger: BadgerSystem) -> str:
    data = encode_abi(["address"], [GOVERNANCE_MULTISIG_ADDRESS])
    delay = 2 * days(2)
    eta = web3.eth.getBlock("latest")["timestamp"] + delay

    return badger.governance_queue_transaction(CONTROLLER_ADDRESS,
                                               FUNCTION_TO_CALL, data, eta)
Example #10
0
    def _encode_abi(cls, abi, arguments, data=None):
        argument_types = get_abi_input_types(abi)

        if not check_if_arguments_can_be_encoded(abi, arguments, {}):
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type.  Expected types are: {0}".format(
                    ', '.join(argument_types), ))

        try:
            encoded_arguments = encode_abi(
                argument_types,
                force_obj_to_bytes(arguments),
            )
        except EncodingError as e:
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type: {0}".format(str(e)))

        if data:
            return add_0x_prefix(
                force_bytes(remove_0x_prefix(data)) +
                force_bytes(remove_0x_prefix(encode_hex(encoded_arguments))))
        else:
            return encode_hex(encoded_arguments)
Example #11
0
    def _encode_abi(cls, abi, arguments, data=None):
        argument_types = get_abi_input_types(abi)

        if not check_if_arguments_can_be_encoded(abi, arguments, {}):
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type.  Expected types are: {0}".format(
                    ', '.join(argument_types), ))

        try:
            normalizers = [
                abi_bytes_to_hex, abi_string_to_hex, hexstrs_to_bytes
            ]
            normalized_arguments = map_abi_data(
                normalizers,
                argument_types,
                arguments,
            )
            encoded_arguments = encode_abi(
                argument_types,
                normalized_arguments,
            )
        except EncodingError as e:
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type: {0}".format(str(e)))

        if data:
            return to_hex(HexBytes(data) + encoded_arguments)
        else:
            return encode_hex(encoded_arguments)
Example #12
0
def eth_abi_encode(func: dict, args: list) -> str:
    """
    >> func = {"constant":True,"inputs":[{"name":"","type":"address"}],
"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":False,"stateMutability":"view","type":"function"}
    >> eth_abi_encode(abi, ['9d3d4cc1986d81f9109f2b091b7732e7d9bcf63b'])
    >> '70a082310000000000000000000000009d3d4cc1986d81f9109f2b091b7732e7d9bcf63b'
    ## address must be lower case
    """
    if not func:
        return "00"
    types = list([inp['type'] for inp in func.get('inputs', [])])
    if func.get('name'):
        result = function_abi_to_4byte_selector(func) + encode_abi(types, args)
    else:
        result = encode_abi(types, args)
    return result.hex()
Example #13
0
 def get_transaction_data_from_chromosome(self, chromosome_index):
     data = ""
     arguments = []
     function = None
     for j in range(len(self.chromosome[chromosome_index]["arguments"])):
         if self.chromosome[chromosome_index]["arguments"][j] == "fallback":
             function = "fallback"
             data += random.choice(["", "00000000"])
         elif self.chromosome[chromosome_index]["arguments"][j] == "constructor":
             function = "constructor"
             data += self.generator.bytecode
         elif not type(self.chromosome[chromosome_index]["arguments"][j]) is bytearray and \
                 not type(self.chromosome[chromosome_index]["arguments"][j]) is list and \
                 self.chromosome[chromosome_index]["arguments"][j] in self.generator.interface:
             function = self.chromosome[chromosome_index]["arguments"][j]
             data += self.chromosome[chromosome_index]["arguments"][j]
         else:
             arguments.append(self.chromosome[chromosome_index]["arguments"][j])
     try:
         argument_types = [argument_type.replace(" storage", "").replace(" memory", "") for argument_type in self.generator.interface[function]]
         data += encode_abi(argument_types, arguments).hex()
     except Exception as e:
         self.logger.error("%s", e)
         self.logger.error("%s: %s -> %s", function, self.generator.interface[function], arguments)
         sys.exit(-6)
     return data
Example #14
0
def signAndExecute(inst, helper, signers, action, opts={}):
    nonce_slot = int(inst.address, 16) + 1
    nonce = int(web3.eth.getStorageAt(inst.address, nonce_slot).hex(), 16)

    # encode data for delegatecall to helper contract
    forward_data = helper.call.encode_input(action.target, action.value,
                                            action.data)
    hash_data = web3.solidityKeccak(['bytes'], [forward_data])

    struct_preimg = encode_abi(
        ['bytes32', 'uint256', 'address', 'uint256', 'bytes32'],
        [
            bytes.fromhex(YUL_TYPEHASH[2:]),
            nonce,
            helper.address,  # delegatecall goes to the helper contract
            action.gas,
            hash_data
        ])
    hash_struct = web3.keccak(struct_preimg)
    digest = web3.solidityKeccak(
        ['bytes1', 'bytes1', 'bytes32', 'bytes32'],
        ['0x19', '0x01',
         bytes.fromhex(YUL_DOMAIN_SEPARATOR[2:]), hash_struct])
    sigs = allSignUnpacked(signers, digest)

    return inst.execute(helper.address, action.gas, forward_data, sigs)
Example #15
0
def create_callback(msg_hex, sig_hex):
    msg_bytes = Web3.toBytes(hexstr=msg_hex)
    sig_bytes = Web3.toBytes(hexstr=sig_hex)
    ec_recover_args = (msg_bytes, sig_bytes)
    encoded_abi = eth_abi.encode_abi(['bytes', 'bytes'], ec_recover_args)

    return Web3.toHex(encoded_abi)
Example #16
0
async def test_responder_receive_timeout(config):

    if not ENABLE_THIS_TESTS:
        return

    (contract_minter, contract_address, contract_abi, url,
     port) = setUp(config, 'left')
    w3 = Web3(Web3.HTTPProvider(url + ":" + str(port)))
    token_instance = w3.eth.contract(abi=contract_abi,
                                     address=contract_address)
    (tokenId, cost) = await create_token(contract_minter, token_instance, w3)
    assert token_instance.functions.getStateOfToken(tokenId).call() == 0
    ### Test Ethereum Responder ###

    resp = EthereumResponder(contract_minter,
                             contract_address,
                             contract_abi,
                             url,
                             port=port)

    data = encode_abi(['uint256'], [tokenId])
    nonce = "42"
    resp.timeout = 0
    result = await resp.send_data(nonce, data)
    assert result["status"] == False
    assert result["error_code"] == ErrorCode.TIMEOUT
Example #17
0
def generate_data(dataset_address, key, price, timestamp):
    V, R, S = [], [], []
    for pk in PROVIDER_PKS.split(","):
        v, r, s = sign_aggregate(
            dataset_address, str.encode(key), price, timestamp, 1, pk
        )
        V.append(v)
        R.append(r)
        S.append(s)
    return (
        "0x"
        + (
            function_signature_to_4byte_selector(
                "report(bytes,uint256,uint64,uint8,uint8[],bytes32[],bytes32[])"
            )
            + encode_abi(
                [
                    "bytes",
                    "uint256",
                    "uint64",
                    "uint8",
                    "uint8[]",
                    "bytes32[]",
                    "bytes32[]",
                ],
                [str.encode(key), price, timestamp, 1, V, R, S],
            )
        ).hex()
    )
Example #18
0
def _verify_token_networks(chain_id: ChainID, apikey: str) -> None:
    deployment_file_path = contracts_deployed_path(chain_id=chain_id)
    with deployment_file_path.open() as f:
        deployed_contracts_info = json.load(f)
    token_networks = deployed_contracts_info.get("token_networks", [])

    with open(contracts_precompiled_path()) as f:
        contract_dict = json.load(f)["contracts"][CONTRACT_TOKEN_NETWORK]
    metadata = json.loads(contract_dict["metadata"])
    constructor = [
        func for func in contract_dict["abi"] if func["type"] == "constructor"
    ][0]
    arg_types = [arg["type"] for arg in constructor["inputs"]]
    arg_names = [arg["name"] for arg in constructor["inputs"]]

    for tn in token_networks:
        args = [
            tn["constructor_arguments"][arg_name] for arg_name in arg_names
        ]
        etherscan_verify_contract(
            chain_id=chain_id,
            apikey=apikey,
            address=tn["token_network_address"],
            contract_name=CONTRACT_TOKEN_NETWORK,
            metadata=metadata,
            constructor_args=encode_abi(arg_types, args).hex(),
        )
Example #19
0
def get_constructor_arguments(contract: Contract,
                              args: Optional[list] = None,
                              kwargs: Optional[dict] = None):
    """Get constructor arguments for Etherscan verify.

    https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments
    """

    # return contract._encode_constructor_data(args=args, kwargs=kwargs)
    constructor_abi = get_constructor_abi(contract.abi)

    # constructor_abi can be none in case of libraries
    if constructor_abi is None:
        return to_hex(contract.bytecode)

    if args is not None:
        return contract.encodeABI(constructor_abi['name'], args)[2:]  # No 0x
    else:
        constructor_abi = get_constructor_abi(contract.abi)
        kwargs = kwargs or {}
        arguments = merge_args_and_kwargs(constructor_abi, [], kwargs)
        # deploy_data = add_0x_prefix(
        #    contract._encode_abi(constructor_abi, arguments)
        # )

        # TODO: Looks like recent Web3.py ABI change
        deploy_data = encode_abi(contract.web3, constructor_abi, arguments)
        return deploy_data
 def queue_upgrade(self, proxyAddress, newLogicAddress,
                   delay=2 * days(2)) -> str:
     target = self.devProxyAdmin.address
     signature = "upgrade(address,address)"
     data = encode_abi(["address", "address"],
                       [proxyAddress, newLogicAddress])
     eta = web3.eth.getBlock("latest")["timestamp"] + delay
     return self.governance_queue_transaction(target, signature, data, eta)
def generate_signature(symbol, timestamp, value, private_key):
    message = encode_abi(
        ["string", "uint64", "string", "uint64"],
        ["prices",
         int(timestamp), symbol,
         int(float(value) * 1000000)],
    )
    # // This part prepares "version E" messages, using the EIP-191 standard
    sign_message = messages.encode_defunct(keccak(message))

    # // This part signs any EIP-191-valid message
    signed_message = Account.sign_message(sign_message,
                                          private_key=private_key)
    return message, encode_abi(
        ["uint256", "uint256", "uint256"],
        [signed_message.r, signed_message.s, signed_message.v],
    )
Example #22
0
def deriveAPK(ask):
    # a_pk = sha256(a_sk || 0^256)
    zeroes = "0000000000000000000000000000000000000000000000000000000000000000"
    a_pk = hashlib.sha256(
        encode_abi(
            ["bytes32", "bytes32"],
            [bytes.fromhex(ask), bytes.fromhex(zeroes)])).hexdigest()
    return a_pk
def test_contract_constructor_encoding_encoding(
        WithConstructorArgumentsContract, bytes_arg):
    deploy_data = WithConstructorArgumentsContract._encode_constructor_data(
        [1234, bytes_arg])
    encoded_args = '0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000'  # noqa: E501
    expected_ending = encode_hex(
        encode_abi(['uint256', 'bytes32'], [1234, b'abcd']))
    assert expected_ending == encoded_args
    assert deploy_data.endswith(remove_0x_prefix(expected_ending))
Example #24
0
 def _pack_data(self, func_name, input_types, input_values):
     try:
         data = self.func_hashes[func_name]
     except:
         raise Exception('Unknown method')
     if input_types is not None:
         data += self.encode_hex(encode_abi(input_types,
                                            input_values))[0].decode()
     return data
Example #25
0
def test_encode_abi(type_str, python_value, abi_encoding, _):
    abi_type = parse(type_str)
    if abi_type.arrlist is not None:
        pytest.skip('ABI coding functions do not support array types')

    types = [str(t) for t in abi_type.components]

    actual = encode_abi(types, python_value)
    assert actual == abi_encoding
Example #26
0
def encode_nodes(accounts):
    encoded_accounts = []
    for index in range(0, len(accounts)):
        data = accounts[index]
        encoded = encode_hex(
            encode_abi(["uint256", "address", "uint256"],
                       (index, data["account"], data["score"])))
        encoded_accounts.append(encoded)
    return encoded_accounts
Example #27
0
def onRequestBuy(event):
    # print(event)
    user = event.args["buyer"]
    keys = masterfile_contract.functions.userKeys(user).call()
    tokenId = event.args["tokenId"]
    token = masterfile_contract.functions.tokenData(tokenId).call()
    uri = token[1]
    label = token[2]
    print(user)
    print(token)

    global globalStorage

    # Call token transfer

    # using fake policy id
    compiled_data = encode_abi(['bytes16', 'uint256', 'string', 'address[]'], [
        Random.new().read(16), 432000, label,
        [
            "0x9920328f8D239613cDfFea4578e37d843772738F",
            "0xf71C4fbb1D0a85ded90c58fF347a026E6b8146AC",
            "0xC11F4fAa477b1634369153c8654eEF581425AD15"
        ]
    ])

    masterfile_contract.functions.safeTransferFrom(
        token[0], user, tokenId, 1,
        compiled_data).transact({'from': w3.eth.accounts[0]})

    # Revoke old policy
    try:
        if globalStorage[uri]["policy"]:
            alice.revoke(globalStorage[uri]["policy"])
            print("Policy Revoked")
    except:
        print("No Policy")

    # Distribute kfrags
    # try:
    print(keys)
    bob = Bob.from_public_keys(verifying_key=keys[0],
                               encrypting_key=keys[1],
                               federated_only=True)
    policy = alice.grant(bob,
                         label=uri.encode(),
                         m=2,
                         n=3,
                         expiration=maya.now() + timedelta(days=5))
    temp = globalStorage[uri]
    temp["policy"] = policy
    globalStorage[uri] = temp

    # except:
    #     print("policy exsists")

    policy.treasure_map_publisher.block_until_complete()
    print("Policy {} was created".format(label))
def hash_integers(values):
    k = bytes(32)

    for i in range(0,len(values)):
        k1 = int(values[i]).to_bytes(32, byteorder='big')
        v = encode_abi(['bytes32','bytes32'],[k,k1])
        k = hashlib.sha256(v).digest()

    return bytes_to_int(k)
Example #29
0
    def encode_params(datatypes: list, values: list) -> str:
        for idx, item in enumerate(datatypes):
            if item == 'address':
                if isinstance(values[idx], int):
                    values[idx] = bytecode_to_bytes(hex(values[idx]))
                elif isinstance(values[idx], str):
                    values[idx] = bytecode_to_bytes(values[idx])

        return encode_abi(datatypes, values).hex()
Example #30
0
def test_multi_abi_reversibility(types_and_values):
    """
    Tests round trip encoding and decoding for basic types and lists of basic
    types.
    """
    types, values = types_and_values
    encoded_values = encode_abi(types, values)
    decoded_values = decode_abi(types, encoded_values)
    assert values == decoded_values
def test_multi_abi_reversibility(types_and_values):
    """
    Tests round trip encoding and decoding for basic types and lists of basic
    types.
    """
    types, values = types_and_values
    encoded_values = encode_abi(types, values)
    decoded_values = decode_abi(types, encoded_values)
    assert values == decoded_values
Example #32
0
 def impl(self, seq, *args):
     if len(args) != len(func_abi["inputs"]):
         raise Exception(
             "Function with abi {} passed not matching {} args".format(
                 func_abi, list(args)))
     encoded_input = func_id + eth_abi.encode_abi(
         [inp["type"] for inp in func_abi["inputs"]], list(args))
     msg_data = sized_byterange.frombytes(encoded_input)
     return value.Tuple([msg_data, address, seq])
Example #33
0
 def _encodeABI(cls, abi, arguments, data=None):
     arguent_types = get_abi_input_types(abi)
     encoded_arguments = encode_abi(arguent_types, force_obj_to_bytes(arguments))
     if data:
         return add_0x_prefix(
             force_bytes(remove_0x_prefix(data)) +
             force_bytes(remove_0x_prefix(encode_hex(encoded_arguments)))
         )
     else:
         return encode_hex(encoded_arguments)
Example #34
0
def test_wrong_type_match_data():
    data = ("hello", "goodbye")
    match_data_and_abi = (
        ("string", (50505050,)),
        ("string", (50505050,)),
    )
    abi_types, match_data = zip(*match_data_and_abi)
    encoded_data = encode_abi(abi_types, data)
    with pytest.raises(ValueError):
        match_fn(match_data_and_abi, encoded_data)
def test_always_positive_multi(_type, value):
    """
    Tests round trip encoding and decoding for basic types and lists of basic
    types.
    """
    assert value >= 0

    encoded_value = encode_abi([_type], [value])
    decoded_value = decode_abi([_type], encoded_value)

    assert decoded_value[0] >= 0
Example #36
0
    def _encode_abi(cls, abi, arguments, data=None):
        argument_types = get_abi_input_types(abi)

        if not check_if_arguments_can_be_encoded(abi, arguments, {}):
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type.  Expected types are: {0}".format(
                    ', '.join(argument_types),
                )
            )

        try:
            normalizers = [
                abi_ens_resolver(cls.web3),
                abi_address_to_hex,
                abi_bytes_to_hex,
                abi_string_to_hex,
                hexstrs_to_bytes,
            ]
            normalized_arguments = map_abi_data(
                normalizers,
                argument_types,
                arguments,
            )
            encoded_arguments = encode_abi(
                argument_types,
                normalized_arguments,
            )
        except EncodingError as e:
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type: {0}".format(str(e))
            )

        if data:
            return to_hex(HexBytes(data) + encoded_arguments)
        else:
            return encode_hex(encoded_arguments)
def test_encode_multiple_arguments(types, value, expected):
    actual = encode_abi(types, value)
    assert actual == expected
def test_encode_array_types(types, value, expected):
    actual = encode_abi(types, value)
    assert actual == expected
def test_contract_constructor_encoding_encoding(WithConstructorArgumentsContract, bytes_arg):
    deploy_data = WithConstructorArgumentsContract._encode_constructor_data([1234, bytes_arg])
    encoded_args = '0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000'  # noqa: E501
    expected_ending = encode_hex(encode_abi(['uint256', 'bytes32'], [1234, b'abcd']))
    assert expected_ending == encoded_args
    assert deploy_data.endswith(remove_0x_prefix(expected_ending))
Example #40
0
def test_match_fn_with_various_data_types(data, expected, match_data_and_abi):
    abi_types, match_data = zip(*match_data_and_abi)
    encoded_data = encode_abi(abi_types, data)
    assert match_fn(match_data_and_abi, encoded_data) == expected