Example #1
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 #2
0
def encode_abi(web3, 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(web3),
            abi_address_to_hex,
            abi_bytes_to_bytes,
            abi_string_to_text,
        ]
        normalized_arguments = map_abi_data(
            normalizers,
            argument_types,
            arguments,
        )
        encoded_arguments = eth_abi_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 #3
0
    def extract_secret_from_redeem_transaction(self, tx_address: str) -> str:
        '''
        Extracting secret from redeem transaction.

        Args:
            tx_address (str): address of the redeem transaction

        Returns:
            str,: Secret string

        Raises:
            ValueError: When given transaction was not a redeem type transaction

        Example:
            >>> from clove.network import EthereumTestnet
            >>> network = EthereumTestnet()
            >>> network.extract_secret_from_redeem_transaction('0x9e41847c3cc780e4cb59902cf55657f0ee92642d9dee4145e090cbf206d4748f')  # noqa: E501
            b2eefaadbbefeb9d9467092b612464db7c6724f71b5c1d70c85853845728f0e9
        '''
        tx_dict = self.get_transaction(tx_address)
        method_id = self.extract_method_id(tx_dict['input'])
        if method_id != self.redeem:
            logger.debug('Not a redeem transaction.')
            raise ValueError('Not a redeem transaction.')
        method_name = self.get_method_name(method_id)
        input_types = get_abi_input_types(
            find_matching_fn_abi(self.abi, fn_identifier=method_name))
        input_values = decode_abi(input_types,
                                  Web3.toBytes(hexstr=tx_dict['input'][10:]))
        return input_values[0].hex()
Example #4
0
    def encodeConstructorData(cls, arguments=None):
        if arguments is None:
            arguments = []

        constructor = get_constructor_abi(cls.abi)
        if constructor:
            if constructor['inputs'] and not arguments:
                raise ValueError(
                    "This contract requires {0} constructor arguments".format(
                        len(constructor['inputs']),
                    )
                )
            if arguments:
                if len(arguments) != len(constructor['inputs']):
                    raise ValueError(
                        "This contract requires {0} constructor arguments".format(
                            len(constructor['inputs']),
                        )
                    )

                is_encodable = check_if_arguments_can_be_encoded(
                    get_abi_input_types(constructor),
                    arguments,
                )
                if not is_encodable:
                    raise ValueError("Unable to encode provided arguments.")

            deploy_data = add_0x_prefix(cls._encodeABI(constructor, arguments, data=cls.code))
        else:
            deploy_data = add_0x_prefix(cls.code)

        return deploy_data
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)
def test_finds_function_with_matching_args(web3, arguments, expected_types):
    Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS)

    abi = Contract._find_matching_fn_abi('a', arguments)
    assert abi['name'] == 'a'
    assert len(abi['inputs']) == len(expected_types)
    assert set(get_abi_input_types(abi)) == set(expected_types)
def test_finds_function_with_matching_args(web3, arguments, expected_types):
    Contract = web3.eth.contract(abi=MULTIPLE_FUNCTIONS)

    abi = Contract._find_matching_fn_abi('a', arguments)
    assert abi['name'] == 'a'
    assert len(abi['inputs']) == len(expected_types)
    assert set(get_abi_input_types(abi)) == set(expected_types)
Example #8
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 #9
0
 def extract_secret_from_redeem_transaction(self, tx_address: str) -> str:
     tx_dict = self.get_transaction(tx_address)
     method_id = self.extract_method_id(tx_dict['input'])
     if method_id != self.redeem:
         logger.debug('Not a redeem transaction.')
         raise ValueError('Not a redeem transaction.')
     method_name = self.get_method_name(method_id)
     input_types = get_abi_input_types(find_matching_fn_abi(self.abi, fn_identifier=method_name))
     input_values = decode_abi(input_types, Web3.toBytes(hexstr=tx_dict['input'][10:]))
     return input_values[0].hex()
Example #10
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 #11
0
 def sanitize_args(abi: Dict, args: List):
     """Prepare inputs to match the ABI"""
     inputs = get_abi_input_types(abi)
     output = []
     assert len(inputs) == len(args)
     for input_type, arg in zip(inputs, args):
         if input_type == 'address':
             output.append(to_checksum_address(arg))
         elif input_type == 'bytes' and isinstance(arg, str):
             output.append(arg.encode())
         else:
             output.append(arg)
     return output
Example #12
0
 def sanitize_args(abi: Dict, args: List):
     """Prepare inputs to match the ABI"""
     inputs = get_abi_input_types(abi)
     output = []
     assert len(inputs) == len(args)
     for input_type, arg in zip(inputs, args):
         if input_type == 'address':
             output.append(to_checksum_address(arg))
         elif input_type == 'bytes' and isinstance(arg, str):
             output.append(arg.encode())
         else:
             output.append(arg)
     return output
Example #13
0
    def __init__(self, network, tx_dict):

        self.network = network
        self.tx_dict = tx_dict
        self.method_id = self.network.extract_method_id(tx_dict['input'])
        self.type = self.network.get_method_name(self.method_id)
        self.token = None

        if not self.is_initiate:
            logger.warning('Not a contract transaction.')
            raise ValueError('Not a contract transaction.')

        if self.is_token_contract:
            self.abi = self.network.token_abi
        else:
            self.abi = self.network.abi

        input_types = get_abi_input_types(
            find_matching_fn_abi(self.abi, fn_identifier=self.type))
        input_names = get_abi_input_names(
            find_matching_fn_abi(self.abi, fn_identifier=self.type))
        input_values = decode_abi(
            input_types, Web3.toBytes(hexstr=self.tx_dict['input'][10:]))
        self.inputs = dict(zip(input_names, input_values))

        self.locktime = datetime.utcfromtimestamp(self.inputs['_expiration'])
        self.recipient_address = Web3.toChecksumAddress(
            self.inputs['_participant'])
        self.refund_address = self.tx_dict['from']
        self.secret_hash = self.inputs['_hash'].hex()
        self.contract_address = Web3.toChecksumAddress(self.tx_dict['to'])
        self.confirmations = self.network.latest_block - self.tx_dict[
            'blockNumber']

        if self.is_token_contract:
            self.value_base_units = self.inputs['_value']
            self.token_address = Web3.toChecksumAddress(self.inputs['_token'])
            self.token = self.network.get_token_by_address(self.token_address)
            self.value = self.token.value_from_base_units(
                self.value_base_units)
            self.symbol = self.token.symbol
        else:
            self.value_base_units = self.tx_dict['value']
            self.value = self.network.value_from_base_units(
                self.value_base_units)
            self.symbol = self.network.default_symbol
Example #14
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)
Example #15
0
def encode_function_call(abi: Dict, function: str, args: List = list()):
    fn_abi = find_matching_fn_abi(abi, function, args)
    fn_types = get_abi_input_types(fn_abi)
    return encode_abi(fn_types, args)