How to use the iconservice.base.type_converter.TypeConverter function in iconservice

To help you get started, we’ve selected a few iconservice examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github icon-project / icon-service / tests / unittest / deploy / test_icon_score_deploy_engine.py View on Github external
def test_initialize_score_on_install(self, mock_engine, mocker):
        """case on_install"""
        deploy_type = DeployType.INSTALL

        self.set_test(mocker)

        mock_engine._initialize_score(deploy_type, self.mock_score, self.params)
        TypeConverter.adjust_params_to_method.assert_called_with(
            self.on_install, self.params
        )
        self.on_install.assert_called_with(**self.params)
        self.on_update.assert_not_called()
        self.on_invalid.assert_not_called()
        mocker.stopall()
github icon-project / icon-service / tests / integrate_test / test_integrate_icon_service_engine.py View on Github external
'method': 'icx_sendTransaction',
                    'params': {
                        'from': str(self._admin.address),
                        'to': to,
                        'fee': hex(fixed_fee),
                        'value': hex(value),
                        'timestamp': '0x574024617ae39',
                        'nonce': '0x1',
                        'signature': 'yKMiB12Os0ZK9+XYiBSwydvMXA0y/LS9HzmZwtczQ1VAK98/mGUOmpwTjByFArjdkx72GOWIOzu6eqyZnKeHBAE=',
                        'txHash': tx_hash.hex()
                    }
                }
            ]
        }

        params = TypeConverter.convert(request, ParamType.INVOKE)
        converted_block_params = params['block']
        block = Block.from_dict(converted_block_params)

        self.assertEqual(block_height, block.height)
        self.assertEqual(block_hash, block.hash)
        self.assertEqual(prev_block_hash, block.prev_hash)
        self.assertEqual(timestamp, block.timestamp)

        transactions: list = params['transactions']
        self.assertIsInstance(transactions[0]['params']['to'], MalformedAddress)

        tx_results, state_root_hash, _, _ = self.icon_service_engine.invoke(block, transactions)
        self.assertIsInstance(state_root_hash, bytes)
        self.assertEqual(len(state_root_hash), 32)
        self.assertEqual(len(tx_results), 1)
github icon-project / icon-service / iconservice / fee / engine.py View on Github external
def handle_deposit_request(self, context: 'IconScoreContext', data: dict):
        """
        Handles fee request(querying or invoking)

        :param context: IconScoreContext
        :param data: data field
        :return:
        """
        converted_data = TypeConverter.convert(data, ParamType.DEPOSIT_DATA)
        action = converted_data['action']

        try:
            if action == 'add':
                term: int = BLOCKS_IN_ONE_MONTH if FIXED_TERM else converted_data['term']
                self._add_deposit(context, term)
            elif action == 'withdraw':
                self._withdraw_deposit(context, converted_data['id'])
            else:
                raise InvalidRequestException(f"Invalid action: {action}")
        except KeyError:
            # missing required params for the action
            raise InvalidParamsException("Required params not found")
github icon-project / icon-service / iconservice / iconscore / icon_score_api_generator.py View on Github external
main_type = get_main_type_from_annotations_type(param.annotation)
        main_type = ScoreApiGenerator.__convert_str_to_type(main_type)
        api_type = ScoreApiGenerator.__find_base_super_type(main_type)
        if api_type is None:
            raise IllegalFormatException(
                f"Unsupported type for '{param.name}: {param.annotation}'")
        info = dict()
        info[ScoreApiGenerator.__API_NAME] = param.name
        info[ScoreApiGenerator.__API_TYPE] = api_type.__name__
        if is_indexed:
            info[ScoreApiGenerator.__API_INPUTS_INDEXED] = is_indexed
        if param.default is not Parameter.empty:
            if param.default is not None and not isinstance(param.default, main_type):
                raise InvalidParamsException(f'Default params type mismatch. value: {param.default} type: {main_type}')
            info[ScoreApiGenerator.__API_INPUTS_DEFAULT] = TypeConverter.convert_type_reverse(param.default)
        src.append(info)
github icon-project / icon-service / iconservice / iiss / engine.py View on Github external
if len(params) == 1:
            delegations: Optional[List[Dict[str, str]]] = params[ConstantKeys.DELEGATIONS]
        elif len(params) == 0:
            delegations = None
        else:
            raise InvalidParamsException(f"Invalid params: {params}")

        assert delegations is None or isinstance(delegations, list)

        if delegations is None or len(delegations) == 0:
            return 0, []

        if len(delegations) > IISS_MAX_DELEGATIONS:
            raise InvalidParamsException("Delegations out of range")

        ret_params: dict = TypeConverter.convert(params, ParamType.IISS_SET_DELEGATION)
        delegations: List[Dict[str, Union['Address', int]]] = \
            ret_params[ConstantKeys.DELEGATIONS]

        total_delegating: int = 0
        converted_delegations: List[Tuple['Address', int]] = []
        delegated_addresses: Dict['Address', int] = {}

        for delegation in delegations:
            address: 'Address' = delegation["address"]
            value: int = delegation["value"]
            assert isinstance(address, Address)
            assert isinstance(value, int)

            if value < 0:
                raise InvalidParamsException(f"Invalid delegating amount: {value}")
github icon-project / icon-service / iconservice / iiss / engine.py View on Github external
def handle_get_delegation(self,
                              context: 'IconScoreContext',
                              params: dict) -> dict:
        """Handles getDelegation JSON-RPC API request

        :param context:
        :param params:
        :return:
        """
        ret_params: dict = TypeConverter.convert(params, ParamType.IISS_GET_DELEGATION)
        address: 'Address' = ret_params[ConstantKeys.ADDRESS]
        return self._get_delegation(context, address)
github icon-project / icon-service / iconservice / prep / handler / candidate_handler.py View on Github external
def handle_get_prep_candidate_list(cls, context: 'IconScoreContext', params: dict) -> dict:

        ret_params: dict = TypeConverter.convert(params, ParamType.IISS_GET_PREP_CANDIDATE_LIST)
        return cls._get_prep_candidate_list(context, ret_params)
github icon-project / icon-service / iconservice / base / type_converter.py View on Github external
) -> Any:
        if TypeConverter._skip_params(params, template):
            return params

        if isinstance(template, dict) and KEY_CONVERTER in template:
            params = TypeConverter._convert_key(params, template[KEY_CONVERTER])

        if isinstance(params, dict) and isinstance(template, dict):
            new_params = {}
            for key, value in params.items():
                if TypeConverter._check_convert_using_method(key, template):
                    ref_key_table = deepcopy(new_params)
                    target_template = TypeConverter._get_convert_using_method_template(
                        key, template
                    )
                    new_value = TypeConverter._convert_using_switch(
                        value, ref_key_table, target_template
                    )
                else:
                    new_value = TypeConverter._convert(value, template.get(key))
                new_params[key] = new_value
        elif isinstance(params, list) and isinstance(template, list):
            new_params = []
            for item in params:
                if isinstance(item, list):
                    new_item = []
                    for element, templete_type in zip(item, template[0]):
                        new_element = TypeConverter._convert(element, templete_type)
                        new_item.append(new_element)
                    new_params.append(new_item)
                else:
                    new_item = TypeConverter._convert(item, template[0])
github icon-project / icon-service / iconservice / base / type_converter.py View on Github external
def _convert_data_value(annotation_type: type, param: Any) -> Any:
        if annotation_type == int:
            param = TypeConverter._convert_value_int(param)
        elif annotation_type == str:
            param = TypeConverter._convert_value_string(param)
        elif annotation_type == bool:
            param = TypeConverter._convert_value_bool(param)
        elif annotation_type == Address:
            param = TypeConverter._convert_value_address(param)
        elif annotation_type == bytes:
            param = TypeConverter._convert_value_bytes(param)
        return param
github icon-project / icon-service / iconservice / base / type_converter.py View on Github external
def convert_type_reverse(value: Any):
        if isinstance(value, dict):
            for k, v in value.items():
                if isinstance(v, bytes):
                    is_hash = k in ('blockHash', 'txHash')
                    value[k] = TypeConverter._convert_bytes_reverse(v, is_hash)
                else:
                    value[k] = TypeConverter.convert_type_reverse(v)
        elif isinstance(value, list):
            for i, v in enumerate(value):
                value[i] = TypeConverter.convert_type_reverse(v)
        elif isinstance(value, int):
            value = hex(value)
        elif isinstance(value, Address):
            value = str(value)
        elif isinstance(value, bytes):
            value = TypeConverter._convert_bytes_reverse(value)
        return value