def transfer(self, conf: dict) -> dict:
        """Transfer ICX Coin.

        :param conf: transfer command configuration.
        :return: response of transfer.
        """
        # check value type (must be int), address and keystore file
        # if valid, return user input password
        password = conf.get('password', None)
        password = self._check_transfer(conf, password)

        if password:
            try:
                wallet = KeyWallet.load(conf['keyStore'], password)
                from_ = wallet.get_address()

            except KeyStoreException as e:
                print(e.args[0])
                return None
        else:
            # make dummy wallet
            wallet = KeyWallet.create()
            from_ = conf['from']

        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        transaction = TransactionBuilder() \
            .from_(from_) \
            .to(conf['to']) \
            .value(int(conf['value'])) \
            .nid(convert_hex_str_to_int(conf['nid'])) \
            .timestamp(int(time() * 10 ** 6)) \
            .build()

        if 'stepLimit' not in conf:
            step_limit = icon_service.estimate_step(transaction)
        else:
            step_limit = convert_hex_str_to_int(conf['stepLimit'])

        transaction.step_limit = step_limit

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, wallet)

        if not password:
            signed_transaction.signed_transaction_dict['signature'] = 'sig'

        # Sends transaction and return response
        response = send_transaction_with_logger(icon_service, signed_transaction, uri)

        if 'result' in response:
            print('Send transfer request successfully.')
            tx_hash = response['result']
            print(f"transaction hash: {tx_hash}")
        else:
            print('Got an error response')
            print(json.dumps(response, indent=4))

        return response
Ejemplo n.º 2
0
def convert_common_data_on_transaction(transaction: dict):
    """
    Convert common fields in the transaction such as value, fee, nid, stepLimit, timestamp, nonce, method, version, data.
    Used in validating a transaction list in a block or validating a single transaction.

    1. Fields such as value, fee, nid, stepLimit, timestamp, and nonce have to be converted to an integer.
    2. Fields such as timestamp and nonce have a different type of the value by the version as V2 or V3.
        - If the version V3, the data type is hex string prefixed with '0x'.
        - If the version V2, the data type is a string but the meaning is an integer.
    3. The field 'method' has to be removed.
    4. The field 'version' has to be added number 2 if the version is 2 or if 3, has to be converted to an integer.
    5. If the field 'dataType' is 'deploy', the field 'content' has to be converted to bytes.
       Or if 'message', the field 'data' has to be converted to an integer.

    :param transaction: data about the single transaction
    """

    # List of Fields which have to be converted to int
    int_fields = ["value", "fee", "nid", "stepLimit"]

    for int_field in int_fields:
        if int_field in transaction:
            transaction[int_field] = convert_hex_str_to_int(
                transaction[int_field])

    odd_fields = ["timestamp", "nonce"]

    for odd_field in odd_fields:
        if odd_field in transaction:
            if is_integer(transaction[odd_field]):
                pass
            elif is_0x_prefixed(transaction[odd_field]):
                transaction[odd_field] = convert_hex_str_to_int(
                    transaction[odd_field])
            else:
                transaction[odd_field] = int(transaction[odd_field])

    if "method" in transaction:
        del transaction["method"]

    if "version" in transaction and convert_hex_str_to_int(
            transaction["version"]) >= 3:
        transaction["version"] = convert_hex_str_to_int(transaction["version"])
    else:
        transaction["version"] = 2

    if "dataType" in transaction:
        if transaction["dataType"] == "deploy":
            transaction["data"]["content"] = convert_hex_str_to_bytes(
                transaction["data"]["content"])
        elif transaction["dataType"] == "message":
            transaction["data"] = bytearray.fromhex(
                remove_0x_prefix(transaction["data"])).decode()
Ejemplo n.º 3
0
def votingResults(walletName) -> dict:
    params = {}
    call = CallBuilder().from_(wallets.get(walletName).get_address()) \
        .to(default_score) \
        .method("get_vote_talley") \
        .params(params) \
        .build()
    result = icon_service.call(call)

    votesResult = {}
    votesResult['yes'] = convert_hex_str_to_int(result['yes'])
    votesResult['no'] = convert_hex_str_to_int(result['no'])
    return json.dumps(votesResult)
Ejemplo n.º 4
0
    def block(self, conf):
        """Query block with given parameter(height or hash)

        :param conf: block command configuration
        :return: result of query
        """
        uri, version = uri_parser(conf['uri'])
        icon_service, response = IconService(HTTPProvider(uri, version)), None
        hash, number = conf.get('hash'), conf.get('number')
        if hash is not None and number is not None:
            raise TBearsCommandException(
                "Only one of id and number can be passed.")
        if hash is not None:
            response = icon_service.get_block(hash, True, BLOCK_0_3_VERSION)
        if number is not None:
            response = icon_service.get_block(convert_hex_str_to_int(number),
                                              True, BLOCK_0_3_VERSION)
        if response is None:
            raise TBearsCommandException(
                "You have to specify block height or block hash")

        if "error" in response:
            print(json.dumps(response, indent=4))
        else:
            print(f"block info : {json.dumps(response, indent=4)}")

        return response
Ejemplo n.º 5
0
def convert_transaction_result(data: dict):
    """
    Convert transaction result data into the right format.
    It supports data about a transaction made not only from JSON RPC V3 but also from V2.

    1. Fields such as status, blockHeight, txIndex, stepUsed, stepPrice, cumulativeStepUsed have to be converted to an integer.
    2. The field 'logsBloom' has to be converted to bytes.

    :param data: data about the transaction result
    """
    # Only for the transaction made with JSON RPC V2 successfully does not have the property 'status'
    if "status" not in data and "code" in data and data["code"] == 0:
        data["status"] = 1
        del data["code"]
        return

    # List of Fields which have to be converted to int
    int_fields = [
        "status", "blockHeight", "txIndex", "stepUsed", "stepPrice",
        "cumulativeStepUsed"
    ]

    for int_field in int_fields:
        if int_field in data:
            data[int_field] = convert_hex_str_to_int(data[int_field])

    if "logsBloom" in data:
        data["logsBloom"] = convert_hex_str_to_bytes(data["logsBloom"])
Ejemplo n.º 6
0
def convert_transaction(transaction: dict):
    """
    Convert transaction data into the right format.
    It supports data about a transaction made not only from JSON RPC V3 but also from V2.

    [what to do on the method 'convert_common_data_on_transaction']
    1. Fields as value, fee, nid, stepLimit, timestamp, and nonce have to be converted to an integer.
    2. Fields as timestamp and nonce have a different type of the value by the version as V2 or V3.
        - If the version V3, the data type is hex string prefixed with '0x'.
        - If the version V2, the data type is a string but the meaning is an integer.
    3. The field 'method' has to be removed.
    4. The field 'version' has to be added number 2 if the version is 2 or if 3, has to be converted to an integer.
    5. If the field 'dataType' is 'deploy', the field 'content' has to be converted to bytes.
       Or if 'message', the field 'data' has to be converted to an integer.

    [Added]
    6. Fields as 'txIndex' and 'blockHeight' have to be converted to an integer.

    :param transaction: data about the single transaction
    """
    convert_common_data_on_transaction(transaction)

    # List of Fields which have to be converted to int
    int_fields = ["txIndex", "blockHeight"]

    for int_field in int_fields:
        if int_field in transaction:
            transaction[int_field] = convert_hex_str_to_int(
                transaction[int_field])
Ejemplo n.º 7
0
def get_financial_transaction(block):
    """
    Gets specific meaningful transactions and prints it.

    [What is the specific meaningful transaction]
    - First, finds ICX transactions on a block.
    - Second, finds token transfer on a block.  """
    # Returns the transaction list.
    tx_list = block["confirmed_transaction_list"]

    if len(tx_list) > 0:
        for tx in tx_list:
            print("\ntxHash:", tx["txHash"])
            tx_result = icon_service.get_transaction_result(tx["txHash"])

            # Finds ICX transaction
            if "value" in tx and tx["value"] > 0:
                print("[ICX]")
                print("status: ", tx_result["status"])
                print("from  : ", tx["from"])
                print("to    : ", tx["to"])
                print("amount: ", tx["value"])

            # Finds token transfer
            if "dataType" in tx and tx["dataType"] == "call" and "method" in tx["data"] and tx["data"]["method"] == "transfer":
                score_address = tx["to"]
                print(f"[{get_token_name(score_address)} Token({get_token_symbol(score_address)})]")
                print("status: ", tx_result["status"])
                print("from  : ", tx["from"])
                print("to    : ", tx["data"]["params"]["_to"])
                print("amount: ", convert_hex_str_to_int(tx["data"]["params"]["_value"]))
Ejemplo n.º 8
0
    def get_transaction(conf: dict, params: dict):
        data_type = params.get('dataType')
        params_data = params.get('data', {})

        try:
            transaction_params = {
                "from_": params['from'],
                "to": params['to'],
                "nid": convert_hex_str_to_int(conf['nid']),
                "value": convert_hex_str_to_int(params.get('value', "0x0"))
            }

            if data_type is None:
                transaction_builder = TransactionBuilder(**transaction_params)
            elif data_type == "call":
                transaction_params['method'] = params_data.get('method')
                transaction_params['params'] = params_data.get('params')
                transaction_builder = CallTransactionBuilder(
                    **transaction_params)
            elif data_type == "deploy":
                transaction_params['content'] = params_data.get('content')
                transaction_params['content_type'] = params_data.get(
                    'contentType')
                transaction_params['params'] = params_data.get('params')
                transaction_builder = DeployTransactionBuilder(**params)
            elif data_type == "message":
                transaction_params['data'] = params_data
                transaction_builder = MessageTransactionBuilder(
                    **transaction_params)
            elif data_type == "deposit":
                transaction_params['action'] = params_data.get('action')
                transaction_params['id'] = params_data.get('id')
                transaction_builder = DepositTransactionBuilder(
                    **transaction_params)
            else:
                raise JsonContentsException("Invalid dataType")
            transaction = transaction_builder.build()
        except KeyError:
            raise JsonContentsException(
                "Invalid json content. check json contents")
        except TypeError:
            raise JsonContentsException("Invalid json content. check keys")
        except DataTypeException:
            raise JsonContentsException("Invalid json content. check values")
        else:
            return transaction
def get_default_step_cost():
    _call = CallBuilder()\
        .from_(wallet1.get_address())\
        .to(GOVERNANCE_ADDRESS)\
        .method("getStepCosts")\
        .build()
    _result = icon_service.call(_call)
    default_step_cost = convert_hex_str_to_int(_result["default"])
    return default_step_cost
Ejemplo n.º 10
0
def get_max_step_limit():
    _param = {"context_type": "invoke"}
    _call = CallBuilder()\
        .from_(wallet1.get_address())\
        .to(GOVERNANCE_ADDRESS)\
        .method("getMaxStepLimit")\
        .params(_param)\
        .build()
    _result = icon_service.call(_call)
    return convert_hex_str_to_int(_result)
Ejemplo n.º 11
0
    def sendtx(self, conf: dict):
        """Send transaction.

        :param conf: sendtx command configuration.
        :return: response of transfer.
        """
        with open(conf['json_file'], 'r') as jf:
            payload = json.load(jf)

        password = conf.get('password', None)
        password = self._check_sendtx(conf, password)
        params = payload['params']

        if password and conf.get('keyStore'):
            try:
                wallet = KeyWallet.load(conf['keyStore'], password)
                params['from'] = wallet.get_address()

            except KeyStoreException as e:
                print(e.args[0])
                return None
        else:
            # make dummy wallet
            wallet = KeyWallet.create()

        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        transaction = self.get_transaction(conf, params)
        if 'stepLimit' not in conf:
            step_limit = icon_service.estimate_step(transaction)
        else:
            step_limit = convert_hex_str_to_int(conf['stepLimit'])

        transaction.step_limit = step_limit

        signed_transaction = SignedTransaction(transaction, wallet)

        if not password:
            signed_transaction.signed_transaction_dict['signature'] = 'sig'

        # Sends transaction
        response = send_transaction_with_logger(icon_service,
                                                signed_transaction, uri)

        if 'result' in response:
            print('Send transaction request successfully.')
            tx_hash = response['result']
            print(f"transaction hash: {tx_hash}")
        else:
            print('Got an error response')
            print(json.dumps(response, indent=4))

        return response
Ejemplo n.º 12
0
    def get_max_step_limit(self, wallet_address):
        params = {'contextType': 'invoke'}

        call_data = CallBuilder() \
          .from_(wallet_address) \
          .to(GOVERNANCE_ADDRESS) \
          .method('getMaxStepLimit') \
          .params(params) \
          .build()

        result = self.icon_service.call(call_data)
        return convert_hex_str_to_int(result)
Ejemplo n.º 13
0
    def test_duplicated_tx(self):
        # test start, deploy, stop, clean command
        conf = self.cmd.cmdUtil.get_init_args(project=self.project_name,
                                              score_class=self.project_class)

        # init
        self.cmd.cmdUtil.init(conf)

        # start
        tbears_config_path = os.path.join(TEST_UTIL_DIRECTORY,
                                          f'test_tbears_server_config.json')
        start_conf = IconConfig(tbears_config_path, tbears_server_config)
        start_conf.load()
        start_conf['config'] = tbears_config_path
        self.start_conf = start_conf
        self.cmd.cmdServer.start(start_conf)
        self.assertTrue(self.cmd.cmdServer.is_service_running())

        # prepare to send
        genesis_info = start_conf['genesis']['accounts'][0]
        from_addr = genesis_info['address']

        uri = f'http://127.0.0.1:{start_conf["port"]}/api/v3'
        uri, version = uri_parser(uri)

        icon_service = IconService(HTTPProvider(uri, version))

        to_addr = f'hx{"d" * 40}'
        timestamp = int(time.time() * 10**6)

        transaction = TransactionBuilder()\
            .from_(from_addr)\
            .to(to_addr)\
            .timestamp(timestamp)\
            .step_limit(convert_hex_str_to_int('0x100000'))\
            .build()

        wallet = KeyWallet.create()
        signed_transaction = SignedTransaction(transaction, wallet)
        signed_transaction.signed_transaction_dict['signature'] = 'sig'

        # send transaction
        response = send_transaction_with_logger(icon_service,
                                                signed_transaction, uri)
        self.assertTrue('result' in response)

        # send again
        response = send_transaction_with_logger(icon_service,
                                                signed_transaction, uri)
        self.assertTrue('error' in response)
        self.assertEqual(
            responseCodeMap[Response.fail_tx_invalid_duplicated_hash][1],
            response['error']['message'])
    def blockbyheight(self, conf):
        """Query block with given height

        :param conf: blockbyheight command configuration
        :return: result of query
        """
        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        response = icon_service.get_block(convert_hex_str_to_int(conf['height']), True)

        if "error" in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print(f"block info : {json.dumps(response, indent=4)}")

        return response
Ejemplo n.º 15
0
def myVote(walletName):
    params = {}
    call = CallBuilder().from_(wallets.get(walletName).get_address()) \
        .to(default_score) \
        .method("get_vote") \
        .params(params) \
        .build()
    result = icon_service.call(call)
    result_value = convert_hex_str_to_int(result['vote'])
    voted = ''

    if result_value == 1:
        voted = 'YES'
    elif result_value == 2:
        voted = 'NO'
    elif result_value == 0:
        voted = '-'

    return voted
print("params:")
pprint(signed_transaction.signed_transaction_dict)

# Sends transaction
tx_hash = icon_service.send_transaction(signed_transaction)
print("txHash: ", tx_hash)


@retry(JSONRPCException, tries=10, delay=1, back_off=2)
def get_tx_result():
    # Returns the result of a transaction by transaction hash
    tx_result = icon_service.get_transaction_result(tx_hash)
    print("transaction status(1:success, 0:failure): ", tx_result["status"])


get_tx_result()

params = {
    "_owner": wallet2.get_address()
}

call = CallBuilder()\
    .from_(wallet1.get_address())\
    .to(SCORE_ADDRESS)\
    .method("balanceOf")\
    .params(params)\
    .build()

result = icon_service.call(call)
print("balance: ", convert_hex_str_to_int(result))
Ejemplo n.º 17
0
    def deploy(self, conf: dict) -> dict:
        """Deploy SCORE on the server.
        :param conf: deploy command configuration
        """
        # check keystore, and get password from user's terminal input
        password = conf.get('password', None)
        password = self._check_deploy(conf, password)

        if conf['mode'] == 'install':
            score_address = f'cx{"0"*40}'
        else:
            score_address = conf['to']

        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        if password:
            try:
                wallet = KeyWallet.load(conf['keyStore'], password)
                from_ = wallet.get_address()

            except KeyStoreException as e:
                print(e.args[0])
                return None
        else:
            # make dummy wallet
            wallet = KeyWallet.create()
            from_ = conf['from']

        # make zip and convert to hexadecimal string data (start with 0x) and return
        content = gen_deploy_data_content(conf['project'])

        deploy_transaction = DeployTransactionBuilder() \
            .from_(from_) \
            .to(score_address) \
            .nid(convert_hex_str_to_int(conf['nid'])) \
            .content_type("application/zip") \
            .content(content) \
            .params(conf.get('scoreParams', {})) \
            .build()

        if 'stepLimit' not in conf:
            step_limit = icon_service.estimate_step(deploy_transaction) + 10000
        else:
            step_limit = convert_hex_str_to_int(conf['stepLimit'])

        deploy_transaction.step_limit = step_limit

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(deploy_transaction, wallet)

        if not password:
            signed_transaction.signed_transaction_dict['signature'] = 'sig'

        # Sends transaction and return response
        response = send_transaction_with_logger(icon_service,
                                                signed_transaction, uri)

        if 'error' in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print('Send deploy request successfully.')
            tx_hash = response['result']
            print(
                f'If you want to check SCORE deployed successfully, execute txresult command'
            )
            print(f"transaction hash: {tx_hash}")

        return response
Ejemplo n.º 18
0
from iconsdk.utils.convert_type import convert_hex_str_to_int
from aloxidesdk.aloxide_service import AloxideService, ICON_NETWORK

service = AloxideService({
    'type': ICON_NETWORK,
    'endpoint': 'https://bicon.net.solidwallet.io',
    'network_id': 3
})

params = {'_to': 'hx2b41326239dba22f7fa6b3e7ca308ee128c97d95', '_value': 10}

tx_result = service.write_data(
    {
        'contract_address': 'cx75ebc9841a5b7f84fa12729a251ff54e6572f66a',
        'action_name': 'transfer'
    }, {'wallet_key': 'key'}, params)

# txHash': '0x9c8c2a83c157c6ed71d9e0c4c2409c4f366c6d749dd71db16ebb26a0ba09d268'
print(tx_result)

params = {'_owner': 'hx61fc50bef6442e733febc9747715b27cebbd082b'}

tx_result = service.read_data(
    {
        'contract_address': 'cx75ebc9841a5b7f84fa12729a251ff54e6572f66a',
        'action_name': 'balanceOf'
    }, {'wallet_key': 'key'}, params)

print(convert_hex_str_to_int(tx_result))
Ejemplo n.º 19
0
def convert_failure_code_to_int(key, value, new_obj):
    if "failure" in new_obj:
        new_obj[key]["code"] = convert_hex_str_to_int(value["code"])