def test_wallet_load_and_call_api(self):
        """Case when loading a wallet and call an api."""
        # Loads a wallet.
        wallet = KeyWallet.load(self.TEST_KEYSTORE_FILE_DIR,
                                self.TEST_KEYSTORE_FILE_PASSWORD)

        # Checks a wallet's address is correct.
        self.assertEqual(wallet.get_address(),
                         "hxfd7e4560ba363f5aabd32caac7317feeee70ea57")

        # Calls an api.
        icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
        balance = icon_service.get_balance(wallet.get_address())
        self.assertEqual(balance, 0)
コード例 #2
0
    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 test_wallet_load_and_call_api(self, _make_id):
        """Case when loading a wallet and call an api."""
        # Loads a wallet.
        wallet = KeyWallet.load(self.TEST_KEYSTORE_FILE_PATH,
                                self.TEST_KEYSTORE_FILE_PASSWORD)

        # Checks a wallet's address is correct.
        self.assertEqual(wallet.get_address(),
                         "hxfd7e4560ba363f5aabd32caac7317feeee70ea57")

        # Calls an api.
        icon_service = IconService(
            HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST, VERSION_FOR_TEST))
        with requests_mock.Mocker() as m:
            response_json = {"jsonrpc": "2.0", "result": hex(0), "id": 1234}
            m.post(self.matcher, json=response_json)
            balance = icon_service.get_balance(wallet.get_address())
            self.assertEqual(balance, 0)
コード例 #4
0
ファイル: utils.py プロジェクト: ICONationTeam/ICONSafe-SCORE
def get_icx_balance(icon_integrate_test_base: IconIntegrateTestBase,
                    address: str,
                    icon_service: IconService = None) -> int:
    """Gets ICX coin balance of address

    :param icon_integrate_test_base: IconIntegrateTestBase
    :param address: target address
    :param icon_service: IconService
    :return: ICX coin balance of target address
    """
    try:
        if icon_service is not None:
            response = icon_service.get_balance(address)
        else:
            request = {"address": Address.from_string(address)}
            response = icon_integrate_test_base._query(request=request,
                                                       method="icx_getBalance")
    except IconServiceBaseException as e:
        response = e.message

    # Sends the call request
    return int(response, 16)
コード例 #5
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
コード例 #6
0
ファイル: test.py プロジェクト: MarkShim7972/iconlab4
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)
コード例 #7
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)
コード例 #8
0
from iconsdk.wallet.wallet import KeyWallet
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.builder.call_builder import CallBuilder
from iconsdk.exception import JSONRPCException
from util.repeater import retry

icon_service = IconService(HTTPProvider("http://localhost:9001/api/v3"))
DIR_PATH = os.path.abspath(os.path.dirname(__file__))
SCORE_PROJECT = os.path.abspath(os.path.join(DIR_PATH, './welcome'))
wallet = KeyWallet.load("./keystore_test1", "test1_Account")

print("address: ", wallet.get_address())  # Returns an address
print("private key: ", wallet.get_private_key())  # Returns a private key
print(
    "balance: ",
    icon_service.get_balance(
        "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb"))  # Returns a private key


@retry(JSONRPCException, tries=10, delay=1, back_off=2)
def get_tx_result() -> str:
    tx_result = icon_service.get_transaction_result(tx_hash)
    print("waiting a second for accepting score...\n")
    return tx_result["scoreAddress"]


@retry(JSONRPCException, tries=10, delay=1, back_off=2)
def get_tx(tx_hash) -> str:
    tx_result = icon_service.get_transaction_result(tx_hash)
    print("waiting a second for accepting score...\n")
    return tx_result
コード例 #9
0
class test_CPS_Score(IconIntegrateTestBase):
    TEST_HTTP_ENDPOINT_URI_V3 = "http://127.0.0.1:9000/api/v3"
    CPS_SCORE_PROJECT = os.path.abspath((os.path.join(DIR_PATH, '..',
                                                      'cps_score')))
    CPF_TREASURY_PROJECT = os.path.abspath(
        (os.path.join(DIR_PATH, '..', 'CPFTreasury')))
    CPS_TREASURY_PROJECT = os.path.abspath(
        (os.path.join(DIR_PATH, '..', 'CPSTreasury')))
    BLOCK_INTERVAL = 6

    def setUp(self):
        super().setUp()
        self.icon_service = IconService(
            HTTPProvider(self.TEST_HTTP_ENDPOINT_URI_V3))
        print(self.icon_service)

        self.system_score = SCORE_INSTALL_ADDRESS
        self.contracts = {
            'baln': 'cx95da4b04e9bd7d6a92b186a1f122278576d34234',
            'bnUSD': 'cx493bae75aaa45227a8af156be09d8ed93090f4b0',
            'bwt': 'cx4166435d4410a960356024fbe303019c70e4cce5',
            'cpf_treasury': 'cxc16ef2ea8ec9599a1f2320df2c4323fd5e965dee',
            'cps_score': 'cx459122f0fa9b93b1eb00753eb57238a91a913e69',
            'cps_treasury': 'cxedf06f84738d44fedc56bc4cf76da47796776794',
            'daofund': 'cx705c8734a68bad1ae4bd1c5779048ca30d0c19d2',
            'dex': 'cx2ffafb2e5fb3b37c144c2780edef2148c9cebabf',
            'dividends': 'cxe33d4af72ef2dfd02c0c93db837a6f2116bd0e46',
            'governance': 'cx821f5c5c83770f0b07b21b927fe3ccd7c26e149b',
            'loans': 'cx9b0045a9cb9fe06dcf9a7c718e41a2396860edaa',
            'oracle': 'cxb44659ae1cfd1198aad4a44397a38bdd0fbf6745',
            'reserve': 'cx9fca7c94f66d136fa3e40a15aafed8a706777342',
            'rewards': 'cx6325ee7aaf3025eb311ef240eb6b380e0642175c',
            'sicx': 'cx0a7905aad9687952f0073038751e48e57485d103',
            'staking': 'cx9d7a0d5beecba73cefa4f08b3a591f78b52a5294',
            'system': 'cx0000000000000000000000000000000000000000'
        }

        pprint(self.contracts)
        self._wallet_setup()
        # self._register_100_preps()

    def _deploy_cps_score(self,
                          to: str = SCORE_INSTALL_ADDRESS,
                          params=None) -> dict:
        if params is None:
            params = {}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPS_SCORE_PROJECT)) \
            .params(params) \
            .build()

        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def test_update_scores(self):
        score_list = ['cps_score', 'cpf_treasury', 'cps_treasury']
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self.contracts[score_list[0]]) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPS_SCORE_PROJECT)) \
            .build()

        signed_transaction = SignedTransaction(transaction, self._test1)

        tx_hash = self.process_transaction(signed_transaction,
                                           self.icon_service)
        pprint(tx_hash)

    def _deploy_cpf_treasury_score(self,
                                   to: str = SCORE_INSTALL_ADDRESS,
                                   params=None) -> dict:
        if params is None:
            params = {'amount': 1_000_000 * 10**18}

        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPF_TREASURY_PROJECT)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def _deploy_cps_treasury_score(self,
                                   to: str = SCORE_INSTALL_ADDRESS,
                                   params=None) -> dict:
        if params is None:
            params = {}

        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPS_TREASURY_PROJECT)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def _register_100_preps(self, start=10, end=20):
        txs = []
        for i in range(start, end):
            len_str = str(start)
            if len(len_str) == 2:
                j = "0" + str(i)
            else:
                j = str(i)
            params = {
                "name":
                "Test P-rep " + str(i),
                "country":
                "KOR",
                "city":
                "Unknown",
                "email":
                "nodehx9eec61296a7010c867ce24c20e69588e28321" + j +
                "@example.com",
                "website":
                'https://nodehx9eec61296a7010c867ce24c20e69588e28321' + j +
                '.example.com',
                "details":
                'https'
                '://nodehx9eec61296a7010c867ce24c20e69588e28321' + j +
                '.example.com/details',
                "p2pEndpoint":
                "nodehx9eec61296a7010c867ce24c20e69588e28321" + j +
                ".example.com:7100",
                "nodeAddress":
                "hx9eec61296a7010c867ce24c20e69588e28321" + j
            }
            self.send_icx(self._test1, self._wallet_array[i].get_address(),
                          3000000000000000000000)
            print(params["nodeAddress"])
            txs.append(
                self.build_tx(self._wallet_array[i],
                              "cx0000000000000000000000000000000000000000",
                              2000000000000000000000, "registerPRep", params))
        ab = self.process_transaction_bulk(txs, self.icon_service, 10)
        pprint(ab)

    def send_icx(self, from_: KeyWallet, to: str, value: int):
        previous_to_balance = self.get_balance(to)
        previous_from_balance = self.get_balance(from_.get_address())

        signed_icx_transaction = self.build_send_icx(from_, to, value)
        tx_result = self.process_transaction(signed_icx_transaction,
                                             self.icon_service,
                                             self.BLOCK_INTERVAL)

        fee = tx_result['stepPrice'] * tx_result['cumulativeStepUsed']
        self.assertTrue('status' in tx_result)
        self.assertEqual(
            1, tx_result['status'], f"Failure: {tx_result['failure']}"
            if tx_result['status'] == 0 else "")
        self.assertEqual(previous_to_balance + value, self.get_balance(to))
        self.assertEqual(previous_from_balance - value - fee,
                         self.get_balance(from_.get_address()))

    def get_balance(self, address: str) -> int:
        if self.icon_service is not None:
            return self.icon_service.get_balance(address)
        params = {'address': Address.from_string(address)}
        response = self.icon_service_engine.query(method="icx_getBalance",
                                                  params=params)
        return response

    def build_send_icx(self, from_: KeyWallet, to: str,
                       value: int) -> SignedTransaction:
        send_icx_transaction = TransactionBuilder(from_=from_.get_address(),
                                                  to=to,
                                                  value=value,
                                                  step_limit=1000000,
                                                  nid=3,
                                                  nonce=3).build()
        signed_icx_transaction = SignedTransaction(send_icx_transaction, from_)
        return signed_icx_transaction

    def send_tx(self,
                from_: KeyWallet,
                to: str,
                value: int = 0,
                method: str = None,
                params: dict = None) -> dict:
        signed_transaction = self.build_tx(from_, to, value, method, params)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service,
                                             self.BLOCK_INTERVAL)
        # ab = tx_result
        # print(ab)
        step_price = tx_result['stepPrice']
        step_used = tx_result['stepUsed']
        # print(step_used)
        # print(step_price)
        print("The tx fee is ....")
        print((step_price * step_used) / 10**18)
        pprint(tx_result)
        self.assertTrue('status' in tx_result)
        self.assertEqual(
            1, tx_result['status'], f"Failure: {tx_result['failure']}"
            if tx_result['status'] == 0 else "")
        return tx_result

    def build_tx(self, from_: KeyWallet, to: str, value: int, method: str = None, params: dict = None) \
            -> SignedTransaction:

        params = {} if params is None else params
        tx = CallTransactionBuilder(from_=from_.get_address(),
                                    to=to,
                                    value=value,
                                    step_limit=3_000_000_000,
                                    nid=3,
                                    nonce=5,
                                    method=method,
                                    params=params).build()
        signed_transaction = SignedTransaction(tx, from_)
        return signed_transaction

    def call_tx(self, _score, params, method):
        params = {} if params is None else params
        _call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(_score) \
            .method(method) \
            .params(params) \
            .build()
        response = self.process_call(_call, self.icon_service)
        return response

    def test_register_prep(self):

        pprint(
            self.send_tx(self._wallet_array[10], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[11], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[12], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[13], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[14], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[15], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[16], self.contracts['cps_score'],
                         0, 'register_prep', None))

    def build_transaction(self,
                          from_: KeyWallet,
                          to: str,
                          value: int = 0,
                          method: str = None,
                          params: dict = None) -> dict:
        call_transaction = CallTransactionBuilder() \
            .from_(from_.get_address()) \
            .to(to) \
            .value(value) \
            .nid(3) \
            .nonce(100) \
            .method(method) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(call_transaction, from_,
                                               10000000)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertEqual(tx_result['status'], 1)
        return tx_result

    def test_period_status(self):
        resposne = self.call_tx(self.contracts['cps_score'], None,
                                'get_period_status')
        pprint(resposne)
        pprint(f"remaining time: {int(resposne['remaining_time'], 16)}")

    # def test_register_prep(self):
    #     self._register_prep()

    def test_unregister_prep(self):
        pprint(
            self.send_tx(self._wallet_array[13], self.contracts['cps_score'],
                         0, 'unregister_prep', None))

    def test_get_preps(self):
        response = self.call_tx(self.contracts['cps_score'], None, 'get_PReps')
        pprint(response)

    def test_set_stake(self):
        pprint(
            self.send_tx(self._wallet_array[10],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[11],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[12],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[13],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[14],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[15],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[16],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))

    def test_set_delegation(self):
        pprint(
            self.send_tx(
                self._wallet_array[10],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[10].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[11],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[11].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[12],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[12].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[13],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[13].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[14],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[14].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[15],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[15].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[16],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[16].get_address(),
                        'value': 100
                    }]
                }))

    def _wallet_setup(self):
        self.icx_factor = 10**18
        self.btest_wallet: 'KeyWallet' = self._wallet_array[5]
        self.staking_wallet: 'KeyWallet' = self._wallet_array[6]
        self.user1: 'KeyWallet' = self._wallet_array[7]
        self.user2: 'KeyWallet' = self._wallet_array[8]

    # set addresses in different scores ___________________________________________________________________________________
    # set addresses in cps_score

    def test_set_cps_treasury_cpf_treasury_and_bnUSD_score_in_cps_score(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_cps_treasury_score',
                                    {'_score': self.contracts['cps_treasury']})
        pprint(tx)
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_cpf_treasury_score',
                                    {'_score': self.contracts['cpf_treasury']})
        pprint(tx)
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_bnUSD_score',
                                    {'_score': self.contracts['bnUSD']})
        pprint(tx)

    def test_score_addresses_in_cps_score(self):
        response = self.call_tx(self.contracts['cps_score'], None,
                                'get_cps_treasury_score')
        pprint(response)
        response = self.call_tx(self.contracts['cps_score'], None,
                                'get_cpf_treasury_score')
        pprint(response)
        response = self.call_tx(self.contracts['cps_score'], None,
                                'get_bnUSD_score')
        pprint(response)

    def test_set_cps_score_cpf_treasury_in_cps_treasury_score(self):
        tx = self.build_transaction(self._test1,
                                    self.contracts['cps_treasury'], 0,
                                    'set_cps_score',
                                    {'_score': self.contracts['cps_score']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cps_treasury'], 0,
                                    'set_cpf_treasury_score',
                                    {'_score': self.contracts['cpf_treasury']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cps_treasury'], 0,
                                    'set_bnUSD_score',
                                    {'_score': self.contracts['bnUSD']})
        pprint(tx)

    def test_score_addresses_in_cps_treasury_score(self):
        response = self.call_tx(self.contracts['cps_treasury'], None,
                                'get_cps_score')
        pprint(response)
        response = self.call_tx(self.contracts['cps_treasury'], None,
                                'get_cpf_treasury_score')
        pprint(response)

    def test_set_cps_score_cps_treasury_cpf_treasury_bnUSD_staking_sicx_dex_in_cpf_treasury(
            self):
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_cps_score',
                                    {'_score': self.contracts['cps_score']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_cps_treasury_score',
                                    {'_score': self.contracts['cps_treasury']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_bnUSD_score',
                                    {'_score': self.contracts['bnUSD']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_staking_score',
                                    {'_score': self.contracts['staking']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_sicx_score',
                                    {'_score': self.contracts['sicx']})
        pprint(tx)
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_dex_score',
                                    {'_score': self.contracts['dex']})
        pprint(tx)

    def test_addresses_in_cpf_treasury(self):
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_cps_score')
        pprint(response)
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_cps_treasury_score')
        pprint(response)
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_bnusd_score')
        pprint(response)
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_staking_score')
        pprint(response)
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_sicx_score')
        pprint(response)
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_dex_score')
        pprint(response)

    # Project flow ________________________________________________________________________________________________________

    def test_add_fund_in_cpf_treasury(self):
        tx = self.send_tx(self._test1, self.contracts['cpf_treasury'],
                          20000 * 10**18, 'add_fund', None)
        pprint(tx)

    def test_get_total_funds_in_cpf_treasury(self):
        response = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_total_funds')
        pprint(response)
        print(
            f"ICX: {int(response['ICX'], 16)}, bnUSD: {int(response['bnUSD'], 16)}"
        )

    def test_staking_on(self):
        tx = self.send_tx(self.staking_wallet, self.contracts['staking'], 0,
                          'toggleStakingOn', None)
        pprint(tx)

    # submit proposal _____________________________________________________________________________________________________

    def test_create_bnUSD_market(self):
        tx = self.send_tx(self.btest_wallet, self.contracts['governance'],
                          500 * 10**18, 'createBnusdMarket', None)
        pprint(tx)

    def test_balanceOf(self):
        resposne = self.call_tx(self.contracts['bnUSD'],
                                {'_owner': self.contracts['cpf_treasury']},
                                'balanceOf')
        pprint(int(resposne, 16) / 10**18)

    def test_get_price(self):
        resposne = self.call_tx(self.contracts['dex'], {'_id': 2}, 'getPrice')
        pprint(int(resposne, 16) / 10**18)

    def test_pool_id(self):
        resposne = self.call_tx(
            self.contracts['dex'], {
                '_token1Address': self.contracts['sicx'],
                '_token2Address': self.contracts['bnUSD']
            }, 'getPoolId')
        pprint(int(resposne, 16))

    def test_max_cap_bnusd(self):
        tx = self.build_transaction(self._test1,
                                    self.contracts['cpf_treasury'], 0,
                                    'set_maximum_treasury_fund_bnusd',
                                    {'_value': 10000 * 10**18})
        pprint(tx)
        resposne = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_remaining_swap_amount')
        pprint(resposne)
        print(
            f"maxCap: {int(resposne['maxCap'], 16)}, remainingToSwap: {int(resposne['remainingToSwap'], 16)}"
        )

    def test_set_initial_block(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_initialBlock', None)
        pprint(tx)
        resposne = self.call_tx(self.contracts['cps_score'], None,
                                'get_period_status')
        pprint(resposne)
        pprint(f"remaining time: {int(resposne['remaining_time'], 16)}")

    def test_stake_ICX_from_wallet(self):
        # tx_hash = self.send_tx(self._wallet_array[10], self.contracts['staking'], 10 * 10 ** 18, 'stakeICX', None)
        # pprint(tx_hash)
        tx_hash = self.send_tx(self._wallet_array[11],
                               self.contracts['staking'], 200 * 10**18,
                               'stakeICX', None)
        pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[12], self.contracts['staking'], 10 * 10 ** 18, 'stakeICX', None)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[13], self.contracts['staking'], 10 * 10 ** 18, 'stakeICX', None)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[14], self.contracts['staking'], 10 * 10 ** 18, 'stakeICX', None)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[15], self.contracts['staking'], 10 * 10 ** 18, 'stakeICX', None)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[16], self.contracts['staking'], 10 * 10 ** 18, 'stakeICX', None)
        # pprint(tx_hash)
        # time.sleep(3)

    def test_swap_sicx_with_bnUSD_from_wallet(self):
        to_token = self.contracts['bnUSD']
        _data = json.dumps({
            "method": "_swap",
            "params": {
                "toToken": str(to_token)
            }
        }).encode()
        params = {
            '_to': self.contracts['dex'],
            '_value': 200 * 10**18,
            '_data': _data
        }

        # tx_hash = self.send_tx(self._wallet_array[10], self.contracts['sicx'], 0, 'transfer', params)
        # pprint(tx_hash)
        tx_hash = self.send_tx(self._wallet_array[11], self.contracts['sicx'],
                               0, 'transfer', params)
        pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[12], self.contracts['sicx'], 0, 'transfer', params)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[13], self.contracts['sicx'], 0, 'transfer', params)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[14], self.contracts['sicx'], 0, 'transfer', params)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[15], self.contracts['sicx'], 0, 'transfer', params)
        # pprint(tx_hash)
        # tx_hash = self.send_tx(self._wallet_array[16], self.contracts['sicx'], 0, 'transfer', params)
        # pprint(tx_hash)
        # time.sleep(3)

    def test_balance(self):
        print(
            self.icon_service.get_balance(self.btest_wallet.get_address()) /
            10**18)

    def test_send_icx(self):
        tx = self.send_icx(self.btest_wallet, self.contracts['bnUSD'],
                           1000 * 10**18)
        pprint(tx)

    def test_bnUSD_balance(self):
        resposne = self.call_tx(
            self.contracts['bnUSD'],
            {'_owner': self._wallet_array[11].get_address()}, 'balanceOf')
        print(int(resposne, 16) / 10**18)

    def test_get_sicx_balance(self):
        resposne = self.call_tx(
            self.contracts['sicx'],
            {'_owner': self._wallet_array[11].get_address()}, 'balanceOf')
        print(int(resposne, 16) / 10**18)

    def test_set_next_block(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_nextBlock', {'_block': 200})
        pprint(tx)

    def test_set_reduce_block(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_reduce_block', {'_block': 646581})
        pprint(tx)

    def test_toogle_maintenence_mode(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'toggle_maintenance', None)
        pprint(tx)

    def test_submit_proposal(self):
        params = {
            "_proposals": {
                "project_title": "METRICX COMICS",
                "total_budget": 10,
                "sponsor_address":
                "hx094a8b5324f86c340e1023ab5bba73d4fd58a122",
                "ipfs_hash": "Proposal 1 bnUSD",
                "ipfs_link": "https://gateway.ipfs.io/ipfs/Proposal",
                "project_duration": 1,
                "token": "bnUSD"
            }
        }
        print(params['_proposals']['sponsor_address'])
        tx_hash = self.send_tx(self.btest_wallet, self.contracts['cps_score'],
                               50 * 10**18, 'submit_proposal', params)
        pprint(tx_hash)

    def test_sponsor_vote(self):
        _data = json.dumps({
            'method': 'sponsor_vote',
            'params': {
                'ipfs_hash': 'Proposal 1 bnUSD',
                'vote': '_accept',
                'vote_reason': 'Vote Reason'
            }
        })
        print(_data)
        params = {
            '_to': self.contracts['cps_score'],
            '_value': 1 * 10**18,
            '_data': _data.encode()
        }
        tx_hash = self.send_tx(self._wallet_array[11], self.contracts['bnUSD'],
                               0, 'transfer', params)
        pprint(tx_hash)

    def test_get_proposals_details_by_hash(self):
        resposne = self.call_tx(self.contracts['cps_score'],
                                {'_ipfs_key': 'Proposal 1 bnUSD'},
                                'get_proposal_details_by_hash')
        pprint(resposne)

    def test_get_proposals_details_by_status(self):
        resposne = self.call_tx(self.contracts['cps_score'],
                                {'_ipfs_key': 'ProposalTest'},
                                'get_proposal_details_by_hash')
        pprint(resposne)

    def test_remaining_time_in_application_period(self):
        resposne = self.call_tx(self.contracts['cps_score'], None,
                                'get_period_status')
        pprint(resposne)
        pprint(f"remaining time: {int(resposne['remaining_time'], 16)}")

    def test_set_next_block_1(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_nextBlock', {'_block': 200})
        pprint(tx)

    def test_update_period(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'update_period', None)
        pprint(tx)

    def test_vote_proposal(self):
        for i in range(7):
            tx_hash = self.send_tx(
                self._wallet_array[10 + i], self.contracts['cps_score'], 0,
                'vote_proposal', {
                    '_ipfs_key': 'Proposal 1 bnUSD',
                    '_vote': APPROVE,
                    '_vote_reason': 'Good addition to the platform',
                    '_vote_change': False
                })
            pprint(tx_hash)
            time.sleep(2)

    def test_remaining_time_in_voting_period(self):
        resposne = self.call_tx(self.contracts['cps_score'], None,
                                'get_period_status')
        pprint(resposne)
        pprint(f"remaining time: {int(resposne['remaining_time'], 16)}")

    def test_update_period_after_voting(self):
        tx = self.send_tx(self._test1, self.contracts['cps_score'], 0,
                          'update_period', None)
        pprint(tx)
        time.sleep(15)
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'update_period', None)
        pprint(tx)
        time.sleep(15)
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'update_period', None)
        pprint(tx)
        time.sleep(15)
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'update_period', None)
        pprint(tx)
        time.sleep(15)

    def test_submit_progress_report(self):
        params = {
            '_progress_report': {
                'ipfs_hash': 'Proposal 1 bnUSD',
                'report_hash': 'Report 1 bnUSD',
                'ipfs_link': 'https://gateway.ipfs.io/ipfs/Proposal',
                'progress_report_title': 'Progress Report 1',
                'budget_adjustment': '0',
                'additional_budget': '0',
                'additional_month': '0',
                'percentage_completed': '50'
            }
        }
        tx_hash = self.send_tx(self.btest_wallet, self.contracts['cps_score'],
                               0, 'submit_progress_report', params)
        pprint(tx_hash)

    def test_get_progress_reports_by_hash(self):
        resposne = self.call_tx(self.contracts['cps_score'],
                                {'_report_key': 'Report test 1'},
                                'get_progress_reports_by_hash')
        pprint(resposne)

    def test_set_next_block_2(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_nextBlock', {'_block': 150})
        pprint(tx)

    def test_remaining_time_in_application_period_1(self):
        resposne = self.call_tx(self.contracts['cps_score'], None,
                                'get_period_status')
        pprint(resposne)
        pprint(f"remaining time: {int(resposne['remaining_time'], 16)}")

    def test_update_period_after_progress_report_submission(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'update_period', None)
        pprint(tx)

    def test_vote_progress_report(self):
        for i in range(7):
            tx_hash = self.send_tx(
                self._wallet_array[10 + i], self.contracts['cps_score'], 0,
                'vote_progress_report', {
                    '_ipfs_key': 'Proposal 1 bnUSD',
                    '_report_key': 'Report 1 bnUSD',
                    '_vote': APPROVE,
                    '_vote_reason': 'Good addition to the platform',
                    '_budget_adjustment_vote': APPROVE,
                    '_vote_change': False
                })
            pprint(tx_hash)
            time.sleep(2)

    def test_update_period_after_voting_progress_report(self):
        # tx = self.build_transaction(self._test1, self.contracts['cps_score'], 0, 'update_period', None)
        # pprint(tx)
        tx = self.send_tx(self._test1, self.contracts['cps_score'], 0,
                          'update_period', None)
        pprint(tx)
        # tx = self.build_transaction(self._test1, self.contracts['cps_score'], 0, 'update_period', None)
        # pprint(tx)
        # tx = self.build_transaction(self._test1, self.contracts['cps_score'], 0, 'update_period', None)
        # pprint(tx)

    def test_remove_deny_list_preps(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'remove_denylist_preps', None)
        pprint(tx)

    def test_get_remaining_swap_amount(self):
        resposne = self.call_tx(self.contracts['cpf_treasury'], None,
                                'get_remaining_swap_amount')
        pprint(resposne)
        print(
            f"maxCap: {int(resposne['maxCap'], 16)}, remainingToSwap: {int(resposne['remainingToSwap'], 16)}"
        )

    def test_set_swap_count(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_swap_count', None)
        pprint(tx)

    # paying prep penalty -------------------------------------------------------------------------------------------------

    def test_set_prep_penalty_amount(self):
        tx = self.build_transaction(self._test1, self.contracts['cps_score'],
                                    0, 'set_prep_penalty_amount',
                                    {'_penalty': [5, 10, 15]})
        pprint(tx)

    def test_get_deny_list(self):
        resposne = self.call_tx(self.contracts['cps_score'], None,
                                'get_denylist')
        pprint(resposne)

    def test_pay_prep_penalty(self):
        _data = json.dumps({'method': 'pay_prep_penalty'})
        print(_data)
        params = {
            '_to': self.contracts['cps_score'],
            '_value': 5 * 10**18,
            '_data': _data.encode()
        }
        tx_hash = self.send_tx(self._wallet_array[11], self.contracts['bnUSD'],
                               0, 'transfer', params)
        pprint(tx_hash)

    def test_get_staking_address_in_sicx_score(self):
        resposne = self.call_tx(self.contracts['sicx'], None,
                                'getStakingAddress')
        pprint(resposne)

    def test_score(self):
        pass
コード例 #10
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)
コード例 #11
0
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.wallet.wallet import KeyWallet
from configu import BASE_DOMAIN_URL_V3_FOR_TEST
from iconsdk.builder.transaction_builder import (CallTransactionBuilder)

icon_service = IconService(HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST))
#------------------------------------------------------------------------------------
nid=3 # 3 for testnet, 1 for mainnet
testnet= "cxe2b43dba05f889fb3a99b480817675fac1fb3ec3"
daoDice_contract="cxb0b6f777fba13d62961ad8ce11be7ef6c4b2bcc6"
#------------------------------------------------------------------------------------
# Loads the gambling wallet
wallet = KeyWallet.load("./testWallet", "P@ssword123")  # USE A NEW WALLET. THIS WALLET ISNT SAFE!!!
print("\nYour Wallet address: ", wallet.get_address(), " ---Your private key: ", wallet.get_private_key())
icx_balance = from_bigint(icon_service.get_balance(wallet.get_address()))
print(f"Your are icx balance is {icx_balance} Icx")


# You can change loops, lower-upper range for the odds, the base bet and the wait-time for speed (let it  min at 4 sec)
# Its recommend it to use the platform for the valid bet amount or for the odds.
loops = 5
lower = 0
upper = 94
bet = 0.4  # IMPORTANT. Its the initial bet only. You have to change the bets below for the loss streak.
wait_time = 5

# IMPORTANT Don't change the loss counter.
bet_counter = 1
loss_streak_counter = 0
コード例 #12
0
class test_CPS_Score(IconIntegrateTestBase):
    TEST_HTTP_ENDPOINT_URI_V3 = "http://127.0.0.1:9000/api/v3"
    CPS_SCORE_PROJECT = os.path.abspath((os.path.join(DIR_PATH, '..',
                                                      'cps_score')))
    CPF_TREASURY_PROJECT = os.path.abspath(
        (os.path.join(DIR_PATH, '..', 'CPFTreasury')))
    CPS_TREASURY_PROJECT = os.path.abspath(
        (os.path.join(DIR_PATH, '..', 'CPSTreasury')))
    GOVERNANCE = os.path.abspath((os.path.join(DIR_PATH, '..', 'governance')))
    bnUSD_SCORE = os.path.abspath((os.path.join(DIR_PATH, '..', 'bnUSD')))
    sICX_SCORE = os.path.abspath((os.path.join(DIR_PATH, '..', 'sicx')))
    DEX_SCORE = os.path.abspath((os.path.join(DIR_PATH, '..', 'dex')))
    STAKING_SCORE = os.path.abspath((os.path.join(DIR_PATH, '..', 'staking')))
    LOANS_SCORE = os.path.abspath((os.path.join(DIR_PATH, '..', 'loans')))
    BLOCK_INTERVAL = 6

    def setUp(self):
        self._wallet_setup()
        super().setUp()

        self.icon_service = IconService(
            HTTPProvider(self.TEST_HTTP_ENDPOINT_URI_V3))
        print(self.icon_service)
        # self.cps_score = self._deploy_cps_score(params={})['scoreAddress']
        # self.cpf_score = self._deploy_cpf_treasury_score(params={'amount': 1_000_000 * 10 ** 18})['scoreAddress']
        # self.cps_treasury_score = self._deploy_cps_treasury_score(params={})['scoreAddress']
        self.system_score = SCORE_INSTALL_ADDRESS
        # self.contracts = {'cps_score': self._deploy_cps_score()['scoreAddress'],
        #                   'cpf_treasury': self._deploy_cpf_treasury_score()['scoreAddress'],
        #                   'cps_treasury': self._deploy_cps_treasury_score()['scoreAddress'],
        #                   'bnUSD': self._deploy_bnUSD_score()['scoreAddress'],
        #                   # 'staking_score': self._deploy_staking_score()['scoreAddress'],
        #                   'sICX_score': self._deploy_sICX_score()['scoreAddress'],
        #                   'dex_score': self._deploy_dex_score()['scoreAddress'],
        #                   'governance_score': self._deploy_governance_score()['scoreAddress'],
        #                   }
        self.contracts = {
            'bnUSD': 'cxa0311a293021d534013d28c528efbd15022a5e91',
            'cpf_treasury': 'cx13bb27bbf86e7a02760646cbd0c5c3bcba9d640c',
            'cps_score': 'cxf0fd220782b4007ecca144f4a80fe3c9e594012f',
            'cps_treasury': 'cxbe941a60817d351fd2151c551754cfa490a1c6c4',
            'dex_score': 'cx5e902c7ea2a3f7693bef0b0059bd6ac376ac8375',
            'governance_score': 'cx027796be7eb5f573cdfa4b41ca4ea61fc5019121',
            'sICX_score': 'cx888dcf645f752a36bc0e86cb23b392068e36d743',
            'staking_score': 'cx73971c52c82dea76f4bb7a8d17915037fd6b8538',
            'loans_score': 'cx10fc346afb055cb0f671c16cc35ef0bd88b277f3'
        }
        pprint(self.contracts)
        # self._register_100_preps(10, 20)
        # self._register_prep()
        # self._set_stake()
        # self._set_delegation()
        # self._add_fund()

    # deployment of scores *************************************************************************
    # ******************************************************************************************

    def _deploy_cps_score(self,
                          to: str = SCORE_INSTALL_ADDRESS,
                          params=None) -> dict:
        if params is None:
            params = {}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPS_SCORE_PROJECT)) \
            .params(params) \
            .build()

        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def _deploy_cpf_treasury_score(self,
                                   to: str = SCORE_INSTALL_ADDRESS,
                                   params=None) -> dict:
        if params is None:
            params = {'amount': 1_000_000 * 10**18}

        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPF_TREASURY_PROJECT)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def _deploy_cps_treasury_score(self,
                                   to: str = SCORE_INSTALL_ADDRESS,
                                   params=None) -> dict:
        if params is None:
            params = {}

        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.CPS_TREASURY_PROJECT)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def _deploy_governance_score(self, to=SCORE_INSTALL_ADDRESS, params=None):
        if params is None:
            params = {}

        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.GOVERNANCE)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def _deploy_bnUSD_score(self, to=SCORE_INSTALL_ADDRESS):
        params = {'_governance': SCORE_INSTALL_ADDRESS}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.bnUSD_SCORE)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def test_deploy_staking_score(self, to=SCORE_INSTALL_ADDRESS):
        params = {}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.STAKING_SCORE)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def test_deploy_sICX_score(self, to=SCORE_INSTALL_ADDRESS):
        params = {'_admin': self.contracts['staking_score']}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.sICX_SCORE)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        return tx_result

    def test_deploy_dex_score(self, to=SCORE_INSTALL_ADDRESS):
        params = {'_governance': self.contracts['governance_score']}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.DEX_SCORE)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        self.assertEqual(True, tx_result['status'])

        return tx_result

    def test_deploy_loans_score(self, to=SCORE_INSTALL_ADDRESS):
        params = {'_governance': self.contracts['governance_score']}
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(self.LOANS_SCORE)) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertTrue('scoreAddress' in tx_result)
        pprint(tx_result)
        self.assertEqual(True, tx_result['status'])

        return tx_result

    # score update ************************************************************************************************
    # *********************************************************************************************************

    def update_contracts(self, contract_path: str, contract_address: str):
        transaction = DeployTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(contract_address) \
            .step_limit(100_000_000_000) \
            .nid(3) \
            .nonce(100) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(contract_path)) \
            .build()
        signed_transaction = SignedTransaction(transaction, self._test1)

        # process the transaction in local
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.assertEqual(True, tx_result['status'])
        self.assertTrue('scoreAddress' in tx_result)
        return tx_result

    def test_update_contract(self):
        self.update_contracts(self.CPF_TREASURY_PROJECT,
                              self.contracts['cpf_treasury'])

    # wallet setup for preps and registering preps ***********************************************************************
    # ****************************************************************************************************************

    def _wallet_setup(self):
        self.icx_factor = 10**18
        self.btest_wallet: 'KeyWallet' = self._wallet_array[5]
        self.staking_wallet: 'KeyWallet' = self._wallet_array[6]

    def _register_100_preps(self, start=10, end=20):
        txs = []
        for i in range(start, end):
            len_str = str(start)
            if len(len_str) == 2:
                j = "0" + str(i)
            else:
                j = str(i)
            params = {
                "name":
                "Test P-rep " + str(i),
                "country":
                "KOR",
                "city":
                "Unknown",
                "email":
                "nodehx9eec61296a7010c867ce24c20e69588e28321" + j +
                "@example.com",
                "website":
                'https://nodehx9eec61296a7010c867ce24c20e69588e28321' + j +
                '.example.com',
                "details":
                'https'
                '://nodehx9eec61296a7010c867ce24c20e69588e28321' + j +
                '.example.com/details',
                "p2pEndpoint":
                "nodehx9eec61296a7010c867ce24c20e69588e28321" + j +
                ".example.com:7100",
                "nodeAddress":
                "hx9eec61296a7010c867ce24c20e69588e28321" + j
            }
            self.send_icx(self._test1, self._wallet_array[i].get_address(),
                          3000000000000000000000)
            print(params["nodeAddress"])
            txs.append(
                self.build_tx(self._wallet_array[i],
                              "cx0000000000000000000000000000000000000000",
                              2000000000000000000000, "registerPRep", params))
        ab = self.process_transaction_bulk(txs, self.icon_service, 10)
        pprint(ab)

    # send tx, call tx, send tx contracts *******************************************************************************
    # ***************************************************************************************************************

    def send_icx(self, from_: KeyWallet, to: str, value: int):
        previous_to_balance = self.get_balance(to)
        previous_from_balance = self.get_balance(from_.get_address())

        signed_icx_transaction = self.build_send_icx(from_, to, value)
        tx_result = self.process_transaction(signed_icx_transaction,
                                             self.icon_service,
                                             self.BLOCK_INTERVAL)

        fee = tx_result['stepPrice'] * tx_result['cumulativeStepUsed']
        self.assertTrue('status' in tx_result)
        self.assertEqual(
            1, tx_result['status'], f"Failure: {tx_result['failure']}"
            if tx_result['status'] == 0 else "")
        self.assertEqual(previous_to_balance + value, self.get_balance(to))
        self.assertEqual(previous_from_balance - value - fee,
                         self.get_balance(from_.get_address()))

    def build_send_icx(self, from_: KeyWallet, to: str,
                       value: int) -> SignedTransaction:
        send_icx_transaction = TransactionBuilder(from_=from_.get_address(),
                                                  to=to,
                                                  value=value,
                                                  step_limit=1000000,
                                                  nid=3,
                                                  nonce=3).build()
        signed_icx_transaction = SignedTransaction(send_icx_transaction, from_)
        return signed_icx_transaction

    def get_balance(self, address: str) -> int:
        if self.icon_service is not None:
            return self.icon_service.get_balance(address)
        params = {'address': Address.from_string(address)}
        response = self.icon_service_engine.query(method="icx_getBalance",
                                                  params=params)
        return response

    def send_tx(self,
                from_: KeyWallet,
                to: str,
                value: int = 0,
                method: str = None,
                params: dict = None) -> dict:
        signed_transaction = self.build_tx(from_, to, value, method, params)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service,
                                             self.BLOCK_INTERVAL)
        # ab = tx_result
        # print(ab)
        step_price = tx_result['stepPrice']
        step_used = tx_result['stepUsed']
        # print(step_used)
        # print(step_price)
        print("The tx fee is ....")
        print((step_price * step_used) / 10**18)
        pprint(tx_result)
        self.assertTrue('status' in tx_result)
        self.assertEqual(
            1, tx_result['status'], f"Failure: {tx_result['failure']}"
            if tx_result['status'] == 0 else "")
        return tx_result

    def build_tx(self, from_: KeyWallet, to: str, value: int, method: str = None, params: dict = None) \
            -> SignedTransaction:

        params = {} if params is None else params
        tx = CallTransactionBuilder(from_=from_.get_address(),
                                    to=to,
                                    value=value,
                                    step_limit=3_000_000_000,
                                    nid=3,
                                    nonce=5,
                                    method=method,
                                    params=params).build()
        signed_transaction = SignedTransaction(tx, from_)
        return signed_transaction

    def call_tx(self, _score, params, method):
        params = {} if params is None else params
        _call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(_score) \
            .method(method) \
            .params(params) \
            .build()
        response = self.process_call(_call, self.icon_service)
        return response

    def build_transaction(self,
                          from_: KeyWallet,
                          to: str,
                          value: int = 0,
                          method: str = None,
                          params: dict = None) -> dict:
        call_transaction = CallTransactionBuilder() \
            .from_(from_.get_address()) \
            .to(to) \
            .value(value) \
            .nid(3) \
            .nonce(100) \
            .method(method) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(call_transaction, self._test1,
                                               10000000)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertEqual(tx_result['status'], 1)
        return tx_result

    def build_transaction_contact(self,
                                  from_,
                                  to: str,
                                  value: int = 0,
                                  method: str = None,
                                  params: dict = None) -> dict:
        call_transaction = CallTransactionBuilder() \
            .from_(from_) \
            .to(to) \
            .value(value) \
            .nid(3) \
            .nonce(100) \
            .method(method) \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(call_transaction, self._test1,
                                               10000000)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertEqual(tx_result['status'], 1)
        return tx_result

    # adding necessary parameters in different scores *******************************************************************
    # ***************************************************************************************************************

    def test_add_admin(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cps_score'], 0, 'add_admin',
            {'_address': self._test1.get_address()})
        pprint(tx_result)

    def test_set_cps_treasury_score(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cps_score'], 0,
            'set_cps_treasury_score',
            {'_score': self.contracts['cps_treasury']})
        pprint(tx_result)

    def test_set_cpf_treasury_score(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cps_score'], 0,
            'set_cpf_treasury_score',
            {'_score': self.contracts['cpf_treasury']})
        pprint(tx_result)

    def test_set_bnUSD_in_cps_score(self):
        tx_result = self.build_transaction(self._test1,
                                           self.contracts['cps_score'], 0,
                                           'set_bnUSD_score',
                                           {'_score': self.contracts['bnUSD']})
        pprint(tx_result)

    def test_set_cps_score_in_cps_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cps_treasury'], 0, 'set_cps_score',
            {'_score': self.contracts['cps_score']})
        pprint(tx_result)

    def test_set_cpf_treasury_in_cps_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cps_treasury'], 0,
            'set_cpf_treasury_score',
            {'_score': self.contracts['cpf_treasury']})
        pprint(tx_result)

    def test_set_bnUSD_in_cps_treasury(self):
        tx_result = self.build_transaction(self._test1,
                                           self.contracts['cps_treasury'], 0,
                                           'set_bnUSD_score',
                                           {'_score': self.contracts['bnUSD']})
        pprint(tx_result)

    def test_set_cps_score_in_cpf_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cpf_treasury'], 0, 'set_cps_score',
            {'_score': self.contracts['cps_score']})
        pprint(tx_result)

    def test_set_cps_treasury_in_cpf_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cpf_treasury'], 0,
            'set_cps_treasury_score',
            {'_score': self.contracts['cps_treasury']})
        pprint(tx_result)

    def test_set_bnUSD_in_cpf_treasury(self):
        tx_result = self.build_transaction(self._test1,
                                           self.contracts['cpf_treasury'], 0,
                                           'set_bnUSD_score',
                                           {'_score': self.contracts['bnUSD']})
        pprint(tx_result)

    def test_set_staking_score_in_cpf_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cpf_treasury'], 0,
            'set_staking_score', {'_score': self.contracts['staking_score']})
        pprint(tx_result)

    def test_set_sicx_score_in_cpf_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cpf_treasury'], 0, 'set_sicx_score',
            {'_score': self.contracts['sICX_score']})
        pprint(tx_result)

    def test_set_dex_score_in_cpf_treasury(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['cpf_treasury'], 0, 'set_dex_score',
            {'_score': self.contracts['dex_score']})
        pprint(tx_result)

    def test_set_sicx_score_in_staking(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['staking_score'], 0, 'setSicxAddress',
            {'_address': self.contracts['sICX_score']})
        pprint(tx_result)

    def test_set_staking_in_sicx(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['sICX_score'], 0, 'setStakingAddress',
            {'_address': self.contracts['staking_score']})
        pprint(tx_result)

    def test_set_governance_on_dex(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['dex_score'], 0, 'setGovernance',
            {'_address': self.contracts['governance_score']})
        pprint(tx_result)

    def test_set_admin_on_dex(self):
        tx_result = self.build_transaction(
            self._test1, self.contracts['dex_score'], 0, 'setStaking',
            {'_address': self.contracts['staking_score']})
        pprint(tx_result)

    def test_set_admin_on_dex_score(self):
        call_transaction = CallTransactionBuilder() \
            .from_('cx027796be7eb5f573cdfa4b41ca4ea61fc5019121') \
            .to(self.contracts['dex_score']) \
            .value(0) \
            .nid(3) \
            .nonce(100) \
            .method('setAdmin') \
            .params({'_admin': self._test1.get_address()}) \
            .build()
        signed_transaction = SignedTransaction(call_transaction, self._test1,
                                               10000000)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertEqual(tx_result['status'], 1)
        return tx_result

    def _register_prep(self):
        print(f'Wallet address: {self._wallet_array[10].get_address()}')

        pprint(
            self.send_tx(self._wallet_array[10], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[11], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[12], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[13], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[14], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[15], self.contracts['cps_score'],
                         0, 'register_prep', None))
        pprint(
            self.send_tx(self._wallet_array[16], self.contracts['cps_score'],
                         0, 'register_prep', None))

    # stake and deligate to vote *****************************************************************************************
    # ****************************************************************************************************************

    def _set_stake(self):
        pprint(
            self.send_tx(self._wallet_array[10],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[11],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[12],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[13],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[14],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[15],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))
        pprint(
            self.send_tx(self._wallet_array[16],
                         'cx0000000000000000000000000000000000000000', 0,
                         'setStake', {'value': 100}))

    def _set_delegation(self):
        pprint(
            self.send_tx(
                self._wallet_array[10],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[10].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[11],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[11].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[12],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[12].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[13],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[13].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[14],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[14].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[15],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[15].get_address(),
                        'value': 100
                    }]
                }))
        pprint(
            self.send_tx(
                self._wallet_array[16],
                'cx0000000000000000000000000000000000000000', 0,
                'setDelegation', {
                    'delegations':
                    [{
                        'address': self._wallet_array[16].get_address(),
                        'value': 100
                    }]
                }))

    # testing the flow ***********************************************************************************************
    # ************************************************************************************************************

    def test_submit_proposal(self):
        proposal_parameters = {
            'ipfs_hash':
            'bafybeie5cifgwgu2x3guixgrs67miydug7ocyp6yia5kxv3imve6fthbs4',
            'project_title': 'Test Proposal',
            'project_duration': 2,
            'total_budget': 100,
            'sponsor_address': self._wallet_array[10].get_address(),
            'ipfs_link': '*****@*****.**',
            'token': 'bnUSD'
        }
        self._set_initial_block()
        tx_result = self.send_tx(self._test1, self.contracts['cps_score'],
                                 50 * 10**18, "submit_proposal",
                                 {'_proposals': proposal_parameters})
        pprint(tx_result)

    def _add_fund(self):
        self.send_tx(self._test1, self.contracts['cpf_treasury'],
                     7000 * 10**18, "add_fund", None)

    def test_toggle_staking_on_staking_score(self):
        tx_result = self.send_tx(self._test1, self.contracts['staking_score'],
                                 0, 'toggleStakingOn', None)
        pprint(tx_result)

    def test_set_sicx_address_on_staking_score(self):
        tx_result = self.send_tx(self._test1, self.contracts['staking_score'],
                                 0, 'setSicxAddress',
                                 {'_address': self.contracts['sICX_score']})
        pprint(tx_result)

    def test_stake_icx_in_cpf_treasury(self):
        tx_result = self.send_tx(self._test1, self.contracts['cpf_treasury'],
                                 0, 'stake_icx', {'_amount': 1000 * 10**18})
        pprint(tx_result)

    def test_configure_balanced(self):
        tx_result = self.send_tx(self._test1,
                                 self.contracts['governance_score'], 0,
                                 'configureBalanced', None)
        pprint(tx_result)

    def test_swap_sicx_in_cpf_treasury(self):
        tx_result = self.send_tx(self._test1, self.contracts['cpf_treasury'],
                                 0, 'swap_bnusd', {'_amount': 900 * 10**18})
        pprint(tx_result)

    def test_get_staking_address(self):
        print(self.call_tx(self.contracts['dex_score'], None, 'getGovernance'))

    def _set_initial_block(self):
        self.send_tx(self._test1, self.contracts['cps_score'], 0,
                     "set_initialBlock", None)

    def test_path(self):
        print(self.GOVERNANCE)
        print(self.sICX_SCORE)
        print(self.bnUSD_SCORE)
        print(self.DEX_SCORE)
        print(self.STAKING_SCORE)
コード例 #13
0
from iconsdk.providers.http_provider import HTTPProvider
from configu import BASE_DOMAIN_URL_V3_FOR_TEST
from iconsdk.builder.call_builder import CallBuilder
from iconsdk.wallet.wallet import KeyWallet
from iconsdk.utils.convert_type import convert_bytes_to_hex_str
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.builder.transaction_builder import (CallTransactionBuilder)

icon_service = IconService(HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST))
pp = pprint.PrettyPrinter(width=3)
address = "Put address here"
icx_score = "cx0000000000000000000000000000000000000000"
iconswap_score = "cx90d86f087c70187d1a054473887165815f6251a8"
tap_score = "cx22ca8e22e3d570b671d7a5b29bbc15a266b7dfae"
nid = 3
icx_balance = from_bigint(icon_service.get_balance(address))

my_wallet = KeyWallet.load("wallet keystore location", "password")
print("[wallet1] address: ", my_wallet.get_address(), " private key: ",
      my_wallet.get_private_key())


def token_balance():
    """ Returns your Tap Balance"""

    call = CallBuilder().from_(my_wallet.get_address()) \
        .to(tap_score) \
        .method("balanceOf") \
        .params({"_owner": address}) \
        .build()
    result = icon_service.call(call)
コード例 #14
0
class Base(IconIntegrateTestBase):
    def setUp(self):
        super().setUp(block_confirm_interval=1, network_only=True)

        # if you want to send request to network, uncomment next line and set self.TEST_HTTP_ENDPOINT_URI_V3
        self.icon_service = IconService(
            HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))

    # ================= Tool =================
    def _get_block_height(self) -> int:
        block_height: int = 0
        if self.icon_service:
            block = self.icon_service.get_block("latest")
            block_height = block['height']
        return block_height

    def _make_blocks(self, to: int):
        block_height = self._get_block_height()

        while to > block_height:
            self.process_message_tx(self.icon_service, "test message")
            block_height += 1

    def _make_blocks_to_next_calculation(self) -> int:
        iiss_info = self.get_iiss_info()
        next_calculation = int(iiss_info.get('nextCalculation', 0), 16)

        self._make_blocks(to=next_calculation)

        self.assertEqual(self._get_block_height(), next_calculation)

        return next_calculation

    @staticmethod
    def create_deploy_score_tx(
            score_path: str,
            from_: 'KeyWallet',
            to: str = SCORE_INSTALL_ADDRESS) -> 'SignedTransaction':
        transaction = DeployTransactionBuilder() \
            .from_(from_.get_address()) \
            .to(to) \
            .step_limit(100_000_000_000) \
            .nid(DEFAULT_NID) \
            .nonce(0) \
            .content_type("application/zip") \
            .content(gen_deploy_data_content(score_path)) \
            .build()

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

    @staticmethod
    def create_set_revision_tx(from_: 'KeyWallet',
                               revision: int) -> 'SignedTransaction':
        # set revision
        transaction = CallTransactionBuilder() \
            .from_(from_.get_address()) \
            .to(GOVERNANCE_ADDRESS) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("setRevision") \
            .params({"code": revision, "name": f"1.4.{revision}"}) \
            .build()

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

    @staticmethod
    def create_transfer_icx_tx(from_: 'KeyWallet',
                               to_: str,
                               value: int,
                               step_limit: int = DEFAULT_STEP_LIMIT,
                               nid: int = DEFAULT_NID,
                               nonce: int = 0) -> 'SignedTransaction':
        transaction = TransactionBuilder() \
            .from_(from_.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, from_)
        return signed_transaction

    @staticmethod
    def create_register_prep_tx(key_wallet: 'KeyWallet',
                                reg_data: Dict[str, Union[str, bytes]] = None,
                                value: int = 0,
                                step_limit: int = DEFAULT_STEP_LIMIT,
                                nid: int = DEFAULT_NID,
                                nonce: int = 0) -> 'SignedTransaction':
        if not reg_data:
            reg_data = Base._create_register_prep_params(key_wallet)

        transaction = CallTransactionBuilder(). \
            from_(key_wallet.get_address()). \
            to(SYSTEM_ADDRESS). \
            value(value). \
            step_limit(step_limit). \
            nid(nid). \
            nonce(nonce). \
            method("registerPRep"). \
            params(reg_data). \
            build()

        signed_transaction = SignedTransaction(transaction, key_wallet)

        return signed_transaction

    @staticmethod
    def create_unregister_prep_tx(key_wallet: 'KeyWallet',
                                  value: int = 0,
                                  step_limit: int = DEFAULT_STEP_LIMIT,
                                  nid: int = DEFAULT_NID,
                                  nonce: int = 0) -> 'SignedTransaction':

        transaction = CallTransactionBuilder(). \
            from_(key_wallet.get_address()). \
            to(SYSTEM_ADDRESS). \
            value(value). \
            step_limit(step_limit). \
            nid(nid). \
            nonce(nonce). \
            method("unregisterPRep"). \
            build()

        signed_transaction = SignedTransaction(transaction, key_wallet)

        return signed_transaction

    @staticmethod
    def create_set_prep_tx(key_wallet: 'KeyWallet',
                           irep: int = None,
                           set_data: Dict[str, Union[str, bytes]] = None,
                           value: int = 0,
                           step_limit: int = DEFAULT_STEP_LIMIT,
                           nid: int = DEFAULT_NID,
                           nonce: int = 0) -> 'SignedTransaction':
        if set_data is None:
            set_data = {}
        if irep is not None:
            set_data[ConstantKeys.IREP] = hex(irep)

        transaction = CallTransactionBuilder(). \
            from_(key_wallet.get_address()). \
            to(SYSTEM_ADDRESS). \
            value(value). \
            step_limit(step_limit). \
            nid(nid). \
            nonce(nonce). \
            method("setPRep"). \
            params(set_data). \
            build()

        signed_transaction = SignedTransaction(transaction, key_wallet)

        return signed_transaction

    @staticmethod
    def create_set_stake_tx(key_wallet: KeyWallet,
                            stake: int,
                            value: int = 0,
                            step_limit: int = DEFAULT_STEP_LIMIT,
                            nid: int = DEFAULT_NID,
                            nonce: int = 0) -> 'SignedTransaction':

        transaction = CallTransactionBuilder(). \
            from_(key_wallet.get_address()). \
            to(SYSTEM_ADDRESS). \
            value(value). \
            step_limit(step_limit). \
            nid(nid). \
            nonce(nonce). \
            method("setStake"). \
            params({"value": hex(stake)}). \
            build()

        signed_transaction = SignedTransaction(transaction, key_wallet)

        return signed_transaction

    @staticmethod
    def create_set_delegation_tx(key_wallet: KeyWallet,
                                 delegations: List[Tuple['KeyWallet', int]],
                                 value: int = 0,
                                 step_limit: int = DEFAULT_STEP_LIMIT,
                                 nid: int = DEFAULT_NID,
                                 nonce: int = 0) -> 'SignedTransaction':
        delegations = Base.create_delegation_params(delegations)

        transaction = CallTransactionBuilder(). \
            from_(key_wallet.get_address()). \
            to(SYSTEM_ADDRESS). \
            value(value). \
            step_limit(step_limit). \
            nid(nid). \
            nonce(nonce). \
            method("setDelegation"). \
            params({"delegations": delegations}). \
            build()

        signed_transaction = SignedTransaction(transaction, key_wallet)

        return signed_transaction

    @staticmethod
    def create_claim_iscore_tx(key_wallet: 'KeyWallet',
                               value: int = 0,
                               step_limit: int = DEFAULT_STEP_LIMIT,
                               nid: int = DEFAULT_NID,
                               nonce: int = 0) -> 'SignedTransaction':

        transaction = CallTransactionBuilder(). \
            from_(key_wallet.get_address()). \
            to(SYSTEM_ADDRESS). \
            value(value). \
            step_limit(step_limit). \
            nid(nid). \
            nonce(nonce). \
            method("claimIScore"). \
            build()

        signed_transaction = SignedTransaction(transaction, key_wallet)

        return signed_transaction

    def get_prep_list(self,
                      start_index: Optional[int] = None,
                      end_index: Optional[int] = None) -> dict:
        params = {}
        if start_index is not None:
            params['startRanking'] = hex(start_index)
        if end_index is not None:
            params['endRanking'] = hex(end_index)
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getPRepList") \
            .params(params) \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_main_prep_list(self) -> dict:
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getMainPRepList") \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_sub_prep_list(self) -> dict:
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getSubPRepList") \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_prep(self, key_wallet: 'KeyWallet') -> dict:

        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getPRep") \
            .params({"address": key_wallet.get_address()}) \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_stake(self, key_wallet: 'KeyWallet') -> dict:
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getStake") \
            .params({"address": key_wallet.get_address()}) \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_delegation(self, key_wallet: 'KeyWallet') -> dict:
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getDelegation") \
            .params({"address": key_wallet.get_address()}) \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_balance(self, key_wallet: 'KeyWallet') -> dict:
        return self.icon_service.get_balance(key_wallet.get_address())

    def query_iscore(self, key_wallet: 'KeyWallet') -> dict:
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("queryIScore") \
            .params({"address": key_wallet.get_address()}) \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    def get_iiss_info(self) -> dict:
        call = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(SYSTEM_ADDRESS) \
            .method("getIISSInfo") \
            .build()
        response = self.process_call(call, self.icon_service)
        return response

    @staticmethod
    def _create_register_prep_params(
            key_wallet: 'KeyWallet') -> Dict[str, Union[str, bytes]]:
        name = f"node{key_wallet.get_address()[2:7]}"

        return {
            ConstantKeys.NAME: name,
            ConstantKeys.EMAIL: f"node{name}@example.com",
            ConstantKeys.WEBSITE: f"https://node{name}.example.com",
            ConstantKeys.DETAILS: f"https://node{name}.example.com/details",
            ConstantKeys.P2P_END_POINT: f"https://node{name}.example.com:7100",
            ConstantKeys.PUBLIC_KEY: f"0x{key_wallet.bytes_public_key.hex()}"
        }

    @staticmethod
    def create_delegation_params(
            params: List[Tuple['KeyWallet', int]]) -> List[Dict[str, str]]:
        return [{
            "address": key_wallet.get_address(),
            "value": hex(value)
        } for (key_wallet, value) in params if value > 0]