def transfer(self, conf: 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: transfer = IconJsonrpc.from_key_store(conf['keyStore'], password) else: transfer = IconJsonrpc.from_string(conf['from']) # make JSON-RPC 2.0 request standard format(dict type) request = transfer.sendTransaction(to=conf['to'], value=hex(int(conf['value'])), nid=conf['nid']) # request to rpcserver icon_client = IconClient(conf['uri']) response = icon_client.send(request=request) 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
def test_sendTransaction_v2(self): # IconJsonrpc object from string addr = f'hx{"0"*40}' from_str = IconJsonrpc.from_string(addr) # IconJsonrpc object from keystore file key_store = os.path.join(TEST_UTIL_DIRECTORY, 'test_keystore') password = '******' from_keystore = IconJsonrpc.from_key_store(keystore=key_store, password=password) # IconJsonrpc object from private key from_private_key = IconJsonrpc.from_private_key() icon_jsonrpc_objs = [from_str, from_keystore, from_private_key] request_template = { "to": f'hx{"a"*40}', "value": hex(int(1e10)), "fee": hex(int(1e16)), "nonce": hex(1), "timestamp": hex(int(time.time() * 10**6)) } # test transfer for obj in icon_jsonrpc_objs: self.check_sendTransaction_v2(obj, request_template)
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'] content_type = "application/zip" # make zip and convert to hexadecimal string data (start with 0x) and return content = IconJsonrpc.gen_deploy_data_content(conf['project']) # make IconJsonrpc instance which is used for making request (with signature) if conf['keyStore']: deploy = IconJsonrpc.from_key_store(keystore=conf['keyStore'], password=password) else: deploy = IconJsonrpc.from_string(from_=conf['from']) uri = conf['uri'] step_limit = conf.get('stepLimit', None) # make JSON-RPC 2.0 request standard format request = deploy.sendTransaction(to=score_address, nid=conf['nid'], step_limit=step_limit, data_type="deploy", data=IconJsonrpc.gen_deploy_data( params=conf.get( 'scoreParams', {}), content_type=content_type, content=content)) if step_limit is None: step_limit = get_enough_step(request, uri) request['params']['stepLimit'] = hex(step_limit) deploy.put_signature(request['params']) # send request to the rpc server icon_client = IconClient(uri) response = icon_client.send(request) 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
def test_gen_deploy_data_content(self): content = IconJsonrpc.gen_deploy_data_content(TEST_UTIL_DIRECTORY) self.assertEqual(content[:2], '0x') # invalid path self.assertRaises(ValueError, IconJsonrpc.gen_deploy_data_content, "Wrong_path")
def test_gen_call_data(self): data = { "method": "transfer", "params": { "to": "hxto", "value": int(1e18) } } gen_data = IconJsonrpc.gen_call_data(method=data['method'], params=data['params']) self.assertEqual(data, gen_data) # check default params gen_data = IconJsonrpc.gen_call_data(method=data['method']) self.assertEqual(data['method'], gen_data['method']) self.assertEqual({}, gen_data['params'])
def test_from_private_key_bytes(self): byte_data = f'{"0"*32}'.encode() private_key_object = PrivateKey(byte_data) from_private_key = IconJsonrpc.from_private_key( private_key_object.private_key) self.assertTrue(from_private_key.signer) self.assertTrue(from_private_key.address)
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) if password: sendtx = IconJsonrpc.from_key_store(conf['keyStore'], password) params = payload['params'] jsonrpc_params_to_pep_style(params) payload = sendtx.sendTransaction(**params) icon_client = IconClient(conf['uri']) response = icon_client.send(request=payload) 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
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) if password: sendtx = IconJsonrpc.from_key_store(conf['keyStore'], password) else: sendtx = IconJsonrpc.from_string(payload['params']['from']) params = payload['params'] params['from'] = None jsonrpc_params_to_pep_style(params) payload = sendtx.sendTransaction(**params) uri = conf['uri'] step_limit = payload['params']['stepLimit'] if step_limit is None: step_limit = conf.get('stepLimit', None) if step_limit is None: step_limit = get_enough_step(payload, uri) else: step_limit = int(step_limit, 16) payload['params']['stepLimit'] = hex(step_limit) sendtx.put_signature(payload['params']) # send request to the rpc server icon_client = IconClient(uri) response = icon_client.send(request=payload) 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
def test_from_key_store(self): key_store = os.path.join(TEST_UTIL_DIRECTORY, 'test_keystore') password = '******' from_keystore = IconJsonrpc.from_key_store(keystore=key_store, password=password) self.assertTrue(from_keystore.signer) self.assertEqual('hxef73db5d0ad02eb1fadb37d0041be96bfa56d4e6', from_keystore.address)
def test_call(self): # IconJsonrpc object from string addr = f'hx{"0"*40}' from_str = IconJsonrpc.from_string(addr) # IconJsonrpc object from keystore file key_store = os.path.join(TEST_UTIL_DIRECTORY, 'test_keystore') password = '******' from_keystore = IconJsonrpc.from_key_store(keystore=key_store, password=password) # IconJsonrpc object from private key from_private_key = IconJsonrpc.from_private_key() to_addr = f'hx{"a"*40}' call_data = { "method": "transfer", "params": { "to": "hxto", "value": "0x10" } } # with IconJsonrpc object from string request = from_str.call(to=to_addr, data=call_data) self.check_jsonschema_validation(request=request) self.assertEqual(from_str.address, request['params']['from']) self.assertEqual(to_addr, request['params']['to']) self.assertEqual('call', request['params']['dataType']) self.assertEqual(call_data, request['params']['data']) # with IconJsonrpc object from keystore request = from_keystore.call(to=to_addr, data=call_data) self.check_jsonschema_validation(request=request) self.assertEqual(from_keystore.address, request['params']['from']) self.assertEqual(to_addr, request['params']['to']) self.assertEqual('call', request['params']['dataType']) self.assertEqual(call_data, request['params']['data']) # with IconJsonrpc object from private_key request = from_private_key.call(to=to_addr, data=call_data) self.check_jsonschema_validation(request=request) self.assertEqual(from_private_key.address, request['params']['from']) self.assertEqual(to_addr, request['params']['to']) self.assertEqual('call', request['params']['dataType']) self.assertEqual(call_data, request['params']['data'])
def test_gen_deploy_data(self): data = { "contentType": "contentType", "content": "content", "params": { "initialSuppliy": 0x10000, "decimals": 18 } } gen_data = IconJsonrpc.gen_deploy_data( content=data['content'], content_type=data['contentType'], params=data['params']) self.assertEqual(data, gen_data) # check default values gen_data = IconJsonrpc.gen_deploy_data(content=data['content']) self.assertEqual(data['content'], gen_data['content']) self.assertEqual("application/zip", gen_data['contentType']) self.assertEqual({}, gen_data['params'])
def balance(self, conf: dict): """Query icx balance of given address :param conf: balance command configuration. """ icon_client = IconClient(conf['uri']) response = icon_client.send(IconJsonrpc.getBalance(conf['address'])) 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 lastblock(self, conf): """Query last block :param conf: lastblock command configuration :return: result of query """ icon_client = IconClient(conf['uri']) response = icon_client.send(IconJsonrpc.getLastBlock()) if "error" in response: print(json.dumps(response, indent=4)) else: print(f'block info : {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 """ icon_client = IconClient(conf['uri']) response = icon_client.send(IconJsonrpc.getBlockByHash(conf['hash'])) 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
def scoreapi(self, conf): """Query score API of given score address. :param conf: scoreapi command configuration. :return: result of query. """ icon_client = IconClient(conf['uri']) response = icon_client.send(IconJsonrpc.getScoreApi(conf['address'])) 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 txbyhash(self, conf): """Query transaction using given transaction hash. :param conf: txbyhash command configuration. :return: result of query. """ icon_client = IconClient(conf['uri']) response = icon_client.send( IconJsonrpc.getTransactionByHash(conf['hash'])) 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 totalsupply(conf: dict): """Query total supply of ICX :param conf: totalsupply command configuration """ icon_client = IconClient(conf['uri']) response = icon_client.send(IconJsonrpc.getTotalSupply()) 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 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'] icon_jsonrpc = IconJsonrpc.from_string(from_addr) icon_client = IconClient( f'http://127.0.0.1:{start_conf["port"]}/api/v3') to_addr = f'hx{"d"*40}' timestamp = hex(int(time.time() * 10**6)) # send transaction request = icon_jsonrpc.sendTransaction(to=to_addr, timestamp=timestamp, step_limit='0x100000') response = icon_client.send(request) self.assertTrue('result' in response) # send again response = icon_client.send(request) self.assertTrue('error' in response) self.assertEqual( responseCodeMap[Response.fail_tx_invalid_duplicated_hash][1], response['error']['message'])
def test_getBlockByHeight(self): request = IconJsonrpc.getBlockByHeight("2") self.check_jsonschema_validation(request=request) request = IconJsonrpc.getBlockByHeight("0x2") self.check_jsonschema_validation(request=request)
def deploy(self, conf: dict) -> dict: """Deploy SCORE on the server. :param conf: deploy command configuration """ if conf['contentType'] == 'tbears' and not CommandServer.is_service_running( ): raise TBearsCommandException(f'Start tbears service first') # check keystore, and get password from user's terminal input password = conf.get('password', None) password = self._check_deploy(conf, password) step_limit = conf.get('stepLimit', "0x1234000") if conf['mode'] == 'install': score_address = f'cx{"0"*40}' else: score_address = conf['to'] if conf['contentType'] == 'zip': content_type = "application/zip" # make zip and convert to hexadecimal string data(start with 0x) and return content = IconJsonrpc.gen_deploy_data_content(conf['project']) else: content_type = "application/tbears" content = os.path.abspath(conf['project']) # make IconJsonrpc instance which is used for making request(with signature) if conf['keyStore']: deploy = IconJsonrpc.from_key_store(keystore=conf['keyStore'], password=password) else: deploy = IconJsonrpc.from_string(from_=conf['from']) # make JSON-RPC 2.0 request standard format request = deploy.sendTransaction(to=score_address, nid=conf['nid'], step_limit=step_limit, data_type="deploy", data=IconJsonrpc.gen_deploy_data( params=conf.get( 'scoreParams', {}), content_type=content_type, content=content)) # send request to rpcserver icon_client = IconClient(conf['uri']) response = icon_client.send(request) 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
def test_getLastBlock(self): request = IconJsonrpc.getLastBlock() self.check_jsonschema_validation(request=request)
def test_getBalance(self): addr = f'hx{"0"*40}' request = IconJsonrpc.getBalance(address=addr) self.check_jsonschema_validation(request=request)
def test_from_private_key(self): from_private_key = IconJsonrpc.from_private_key() self.assertTrue(from_private_key.signer) self.assertTrue(from_private_key.address)
def test_from_string(self): addr = f'hx{"0"*40}' from_str = IconJsonrpc.from_string(addr) self.assertFalse(from_str.signer) self.assertEqual(addr, from_str.address)
def test_ScoreApi(self): addr = f'cx{"0"*40}' request = IconJsonrpc.getScoreApi(score_address=addr) self.check_jsonschema_validation(request=request)
def test_sendTransaction(self): # IconJsonrpc object from string addr = f'hx{"0"*40}' from_str = IconJsonrpc.from_string(addr) # IconJsonrpc object from keystore file key_store = os.path.join(TEST_UTIL_DIRECTORY, 'test_keystore') password = '******' from_keystore = IconJsonrpc.from_key_store(keystore=key_store, password=password) # IconJsonrpc object from private key from_private_key = IconJsonrpc.from_private_key() icon_jsonrpc_objs = [from_str, from_keystore, from_private_key] request_template = { "to": f'hx{"a"*40}', "version": hex(3), "value": hex(int(1e10)), "stepLimit": hex(0x2000), "nid": hex(3), "nonce": hex(1), "timestamp": hex(int(time.time() * 10**6)) } """ test transfer """ for obj in icon_jsonrpc_objs: self.check_sendTransaction(obj, request_template) """ test dataType 'call' """ request_template["dataType"] = 'call' request_template["data"] = { "method": "transfer", "params": { "to": "hxto", "value": hex(0x10) } } for obj in icon_jsonrpc_objs: self.check_sendTransaction(obj, request_template) """ test dataType 'deploy' """ request_template["dataType"] = 'deploy' request_template["data"] = { "contentType": "application/zip", "content": "0xcontent", "params": { "on_install": "need_param?", "on_update": "need_param?", } } for obj in icon_jsonrpc_objs: self.check_sendTransaction(obj, request_template) """ test dataType 'message' """ request_template["dataType"] = 'message' request_template["data"] = "0xmessage" for obj in icon_jsonrpc_objs: self.check_sendTransaction(obj, request_template)
def test_getTransactionByHash(self): txHash = '0x43de4f25a41cb8cd09b0478300ce8da24191f1602e54b6db2ce6274311556164' request = IconJsonrpc.getTransactionByHash(txHash) self.check_jsonschema_validation(request=request)
def test_getTotalSupply(self): request = IconJsonrpc.getTotalSupply() self.check_jsonschema_validation(request=request)