Example #1
0
    def process_call(self, call: Call, network: IconService = None):
        if self._network_only and network is None:
            raise URLException("Set network URL")

        try:
            if network is not None:
                response = network.call(call)
            else:
                request = {
                    "from": Address.from_string(call.from_),
                    "to": Address.from_string(call.to),
                    "dataType": "call",
                    "data": {
                        "method": call.method
                    }
                }

                if isinstance(call.params, dict):
                    request["data"]["params"] = call.params

                response = self._query(request=request)
        except IconServiceBaseException as e:
            response = e.message

        return response
Example #2
0
    def json_rpc_call(self, method_name, params):
        icon_service = IconService(HTTPProvider(DashboardRPCCalls.MAIN_NET))
        call_builder = CallBuilder() \
            .to(self._to_contract) \
            .method(method_name) \
            .params(params) \
            .build()

        response = icon_service.call(call_builder)

        return response
Example #3
0
    def show_game_room_list(self):

        _icon_service = IconService(
            HTTPProvider("https://bicon.net.solidwallet.io/api/v3"))
        _ = CallBuilder().from_(self._keywallet_address) \
            .to(self._sample_game_score_address) \
            .method("showGameRoomList") \
            .build()

        response = _icon_service.call(_)

        return response
class TestGetterMethods(unittest.TestCase):
    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))

    def tearDown(self):
        pass

    def test_name(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("name")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'HelloWorld')

    def test_hello(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("hello")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'Hello')
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))
class IconNetwork:
    def __init__(self, endpoint, network_id):
        self.endpoint = endpoint
        self.network_id = network_id
        self.icon_service = IconService(HTTPProvider(endpoint, network_id))

    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)

    def deploy_contract(self, contract_info, account_info):
        wallet = KeyWallet.load(bytes.fromhex(account_info['wallet_key']))
        contract_content_bytes = gen_deploy_data_content(
            contract_info['contract_file'])

        deploy_transaction = DeployTransactionBuilder() \
          .from_(wallet.get_address()) \
          .to(SCORE_INSTALL_ADDRESS) \
          .step_limit(self.get_max_step_limit(wallet.get_address())) \
          .nid(self.network_id) \
          .nonce(self.network_id) \
          .content_type('application/zip') \
          .content(contract_content_bytes) \
          .params(contract_info['params']) \
          .version(self.network_id) \
          .build()

        signed_transaction = SignedTransaction(deploy_transaction, wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)
        # print('tx_hash:', tx_hash)

        tx_result = self.get_transaction_result(tx_hash)
        return tx_result

    def get_transaction_result(self, tx_hash):
        max_retries = 10
        retry_count = 0
        sleep_seconds = 5
        tx_result = None

        while retry_count < max_retries:
            tx_result = self.get_transaction_result_once(tx_hash)

            if None != tx_result:
                retry_count = max_retries
            else:
                retry_count += 1
                # print('Retrying {0} in {1} seconds'.format(retry_count, sleep_seconds))
                time.sleep(sleep_seconds)

        # tx_result might be still None if all retries failed.
        return tx_result

    def get_transaction_result_once(self, tx_hash):
        try:
            tx_result = self.icon_service.get_transaction_result(tx_hash)
            # print('tx_result:', tx_result)
            return tx_result
        except:
            error = sys.exc_info()
            # print('get_transaction_result error:', error[1])
            return None

    def read_data(self, contract_address, table_name, wallet_key, params):
        wallet = KeyWallet.load(bytes.fromhex(wallet_key))

        call_data = CallBuilder() \
          .from_(wallet.get_address()) \
          .to(contract_address) \
          .method('get' + table_name) \
          .params(params) \
          .build()

        result = self.icon_service.call(call_data)
        return result

    def write_data(self, contract_address, action_name, wallet_key, params):
        wallet = KeyWallet.load(bytes.fromhex(wallet_key))

        call_transaction = CallTransactionBuilder() \
          .from_(wallet.get_address()) \
          .to(contract_address) \
          .step_limit(self.get_max_step_limit(wallet.get_address())) \
          .nid(self.network_id) \
          .nonce(self.network_id) \
          .method(action_name) \
          .params(params) \
          .build()

        signed_transaction = SignedTransaction(call_transaction, wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)
        # print('tx_hash:', tx_hash)

        tx_result = self.get_transaction_result(tx_hash)
        return tx_result

    def create_data(self, contract_address, table_name, wallet_key, data):
        return self.write_data(contract_address, 'cre' + table_name,
                               wallet_key, data)

    def update_data(self, contract_address, table_name, wallet_key, data):
        return self.write_data(contract_address, 'upd' + table_name,
                               wallet_key, data)

    def delete_data(self, contract_address, table_name, wallet_key, data):
        return self.write_data(contract_address, 'del' + table_name,
                               wallet_key, data)
Example #7
0
class Sync:
    PREPS = TEST_ACCOUNTS[:4]

    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 apply(self):
        # get status
        response = self._get_revision()
        self.revision = int(response.get("code", "0x0"), 16)

        # start sync
        for i, action in enumerate(sync_list):
            print("")
            type_: int = action.get("type", -1)
            params = action.get("params", {})
            self.handlers[type_](params)

    @staticmethod
    def archive():
        root = "./"
        with tarfile.open('mainnet.tar.gz', 'w:gz') as tar:
            for dir in [".score", ".statedb"]:
                for _, _, files in os.walk(os.path.join(root, dir)):
                    for f in files:
                        tar.add(os.path.join(root, dir, f), arcname=f)

    def _is_network_proposal_enabled(self):
        return self.revision >= Revision.DECENTRALIZATION.value and self.gs_version >= "1.0.0"

    def _set_revision(self, params: dict):
        revision = int(params.get('code'), 16)
        print(f"## Set revision {revision}")
        if self.revision > revision:
            print(f"pass revision {revision}. {revision} < {self.revision}")
            return

        if not self._is_network_proposal_enabled():
            # send setRevision TX
            tx_hash = self._call_tx(key_wallet=self.key_wallet,
                                    to=GOVERNANCE_ADDRESS,
                                    method='setRevision',
                                    params=params)
            print(f"transaction hash: {tx_hash}")
        else:
            # register setRevision network proposal and approve it
            register = self.preps[0]
            np_id = self._register_proposal_tx(
                key_wallet=register,
                title=f"set revision {revision}",
                desc=f"T-Bears set revision {revision}",
                type=1,
                value_dict=params)
            for prep in self.preps:
                if prep == register:
                    continue
                tx_hash = self._vote_proposal_tx(key_wallet=prep,
                                                 id_=np_id,
                                                 vote=1)
                debug_print(
                    f"{prep.get_address()} votes agree to {np_id}. transaction hash: {tx_hash}"
                )

            print(f"Network proposal ID: {np_id}")

        self.revision = revision

        if self.revision == Revision.IISS.value:
            # make 4 P-Reps for network proposal
            self._make_preps(self.preps)

        if self.revision == Revision.DECENTRALIZATION.value:
            response = self._call(to=SYSTEM_ADDRESS, method="getIISSInfo")
            block_height = int(response.get("blockHeight"), 16)
            next_calc = int(response.get("nextCalculation"), 16)
            wait_time = (next_calc - block_height) * 2
            print(f"Wait decentralization..... {wait_time} secs")
            sleep(wait_time)
            while True:
                response = self._call(to=SYSTEM_ADDRESS, method="getIISSInfo")
                print(response.get("nextPRepTerm"))
                if response.get("nextPRepTerm", "0x0") != "0x0":
                    print(f"Decentralization is done.")
                    break
                else:
                    sleep(1)

    def _update_governance_score(self, params: dict):
        version = params.get('version')
        print(f"## Update governance SCORE to {version}")

        path = os.path.join(DIR_PATH, f"data/governance_{version}.zip")
        self._deploy_score(key_wallet=self.key_wallet,
                           score_address=GOVERNANCE_ADDRESS,
                           path=path)

        self.gs_version = version

    def _set_step_cost(self, params: dict):
        step_type = params.get('stepType')
        cost = params.get('cost')
        print(f"## Set stepCost.{step_type} to {cost}")
        if not self._is_network_proposal_enabled():
            # send setStepCost TX
            tx_hash = self._call_tx(key_wallet=self.key_wallet,
                                    to=GOVERNANCE_ADDRESS,
                                    method='setStepCost',
                                    params=params)
            print(f"transaction hash: {tx_hash}")
        else:
            # TODO send setStepCost network proposal and approve it
            print(f"Network proposal : ID")

    def _deploy_score(
        self,
        key_wallet: 'KeyWallet',
        path: str,
        score_address: str = SYSTEM_ADDRESS,
    ) -> dict:
        # Generates an instance of transaction for deploying SCORE.
        transaction = DeployTransactionBuilder() \
            .from_(key_wallet.get_address()) \
            .to(score_address) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(path)) \
            .build()

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

        # send transaction
        return self.icon_service.send_transaction(signed_transaction)

    def _call(self,
              to: str,
              method: str,
              params: dict = {}) -> Union[dict, str]:
        call = CallBuilder() \
            .from_(self.key_wallet.get_address()) \
            .to(to) \
            .method(method) \
            .params(params) \
            .build()

        return self.icon_service.call(call)

    def _tx(self,
            key_wallet: 'KeyWallet',
            to: str,
            value: int = 0,
            step_limit: int = DEFAULT_STEP_LIMIT,
            nid: int = DEFAULT_NID,
            nonce: int = 0) -> str:
        transaction = TransactionBuilder() \
            .from_(key_wallet.get_address()) \
            .to(to) \
            .value(value) \
            .step_limit(step_limit) \
            .nid(nid) \
            .nonce(nonce) \
            .build()

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

        # Send transaction
        return self.icon_service.send_transaction(signed_transaction)

    def _call_tx(self,
                 key_wallet: 'KeyWallet',
                 to: str,
                 method: str,
                 params: dict = {},
                 value: int = 0,
                 step_limit: int = DEFAULT_STEP_LIMIT,
                 nid: int = DEFAULT_NID,
                 nonce: int = 0) -> str:
        transaction = CallTransactionBuilder() \
            .from_(key_wallet.get_address()) \
            .to(to) \
            .value(value) \
            .step_limit(step_limit) \
            .nid(nid) \
            .nonce(nonce) \
            .method(method) \
            .params(params) \
            .build()

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

        # Send transaction
        return self.icon_service.send_transaction(signed_transaction)

    def _get_revision(self) -> dict:
        try:
            return self._call(to=GOVERNANCE_ADDRESS, method="getRevision")
        except JSONRPCException:
            return {"code": "0x0", "name": "0.0.0"}

    def _register_proposal_tx(self,
                              key_wallet: 'KeyWallet',
                              title: str,
                              desc: str,
                              type: int,
                              value_dict: dict,
                              value: int = 0,
                              step_limit: int = DEFAULT_STEP_LIMIT,
                              nid: int = DEFAULT_NID,
                              nonce: int = 0) -> str:
        params = {
            "title": title,
            "description": desc,
            "type": hex(type),
            "value": "0x" + bytes.hex(json.dumps(value_dict).encode())
        }
        return self._call_tx(key_wallet=key_wallet,
                             to=GOVERNANCE_ADDRESS,
                             method="registerProposal",
                             params=params,
                             value=value,
                             step_limit=step_limit,
                             nid=nid,
                             nonce=nonce)

    def _vote_proposal_tx(self,
                          key_wallet: 'KeyWallet',
                          id_: str,
                          vote: int,
                          value: int = 0,
                          step_limit: int = DEFAULT_STEP_LIMIT,
                          nid: int = DEFAULT_NID,
                          nonce: int = 0) -> 'str':
        params = {"id": id_, "vote": hex(vote)}

        return self._call_tx(key_wallet=key_wallet,
                             to=GOVERNANCE_ADDRESS,
                             method="voteProposal",
                             params=params,
                             value=value,
                             step_limit=step_limit,
                             nid=nid,
                             nonce=nonce)

    def _make_preps(self, preps: List[KeyWallet]):
        print(f"#### make P-Reps")
        delegate_value = self.icon_service.get_total_supply() * 2 // 1000
        transfer_value = delegate_value + 3000 * ICX
        for prep in preps:
            # transfer ICX
            tx_hash = self._tx(key_wallet=self.key_wallet,
                               to=prep.get_address(),
                               value=transfer_value)
            debug_print(
                f"transfer {transfer_value} to {prep.get_address()} tx_hash: {tx_hash}"
            )
        while True:
            sleep(1)
            balance = self.icon_service.get_balance(preps[0].get_address())
            if balance >= transfer_value:
                break

        for prep in preps:
            # register P-Rep
            name = f"node{prep.get_address()}"
            params = {
                ConstantKeys.NAME: name,
                ConstantKeys.COUNTRY: "KOR",
                ConstantKeys.CITY: "Unknown",
                ConstantKeys.EMAIL: f"{name}@example.com",
                ConstantKeys.WEBSITE: f"https://{name}.example.com",
                ConstantKeys.DETAILS: f"https://{name}.example.com/details",
                ConstantKeys.P2P_ENDPOINT: f"{name}.example.com:7100",
            }
            tx_hash = self._call_tx(key_wallet=prep,
                                    to=SYSTEM_ADDRESS,
                                    value=2000 * ICX,
                                    method="registerPRep",
                                    params=params)
            debug_print(f"register {prep.get_address()} tx_hash: {tx_hash}")

            # stake
            tx_hash = self._call_tx(key_wallet=prep,
                                    to=SYSTEM_ADDRESS,
                                    method="setStake",
                                    params={"value": hex(delegate_value)})
            debug_print(f"set stake {prep.get_address()} tx_hash: {tx_hash}")
            # delegate
            tx_hash = self._call_tx(key_wallet=prep,
                                    to=SYSTEM_ADDRESS,
                                    method="setDelegation",
                                    params={
                                        "delegations": [{
                                            "address":
                                            prep.get_address(),
                                            "value":
                                            hex(delegate_value)
                                        }]
                                    })
            debug_print(f"delegate {prep.get_address()} tx_hash: {tx_hash}")

        while True:
            sleep(1)
            response = self._call(to=SYSTEM_ADDRESS, method="getPReps")
            if len(response.get("preps", 0)) > 0:
                print(f"make 4 P-Reps")
                for prep in preps:
                    address = prep.get_address()
                    resp = self._call(to=SYSTEM_ADDRESS,
                                      method="getPRep",
                                      params={"address": address})
                    print(
                        f" - {address}, delegated: {int(resp.get('delegated'), 16)//ICX:,} ICX"
                    )
                print(self._call(to=SYSTEM_ADDRESS, method="getIISSInfo"))
                break

    def check_revision(self) -> int:
        current_revision = int(self._get_revision().get("code"), 16)
        latest_revision = self._get_latest_revision()

        return current_revision - latest_revision

    @staticmethod
    def _get_latest_revision() -> int:
        for cmd in reversed(sync_list):
            if cmd.get("type") == SyncType.REVISION:
                return int(cmd["params"]["code"], 16)
        return 0
Example #8
0
class TestGetterMethods(unittest.TestCase):

    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))
 
    def tearDown(self):
        pass 


    def test_name(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("name")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'HelloWorld')


    def test_hello(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("hello")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'Hello')


    def test_send_token_to_ca(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(token_address)\
                    .method("balanceOf")\
                    .params({"_owner": hello_world_address})\
                    .build()
        balance_before = self.icon_service.call(call)
        token_value = "0x1"
        
        transaction = CallTransactionBuilder()\
            .from_(self.tester_addr)\
            .to(token_address)\
            .step_limit(2000000)\
            .nid(network_id)\
            .method("transfer")\
            .params({"_to":hello_world_address, "_value":token_value})\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.call(call)
        self.assertEqual(int(balance_before,0)+int(token_value,0), int(balance_after,0))


    def test_send_icx_to_ca(self):
        balance_before = self.icon_service.get_balance(hello_world_address)
        icx_value = 1

        transaction = TransactionBuilder()\
            .from_(self.tester_addr)\
            .to(hello_world_address)\
            .value(icx_value)\
            .step_limit(2000000)\
            .nid(network_id)\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.get_balance(hello_world_address)
        self.assertEqual(balance_before+icx_value, balance_after)
Example #9
0
class ServiceManager:
    def __init__(self, node_conf_path: str, wallet_path: str, passwd: str):

        # Node configuration to be connected
        with open(node_conf_path, "r") as f:
            node_conf = json.load(f)

        self._my_chain_name = node_conf["chain_name"]
        self._nid = int(node_conf["nid"], 16)

        self.web_protocol = node_conf["web_protocol"]

        if self.web_protocol == "ssl":
            self._icon_service = IconService(
                HTTPProvider("https://" + node_conf["address"], 3))
            self._ws_block = f"wss://{node_conf['address']}/api/ws/{node_conf['channel']}"
        elif self.web_protocol == "http":
            self._icon_service = IconService(
                HTTPProvider("http://" + node_conf["address"], 3))
            self._ws_block = f"ws://{node_conf['address']}/api/node/{node_conf['channel']}"
        else:
            print("[error] Not supported web_protocol")
            sys.exit()

        # Set wallet of actor
        self._wallet = KeyWallet.load(wallet_path, passwd)

        self._score_info = node_conf["scores"]

    # TODO 실제로는 없어도 되는 method
    def get_block(self, value=None) -> dict:
        block = self._icon_service.get_block(value)
        return block

    def get_rep_list(self):
        resp = self.query("cx0000000000000000000000000000000000000000",
                          "getPRepTerm", {})
        preps_info = resp["preps"]
        preps_list = []
        for item in preps_info:
            preps_list.append(item["address"])

        return preps_list

    def get_rep_list_local(self):
        node_info = f"http://localhost:9100/api/node"

        headers = {"content-type": "application/json"}
        body = {"jsonrpc": "2.0", "method": "node_getChannelInfos", "id": 1234}
        resp = requests.post(node_info, data=json.dumps(body),
                             headers=headers).json()

        assert resp["jsonrpc"]
        assert resp["id"]

        preps_list = []
        for item in resp["result"]["channel_infos"]["icon_dex"]["peers"]:
            preps_list.append(item["id"])

        return preps_list

    def get_tx_result_by_hash(self, tx_hash: str) -> dict:
        tx_result = self._icon_service.get_transaction_result(tx_hash)
        for key, value in tx_result.items():
            if isinstance(value, int):
                tx_result[key] = hex(value)

        try:
            tx_result["logsBloom"] = "0x" + tx_result["logsBloom"].hex()
        except KeyError:
            pass
        return tx_result

    def call_tx(self, score_addr: str, method: str, params: dict) -> dict:
        transaction = CallTransactionBuilder() \
            .from_(self._wallet.get_address()) \
            .to(score_addr) \
            .step_limit(STEP_LIMIT) \
            .nid(self._nid) \
            .nonce(NONCE) \
            .method(method) \
            .params(params) \
            .build()
        return self._send_transaction(transaction)

    def query(self, score_addr: str, method: str, params: dict):
        query = CallBuilder() \
            .from_(self._wallet.get_address()) \
            .to(score_addr) \
            .method(method) \
            .params(params) \
            .build()
        return self._icon_service.call(query)

    def dummy_tx_send(self, loop: int):
        for i in range(loop):
            transaction = CallTransactionBuilder().\
                from_(self._wallet.get_address()).\
                to(self._wallet.get_address()).\
                step_limit(STEP_LIMIT).\
                value(1).\
                nid(self.nid).\
                nonce(NONCE).\
                method("transfer").build()

            signed_tx = SignedTransaction(transaction, self._wallet)
            tx_hash = self.icon_service.send_transaction(signed_tx)
            print(f"[dc_log] dummy tx hash: {tx_hash}")

    def _send_transaction(self, transaction) -> dict:
        signed_tx = SignedTransaction(transaction, self._wallet)
        tx_hash = self._icon_service.send_transaction(signed_tx)

        sleep(SLEEP_TIMER)
        return self.get_tx_result_by_hash(tx_hash)

    @staticmethod
    def print_result(data: dict):

        print(
            "----------------------------------------------------------------------------------"
        )
        print("<Tx_result>")
        print(f" -    txHash: {data['txHash']}")
        print(f" -    height: {data['blockHeight']}")
        print(f" - blockHash: {data['blockHash']}")
        try:
            print(f" - scoreAddr: {data['scoreAddress']}")
        except KeyError:
            pass
        print(f" -  stepUsed: {data['stepUsed']}")
        print(f" -    status: {data['status']}")
        print(
            "----------------------------------------------------------------------------------\n\n"
        )

    @property
    def ws_addr(self):
        return self._ws_block

    @property
    def chain_name(self):
        return self._my_chain_name

    @property
    def nid(self):
        return self._nid

    @property
    def from_account(self):
        return self._wallet.get_address()

    @property
    def icon_service(self):
        return self._icon_service
Example #10
0
class TestUcBase(unittest.TestCase):
    _scoreAddrOfContractRegistry = ''
    _scoreAddrOfStoreAgentProxy = ''
    _scoreAddrOfOrderAgentProxy = ''
    _scoreAddrOfStoreAgent = ''
    _scoreAddrOfOrderAgent = ''

    @classmethod
    def setUpClass(self):
        self._currentDirPath = path.abspath(path.dirname(__file__))
        self._walletOfTest1 = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_TEST1}',
            'test1_Account')
        self._walletOfUc = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_UC}',
            TEST_KEYSTORE_PW)
        self._walletOfProvider = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_PROVIDER}',
            TEST_KEYSTORE_PW)
        self._walletOfCustomer = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_CUSTOMER}',
            TEST_KEYSTORE_PW)
        self._iconService = IconService(
            HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))

    def setUp(self):
        self._scoreAddrOfContractRegistry = self.__class__._scoreAddrOfContractRegistry
        self._scoreAddrOfOrderAgentProxy = self.__class__._scoreAddrOfOrderAgentProxy
        self._scoreAddrOfStoreAgentProxy = self.__class__._scoreAddrOfStoreAgentProxy
        self._scoreAddrOfOrderAgent = self.__class__._scoreAddrOfOrderAgent
        self._scoreAddrOfStoreAgent = self.__class__._scoreAddrOfStoreAgent

    def _deploy(self, _installContentBytes: bytes, _params: object) -> str:
        transaction = DeployTransactionBuilder()\
            .from_(self._walletOfUc.get_address())\
            .to('cx0000000000000000000000000000000000000000')\
            .step_limit(1000000000)\
            .nid(3)\
            .nonce(100)\
            .content_type('application/zip')\
            .content(_installContentBytes)\
            .params(_params)\
            .build()

        signedTransaction = SignedTransaction(transaction, self._walletOfUc)
        txHash = self._iconService.send_transaction(signedTransaction)

        scoreAddr = ''
        for i in range(1, 11):
            sleep(1)
            try:
                txResult = self._iconService.get_transaction_result(txHash)
            except:
                continue
            else:
                break

        self.assertNotEqual(txResult, None)
        scoreAddr = txResult['scoreAddress']
        self.assertNotEqual(scoreAddr, '')
        return scoreAddr

    def _sendTransaction(self, _transaction: object,
                         _wallet: object) -> object:
        signedTransaction = SignedTransaction(_transaction, _wallet)
        txHash = self._iconService.send_transaction(signedTransaction)

        txResult = None
        for i in range(1, 11):
            sleep(1)
            try:
                txResult = self._iconService.get_transaction_result(txHash)
            except:
                continue
            else:
                break

        self.assertNotEqual(txResult, None)
        self.assertEqual(txResult['status'], 0x1)
        return txResult

    def _sendCall(self, _call: object) -> object:
        return self._iconService.call(_call)

    def _getBalance(self, _owner: str) -> int:
        return self._iconService.get_balance(_owner)
Example #11
0
class TestGetterMethods(unittest.TestCase):

    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))
 
    def tearDown(self):
        pass 


    def test_name(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("name")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'HelloWorld')


    def test_hello(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("hello")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'Hello')


    def test_send_token_to_ca(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(token_address)\
                    .method("balanceOf")\
                    .params({"_owner": hello_world_address})\
                    .build()
        balance_before = self.icon_service.call(call)
        token_value = "0x1"
        
        transaction = CallTransactionBuilder()\
            .from_(self.tester_addr)\
            .to(token_address)\
            .step_limit(2000000)\
            .nid(network_id)\
            .method("transfer")\
            .params({"_to":hello_world_address, "_value":token_value})\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.call(call)
        self.assertEqual(int(balance_before,0)+int(token_value,0), int(balance_after,0))


    def test_send_icx_to_ca(self):
        balance_before = self.icon_service.get_balance(hello_world_address)
        icx_value = 1

        transaction = TransactionBuilder()\
            .from_(self.tester_addr)\
            .to(hello_world_address)\
            .value(icx_value)\
            .step_limit(2000000)\
            .nid(network_id)\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.get_balance(hello_world_address)
        self.assertEqual(balance_before+icx_value, balance_after)
Example #12
0
def main():
    cmd_args = sys.argv[1:]
    parser = get_parser()

    args = vars(parser.parse_args(cmd_args))
    command = args.get('command')
    url = args.get('url')
    step_limit = int(args.get('stepLimit', 0))
    nid = int(args.get('nid', 0))
    icon_service = IconService(HTTPProvider(url))

    try:
        if command == 'register':
            wallet = get_wallet(args)
            json_path = args.get('json')
            with open(json_path, mode='r') as prep_info:
                reg_info = json.load(prep_info)
            public_key = wallet.bytes_public_key
            reg_info['publicKey'] = f"0x{public_key.hex()}"

            register_fee: int = 2000 * 10 ** 18
            tx = CallTransactionBuilder(). \
                from_(wallet.get_address()). \
                to(ZERO_ADDRESS). \
                step_limit(step_limit). \
                value(register_fee). \
                nid(nid). \
                nonce(100). \
                method("registerPRep"). \
                params(reg_info). \
                build()
            signed_data = SignedTransaction(tx, wallet)
            result = icon_service.send_transaction(signed_data)
        elif command == 'unregister':
            wallet = get_wallet(args)
            params = {}
            if args.get('address'):
                params['address'] = args['address']
            tx = CallTransactionBuilder().from_(wallet.get_address()).to(ZERO_ADDRESS). \
                step_limit(step_limit).nid(nid).nonce(100).method("unregisterPRep").\
                params(params).value(0).build()
            signed_data = SignedTransaction(tx, wallet)
            result = icon_service.send_transaction(signed_data)
        elif command == 'preps':
            json_path = args.get('json')
            if json_path is not None:
                with open(json_path, mode='r') as prep_info:
                    params = json.load(prep_info)
            else:
                params = {}
            call_data = CallBuilder(from_=f"hx{'0'*40}", to=ZERO_ADDRESS,
                                    method="getPReps").params(params).build()
            result = icon_service.call(call_data)
        else:
            print('unknown command')
            sys.exit(2)
        print('result : ', result)
        return 0
    except BaseException as e:
        print(e)
        sys.exit(3)
class TestTest(IconIntegrateTestBase):
    TEST_HTTP_ENDPOINT_URI_V3 = "https://zicon.net.solidwallet.io/api/v3"
    #Address of recently deployed contract


    def setUp(self):
        super().setUp()
        self.contracts = {}
        self.contracts['sicx1'] = "cx20fa65cffc720db31e78fba6db5d58f58babd933"
        self.contracts['staking1'] = "cx25c39ed0d27853e44af8ab2739d6af832f35d533"
        self.contracts['staking2'] = "cx8b250e76bc919f73068571c26cadecde69e63b46"
        self.contracts['staking3'] = "cx3502e9af253098d187578ca826fe71032f116e47"
        # WARNING: ICON service emulation is not working with IISS.
        # You can stake and delegate but can't get any I-Score for reward.
        # If you want to test IISS stuff correctly, set self.icon_service and send requests to the network
        self.icon_service = IconService(HTTPProvider(self.TEST_HTTP_ENDPOINT_URI_V3))
        private2="093f12dba9dc75da81ecafc88de73ef9b311b555939aeb5a875dc6ad8feef424"
        private3="167f6ec1694ab63243efdce98f6f6bfdcef0575cefbb86ffe3826f8373f12b85"
        self._test2 = KeyWallet.load(bytes.fromhex(private2))
        self._test3 = KeyWallet.load(bytes.fromhex(private3))

        #
        # If you want to send requests to the network, uncomment next line and set self.TEST_HTTP_ENDPOINT_URI_V3



    @retry(JSONRPCException, tries=10, delay=1, back_off=2)
    def _get_tx_result(self,_tx_hash):
        tx_result = self.icon_service.get_transaction_result(_tx_hash)
        return tx_result

    # Sends the call request
    @retry(JSONRPCException, tries=10, delay=1, back_off=2)
    def get_tx_result(self,_call):
        tx_result = self.icon_service.call(_call)
        return tx_result

    def test_add_collateral(self):
        print('======================================================================')
        print('Test Add Collateral')
        print('----------------------------------------------------------------------')
        settings = [
                    #{'name': 'Sending 30 ICX from test_account1', 'from' : self._test1.get_address(),'value':25 * 10 ** 18, 'params' : {'_to': self._test1.get_address()},'sign':self._test1},
                    #{'name': 'Sending 80 ICX from test_account1', 'from' : self._test1.get_address(),'value':40 * 10 ** 18, 'params' : {'_to': self._test1.get_address()},'sign': self._test1},
                    {'name': 'Sending 15 ICX from test_account2', 'from' : self._test2.get_address(),'value':15 * 10 ** 18, 'params' : {'_to': self._test2.get_address()},'sign': self._test2}
                    # {'name': 'Sending 15 ICX from test_account2', 'from' : self._test3.get_address(),'value':15 * 10 ** 18, 'params' : {'_to': self._test3.get_address()},'sign': self._test3}
                     ]

        for sett in settings:
            print('======================================================================')
            print(sett['name'])
            print('----------------------------------------------------------------------')

            transaction = CallTransactionBuilder() \
            .from_(sett['from']) \
            .to(self.contracts['staking1']) \
            .value (sett['value']) \
            .step_limit(10000000) \
            .nid(80) \
            .nonce(100) \
            .method('addCollateral') \
            .params(sett['params']) \
            .build()
            # Returns the signed transaction object having a signature
            signed_transaction = SignedTransaction(transaction, sett['sign'])

            # process the transaction in zicon
            tx_hash = self.icon_service.send_transaction(signed_transaction)
            _tx_result= self._get_tx_result(tx_hash)
             #check Transaction result
            print (_tx_result)
            self.assertTrue('status' in _tx_result)
            self.assertEqual(True, _tx_result['status'])
            # contract_delegation_call = CallBuilder().from_(sett['from']) \
            #     .to(self.contracts['staking1']) \
            #     .method("getDelegationFromNetwork") \
            #     .build()
            # response_delegation_contract = self.get_tx_result(contract_delegation_call)
            # print('----------------------------------------------------------------------')
            # print('Delegation List from Network')
            # print('----------------------------------------------------------------------')
            # delegation_from_contract = {}
            # #Iterating through contract delegations
            # for i in response_delegation_contract["delegations"]:
            #     delegation_from_contract[i['address']] = i['value']
            # print(delegation_from_contract)
            # check call result
            # if sett['name'] == 'Test Case 1.3':
            #     self.assertEqual(response_delegation,delegation_from_contract)

    # def test_update_delegation(self):
    #     print('======================================================================')
    #     print(' *******************Test Update Delegations***************************')
    #     print('----------------------------------------------------------------------')
    #     settings = [{'name': 'Test Case 1.1', 'wAddress':'staking3', 'params' : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.1', 'wAddress':'staking1', "params" : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "5"},{'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "10"},
    #                                                               {'_address': 'hxbdc3baae0632fad453d62130d3379900a323f5b4',  '_votes_in_per' : "15"}]}},
    #                 {'name': 'Test Case 2.2', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hxc89dfd4bf903b39ca98db905443ca9020f955e8c',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.3', 'wAddress':'staking1', 'params' : {}},
    #                 {'name': 'Test Case 2.4', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx4917005bf4b8188b9591da520fc1c6dab8fe717f',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx9a24e7a53e031ab6aa7b831b1dbe4200bd3f9483',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.5', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx8573a132f3df5c34a292fc16cb33737ffe10b367',  '_votes_in_per' : "40"},{'_address': 'hx6bd3a3b1390e99194ced786725e0f0725fc1960b',  '_votes_in_per' : "15"},
    #                                                               {'_address': 'hx7cc2bb9d84ff3b5843f83d07818ebcff31be29e5',  '_votes_in_per' : "45"}]}},
    #                 {'name': 'Test Case 2.6', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx2d058aa34a76b2039e7cc59f18633aabd272d89f',  '_votes_in_per' : "100"}]}},
    #                 ]
    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         call_transaction = CallTransactionBuilder() \
    #             .from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .nid(80) \
    #             .step_limit(10000000) \
    #             .nonce(100) \
    #             .method('updateDelegations') \
    #             .params(sett['params']) \
    #             .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(call_transaction, self._test1)
    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         if sett['name'] == 'Test Case 1.1' or sett['name'] == 'Test Case 2.1' or sett['name'] == 'Test Case 2.2' or sett['name'] == 'Test Case 2.3':
    #             self.assertEqual(_tx_result,_tx_result)
    #         else:
    #             self.assertTrue('status' in _tx_result)
    #             self.assertEqual(True, _tx_result['status'])
    #             delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getPrepDelegations") \
    #                 .build()

    #             contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getDelegationFromNetwork") \
    #                 .build()
    #             response_delegation = self.get_tx_result(delegation_call)
    #             response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List')
    #             print('----------------------------------------------------------------------')
    #             print (response_delegation)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List from Network')
    #             print('----------------------------------------------------------------------')
    #             delegation_from_contract = {}
    #             #Iterating through contract delegations
    #             for i in response_delegation_contract["delegations"]:
    #                 delegation_from_contract[i['address']] = i['value']
    #             print(delegation_from_contract)

    # def test_wclaim_iscore(self):
    #     print('======================================================================')
    #     print(' **********************Test Claim IScore*****************************')
    #     print('----------------------------------------------------------------------')

    #     transaction = CallTransactionBuilder() \
    #         .from_(self._test1.get_address()) \
    #         .to(self.contracts['staking1']) \
    #         .step_limit(10000000) \
    #         .nid(80) \
    #         .nonce(100) \
    #         .method('_claim_iscore') \
    #         .build()
    #     # # Returns the signed transaction object having a signature
    #     signed_transaction = SignedTransaction(transaction, self._test1)

    #     # # process the transaction in zicon
    #     tx_hash = self.icon_service.send_transaction(signed_transaction)
    #     _tx_result= self._get_tx_result(tx_hash)
    #     print (_tx_result)
    #     # #check Transaction result
    #     self.assertTrue('status' in _tx_result)
    #     self.assertEqual(True, _tx_result['status'])


    #     contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #         .to(self.contracts['staking1']) \
    #         .method("getLifetimeReward") \
    #         .build()
    #     response_delegation_contract = self.get_tx_result(contract_delegation_call)

    #     print('----------------------------------------------------------------------')
    #     print('Delegation List from Network')
    #     print('----------------------------------------------------------------------')
    #     delegation_from_contract = {}
    #     # #Iterating through contract delegations
    #     # for i in response_delegation_contract["delegations"]:
    #     #     delegation_from_contract[i['address']] = i['value']
    #     # print(delegation_from_contract)
    #     print(response_delegation_contract)


    # def test_tr(self):
    #     print('======================================================================')
    #     print(' *******************Test Update Delegations***************************')
    #     print('----------------------------------------------------------------------')
    #     settings = [{'name': 'Test Case 1.1', 'wAddress':'staking3', 'params' : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.1', 'wAddress':'staking1', "params" : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "5"},{'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "10"},
    #                                                               {'_address': 'hxbdc3baae0632fad453d62130d3379900a323f5b4',  '_votes_in_per' : "15"}]}},
    #                 {'name': 'Test Case 2.2', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hxc89dfd4bf903b39ca98db905443ca9020f955e8c',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.3', 'wAddress':'staking1', 'params' : {}},
    #                 {'name': 'Test Case 2.4', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx4917005bf4b8188b9591da520fc1c6dab8fe717f',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx9a24e7a53e031ab6aa7b831b1dbe4200bd3f9483',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.5', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx8573a132f3df5c34a292fc16cb33737ffe10b367',  '_votes_in_per' : "40"},{'_address': 'hx6bd3a3b1390e99194ced786725e0f0725fc1960b',  '_votes_in_per' : "15"},
    #                                                               {'_address': 'hx7cc2bb9d84ff3b5843f83d07818ebcff31be29e5',  '_votes_in_per' : "45"}]}},
    #                 {'name': 'Test Case 2.6', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx23dfce82d36268f4cc3b943fa65d4c9632d23e76',  '_votes_in_per' : "100"}]}},
    #                 ]
    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         call_transaction = CallTransactionBuilder() \
    #             .from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .nid(80) \
    #             .step_limit(10000000) \
    #             .nonce(100) \
    #             .method('updateDelegations') \
    #             .params(sett['params']) \
    #             .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(call_transaction, self._test1)
    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         if sett['name'] == 'Test Case 1.1' or sett['name'] == 'Test Case 2.1' or sett['name'] == 'Test Case 2.2' or sett['name'] == 'Test Case 2.3':
    #             self.assertEqual(_tx_result,_tx_result)
    #         else:
    #             self.assertTrue('status' in _tx_result)
    #             self.assertEqual(True, _tx_result['status'])
    #             delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getPrepDelegations") \
    #                 .build()

    #             contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getDelegationFromNetwork") \
    #                 .build()
    #             response_delegation = self.get_tx_result(delegation_call)
    #             response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List')
    #             print('----------------------------------------------------------------------')
    #             print (response_delegation)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List from Network')
    #             print('----------------------------------------------------------------------')
    #             delegation_from_contract = {}
    #             #Iterating through contract delegations
    #             for i in response_delegation_contract["delegations"]:
    #                 delegation_from_contract[i['address']] = i['value']
    #             print(delegation_from_contract)



    # def test_unstake(self):
    #     print('======================================================================')
    #     print('Test Unstake')
    #     print('----------------------------------------------------------------------')
    #     data = "{\"method\": \"unstake\"}".encode("utf-8")
    #     settings = [
    #                 # {'name': 'Test Case 1.1', 'from' : self._test1.get_address(), 'wAddress':'sicx1', 'params' : {'_to': self.contracts['staking1'],'_value': 20 * 10**18,'_data':data},'sign': self._test1,'delegation_address':'staking1'},
    #                 {'name': 'Test Case 1.2', 'from' : self._test2.get_address(), 'wAddress':'sicx1', 'params' : {'_to': self.contracts['staking1'], '_value': 20 * 10**18,'_data':data},'sign': self._test2,'delegation_address':'staking1'},
    #                 ]

    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         transaction = CallTransactionBuilder() \
    #         .from_(sett['from']) \
    #         .to(self.contracts[sett['wAddress']]) \
    #         .step_limit(10000000) \
    #         .nid(80) \
    #         .nonce(100) \
    #         .method('transfer') \
    #         .params(sett['params']) \
    #         .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(transaction, sett['sign'])

    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         self.assertTrue('status' in _tx_result)
    #         self.assertEqual(True, _tx_result['status'])
    #     # Address =[self._test1.get_address(),self._test2.get_address()]
    #     # for test in Address:
    #     #     contract_delegation_call = CallBuilder().from_(test) \
    #     #         .to(self.contracts[sett['delegation_address']]) \
    #     #         .method("getDelegationFromNetwork") \
    #     #         .build()
    #     #     response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #     #     print('----------------------------------------------------------------------')
    #     #     print('Delegation List from Network')
    #     #     print('----------------------------------------------------------------------')
    #     #     delegation_from_contract = {}
    #     #     #Iterating through contract delegations
    #     #     for i in response_delegation_contract["delegations"]:
    #     #         delegation_from_contract[i['address']] = i['value']
    #     #     print(delegation_from_contract)
    #     # check call result
    #     # if sett['name'] == 'Test Case 1.3':
    #     #     self.assertEqual(response_delegation,delegation_from_contract)


    # def test_send_ICX(self):
    #     print('======================================================================')
    #     print('Test Send ICX')
    #     print('----------------------------------------------------------------------')
    #     settings = [
    #                 {'name': 'Test Case 1.1', 'from' : self._test1.get_address(), 'wAddress':'staking1', 'params' : {'_to': self._test2.get_address(),'_value': 800 }}
    #                 ]
    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         call_transaction = CallTransactionBuilder() \
    #             .from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .nid(80) \
    #             .step_limit(10000000) \
    #             .nonce(100) \
    #             .method('_send_ICX') \
    #             .params(sett['params']) \
    #             .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(call_transaction, self._test1)
    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         self.assertTrue('status' in _tx_result)
    #         self.assertEqual(True, _tx_result['status'])
    #         delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .method("getPrepDelegations") \
    #             .build()

    #         contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .method("getDelegationFromNetwork") \
    #             .build()
    #         response_delegation = self.get_tx_result(delegation_call)
    #         response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #         print('----------------------------------------------------------------------')
    #         print('Delegation List')
    #         print('----------------------------------------------------------------------')
    #         print (response_delegation)
    #         print('----------------------------------------------------------------------')
    #         print('Delegation List from Network')
    #         print('----------------------------------------------------------------------')
    #         delegation_from_contract = {}
    #         #Iterating through contract delegations
    #         for i in response_delegation_contract["delegations"]:
    #             delegation_from_contract[i['address']] = i['value']
    #         print(delegation_from_contract)
    



    def test_lifeTime(self):
        print('======================================================================')
        print('getLifetimeReward')
        print('----------------------------------------------------------------------')

        _call = CallBuilder().from_(self._test1.get_address()) \
            .to(self.contracts['staking1']) \
            .method("getLifetimeReward") \
            .build()

        response = self.get_tx_result(_call)
        # check call result
        print (response)
        

    def test_getRate(self):
        print('======================================================================')
        print('Test getRate ')
        print('----------------------------------------------------------------------')

        _call = CallBuilder().from_(self._test1.get_address()) \
            .to(self.contracts['staking1']) \
            .method("getRate") \
            .build()

        response = self.get_tx_result(_call)
        # check call result
        print (response)
        

    def test_getTodayRate(self):
        print('======================================================================')
        print('Test getTodayRate')
        print('----------------------------------------------------------------------')

        _call = CallBuilder().from_(self._test1.get_address()) \
            .to(self.contracts['staking1']) \
            .method("getTodayRate") \
            .build()

        response = self.get_tx_result(_call)
        # check call result
        print (response)
Example #14
0
class TestGetterMethods(unittest.TestCase):

    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))

    def test_vote_list(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(vote_dao_address)\
                    .method("vote_list")\
                    .build()
        self.icon_service.call(call)

    def test_add_user(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("add_user") \
            .params({"contents": "hx8d29ac2645805452a6e921c888b23c58be862cf0"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def test_remove_user(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("remove_user") \
            .params({"contents": "hx8d29ac2645805452a6e921c888b23c58be862cf0"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def test_ox(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("ox") \
            .params({"contents": "tests"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def vote(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("vote") \
            .params({"code": "O0","vote_res": "2"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def delete(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("delete") \
            .params({"code": "O0"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1
Example #15
0
class RPCmanager(object):
    def __init__(self, _conf_rpc: dict) -> None:
        # Key Wallet with Password
        self.key_wallet = KeyWallet.load(_conf_rpc["KeyWallet"]["File"],
                                         _conf_rpc["KeyWallet"]["Password"])
        # Service Endpoint (URL)
        self.service_endpoint = IconService(
            HTTPProvider(_conf_rpc["Service Endpoint"]))
        # Smart Contract Address
        self.id_contract_address = _conf_rpc["ID Contract Address"]
        self.ptm_contract_address = _conf_rpc["PTM Contract Address"]
        self.pgm_contract_address = _conf_rpc["PGM Contract Address"]
        # Network ID
        self.nid = int(_conf_rpc["Network ID"])

    def getMethod(self, _method: dict, type: str) -> str:
        if type == "DIR":
            contract_address = self.id_contract_address
        elif type == "PTM":
            contract_address = self.ptm_contract_address
        elif type == "PGM":
            contract_address = self.pgm_contract_address
        else:
            print("Not supported contract type")
            pass

        call = CallBuilder() \
            .from_(self.key_wallet.get_address()) \
            .to(contract_address) \
            .method(_method["name"]) \
            .params(_method["params"]) \
            .build()

        result = self.service_endpoint.call(call)
        print(result)

        return result

    def setMethod(self, _method: dict, type: str) -> dict:
        result = {}
        if type == "DIR":
            contract_address = self.id_contract_address
        elif type == "PTM":
            contract_address = self.ptm_contract_address
        elif type == "PGM":
            contract_address = self.pgm_contract_address
        else:
            print("Not supported contract type")
            result["status"] = "failure"
            result["message"] = ""
            return result

        if not _method.__contains__("params"):
            _method["params"] = ""

        transaction = CallTransactionBuilder() \
            .from_(self.key_wallet.get_address()) \
            .to(contract_address) \
            .step_limit(10000000) \
            .nid(self.nid) \
            .method(_method["name"]) \
            .params(_method["params"]) \
            .build()

        # sign the transaction with key wallet
        signed_tx = SignedTransaction(transaction, self.key_wallet)
        # commit(send) the signed transaction to the service endpoint
        tx_hash = self.service_endpoint.send_transaction(signed_tx)
        sleep(3)  # wait a second for the transaction to be finalized
        tx_result = self.service_endpoint.get_transaction_result(tx_hash)
        print(tx_result)

        if "failure" in tx_result:
            result["status"] = "failure"
            result["message"] = tx_result["failure"]
        else:
            result["status"] = "success"
            result["message"] = tx_result["eventLogs"][0]["data"]

        return result