def call(conf):
        """Request icx_call

        :param conf: call command configuration.
        :return: response of icx_call
        """
        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        with open(conf['json_file'], 'r') as jf:
            payload = json.load(jf)

        call = CallBuilder()\
            .from_(conf['from'])\
            .to(payload['params']['to'])\
            .method(payload['params']['data']['method'])\
            .params(payload['params']['data'].get('params', None))\
            .build()

        response = call_with_logger(icon_service, call, uri)

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

        return response
    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.º 3
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.º 4
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.º 5
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'])
Ejemplo n.º 6
0
    def __init__(self):
        self.handlers = [
            self._set_revision,
            self._update_governance_score,
            self._set_step_cost,
        ]
        self.revision = 0
        self.gs_version = "0.0.0"

        self.key_wallet = KeyWallet.load(bytes.fromhex(TEST1_PRIVATE_KEY))
        self.preps = []
        for prep in self.PREPS:
            self.preps.append(KeyWallet.load(prep))
        uri, version = uri_parser("http://127.0.0.1:9000/api/v3")
        self.icon_service = IconService(HTTPProvider(uri, version))
    def lastblock(self, conf):
        """Query last block

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

        response = icon_service.get_block("latest", True)

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

        return response
    def scoreapi(self, conf):
        """Query score API of given score address.

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

        response = icon_service.get_score_api(conf['address'], True)

        if "error" in response:
            print('Got an error response')
            print(f"Can not get {conf['address']}'s API\n{json.dumps(response, indent=4)}")
        else:
            print(f"SCORE API: {json.dumps(response['result'], indent=4)}")

        return response
    def totalsupply(conf: dict):
        """Query total supply of ICX

        :param conf: totalsupply command configuration
        """
        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        response = icon_service.get_total_supply(True)

        if "error" in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print(f'Total supply of ICX in hex: {response["result"]}')
            print(f'Total supply of ICX in decimal: {int(response["result"], 16)}')

        return response
    def balance(self, conf: dict):
        """Query icx balance of given address

        :param conf: balance command configuration.
        """
        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        response = icon_service.get_balance(conf['address'], True)

        if "error" in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print(f"balance in hex: {response['result']}")
            print(f"balance in decimal: {int(response['result'], 16)}")

        return response
    def txresult(self, conf):
        """Query transaction result using given transaction hash.

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

        response = icon_service.get_transaction_result(conf['hash'], True)

        if "error" in response:
            print('Got an error response')
            print(f"Can not get transaction \n{json.dumps(response, indent=4)}")
        else:
            print(f"Transaction : {json.dumps(response, indent=4)}")

        return response
    def blockbyhash(self, conf):
        """Query block with given hash

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

        response = icon_service.get_block(conf['hash'], 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.º 13
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