Пример #1
0
    def setUpClass(cls):
        icon_endpoint = os.environ['ICON_ENDPOINT']

        if icon_endpoint == 'testnet':
            cls.icon_service = IconService(
                HTTPProvider('https://bicon.net.solidwallet.io/api/v3'))
            cls.act_kard_score_address = 'cx3d85fc30097cb8b18eb52de927b444833c690705'
            cls.act_ace_score_address = 'cxdccbc7ee2d5581e62c8ba300219a5e8d05b58215'
        else:
            cls.icon_service = IconService(
                HTTPProvider('http://127.0.0.1:9000/api/v3'))
            cls.act_kard_score_address = 'cx3d85fc30097cb8b18eb52de927b444833c690705'
            cls.act_ace_score_address = 'cxdccbc7ee2d5581e62c8ba300219a5e8d05b58215'

        cls.owner_wallet = KeyWallet.load('conf/test_owner.keystore',
                                          'test123!')
        cls.user1_wallet = KeyWallet.load('conf/test_user1.keystore',
                                          'test123!')
        cls.user2_wallet = KeyWallet.load('conf/test_user2.keystore',
                                          'test123!')

        totalSupply = total_supply(cls.act_kard_score_address,
                                   cls.owner_wallet.get_address())

        print(f'[KARD]total_supply = {totalSupply}')

        totalSupply = total_supply(cls.act_ace_score_address,
                                   cls.owner_wallet.get_address())

        print(f'[A.C.E]total_supply = {totalSupply}')

        owner_balance = balance_of(cls.act_kard_score_address,
                                   cls.owner_wallet.get_address(),
                                   cls.owner_wallet.get_address())
        print('[KARD]owner_balance = {}'.format(owner_balance))

        user1_balance = balance_of(cls.act_kard_score_address,
                                   cls.user1_wallet.get_address(),
                                   cls.user1_wallet.get_address())
        print('[KARD]user1_balance = {}'.format(user1_balance))

        user2_balance = balance_of(cls.act_kard_score_address,
                                   cls.user2_wallet.get_address(),
                                   cls.user2_wallet.get_address())
        print('[KARD]user2_balance = {}'.format(user2_balance))

        owner_balance = balance_of(cls.act_ace_score_address,
                                   cls.owner_wallet.get_address(),
                                   cls.owner_wallet.get_address())
        print('[A.C.E]owner_balance = {}'.format(owner_balance))

        user1_balance = balance_of(cls.act_ace_score_address,
                                   cls.user1_wallet.get_address(),
                                   cls.user1_wallet.get_address())
        print('[A.C.E]user1_balance = {}'.format(user1_balance))

        user2_balance = balance_of(cls.act_ace_score_address,
                                   cls.user2_wallet.get_address(),
                                   cls.user2_wallet.get_address())
        print('[A.C.E]user2_balance = {}'.format(user2_balance))
    def transfer(self, conf: dict) -> dict:
        """Transfer ICX Coin.

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

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

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

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

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

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

        transaction.step_limit = step_limit

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

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

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

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

        return response
Пример #3
0
    def __init__(self, node_conf_path: str, wallet_path: str, passwd: str):

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

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

        self.web_protocol = node_conf["web_protocol"]

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

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

        self._score_info = node_conf["scores"]
    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)
Пример #5
0
    def block(self, conf):
        """Query block with given parameter(height or hash)

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

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

        return response
Пример #6
0
def add_token_test(request):
    # Withouth all the mapping fusiness. This just min  ts the token and show it up

    #Connect to Federico wallet Method

    node_uri = "https://bicon.net.solidwallet.io/api/v3"
    network_id = 3
    hello_world_address = "cx2a96ae73368ee622f29ea6df5a9e621059326feb"
    keystore_path = "./walletFEDEKEYSTORE.119Z--hx8bad34f951350f2805af083b50562529241c5baf"
    keystore_pw = "Darkarior448!"

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

    #Checking the wallet data

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

    tester_addr = wallet.get_address()
    icon_service = IconService(HTTPProvider(node_uri))
    service_adress = "cx312f84fa11a0d315ea4331c5e601d3c4897575f8"
    # TODO Here put the receiver address from the current logged in data
    receiver_address = tester_addr

    # Way to large
    # tokenId = uuid.uuid1().int

    tokenId_start = int(str(uuid.uuid1().int)[:5])
    tokenId = tokenId_start + int(round(time.time() * 1000))

    firebase_id = request.session['local_id']
    champType = 1

    addChampionToDB(firebase_id, tokenId, champType)

    params = {
        '_to': receiver_address,
        '_tokenId': tokenId,
    }

    transaction = CallTransactionBuilder().from_(tester_addr)\
                        .to(service_adress)\
                        .method("mint")\
                        .nid(3)\
                        .nonce(100)\
                        .params(params)\
                        .step_limit(1000000)\
                        .build()

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

    # Sends the transaction
    tx_hash = icon_service.send_transaction(signed_transaction)
    print(tx_hash)

    context = {'newChampionName': "example"}
    return render(request, join('core', 'champion_added.html'), context)
Пример #7
0
    def _set_samples(self, domain: str) -> (list, list, list, list):
        buf_blocks = list()
        buf_transactions_on_blocks = list(
        )  # block's transaction list which means confirmed transaction list
        buf_transactions = list()  # return value of 'get_transaction'
        buf_transaction_results = list(
        )  # return value of 'get_transaction_result'

        icon_service = IconService(HTTPProvider(domain, VERSION_FOR_TEST))
        target_block_heights = self._set_target_heights()
        for height in target_block_heights:
            block = icon_service.get_block(height, full_response=True)
            block = block['result']
            buf_blocks.append(block)
            for transaction in block[
                    'confirmed_transaction_list' if block['version'] ==
                    BLOCK_0_1A_VERSION else 'transactions']:
                buf_transactions_on_blocks.append(transaction)

                if ('tx_hash' or 'txHash') in transaction:
                    tx_hash = transaction['tx_hash' if 'tx_hash' in
                                          transaction else 'txHash']
                    tx_hash = add_0x_prefix(tx_hash)
                    tx = icon_service.get_transaction(tx_hash,
                                                      full_response=True)
                    tx = tx['result']
                    buf_transactions.append(tx)
                    tx_result = icon_service.get_transaction_result(
                        tx_hash, full_response=True)
                    tx_result = tx_result['result']
                    buf_transaction_results.append(tx_result)

        return buf_blocks, buf_transactions_on_blocks, buf_transactions, buf_transaction_results
    def __init__(self, node_conf_path: str, wallet_path: str, passwd: str):

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

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

        if node_conf["web_protocol"] == "ssl":
            self._icon_service = IconService(
                HTTPProvider("https://" + node_conf["address"], 3))
        else:
            self._icon_service = IconService(
                HTTPProvider("http://" + node_conf["address"], 3))
        print(
            f"--------------------------------<Connecting node>--------------------------------"
        )
        print(f" - address    : {node_conf['address']}")
        print(f" - chain_name : {self._my_chain_name}")
        print(f" - nid        : {self._nid}")
        print(
            f"---------------------------------------------------------------------------------"
        )

        # Set wallet of deployer
        self._wallet = KeyWallet.load(wallet_path, passwd)
        # print(f"pk: {self._wallet.get_private_key()}")

        # Set deployed score address
        self._score_addr = ""  # It will be set after deployment
        self._score_path = ""
        self._score_params = {}
        self._score_info = ""
    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()
Пример #10
0
def generate_tx(file, password, icx_value, to_addr, nid, api_url, is_send,
                timestamp):
    step_limit = 1000000
    value = int(icx_value * 10**18)
    wallet = KeyWallet.load(file, password)
    owner_from_addr = wallet.get_address()
    transaction = TransactionBuilder() \
        .from_(owner_from_addr) \
        .to(to_addr) \
        .step_limit(step_limit) \
        .nid(int(nid)) \
        .nonce(100) \
        .value(value) \
        .timestamp(timestamp)\
        .build()
    signed_params = SignedTransaction(transaction, wallet)
    signed_payload = {
        'jsonrpc': '2.0',
        'method': "icx_sendTransaction",
        'id': 1234,
        "params": signed_params.signed_transaction_dict
    }
    kvPrint("[before] signed_payload",
            json.dumps(signed_payload, indent=4, sort_keys=True))
    kvPrint("[before] calculate the tx_hash",
            f"0x{generate_message(signed_params.signed_transaction_dict)}")

    if is_send:
        print("===== send tx =====")
        provider = HTTPProvider(f"{api_url}/api/v3")
        icon_service = IconService(provider)
        tx_hash = icon_service.send_transaction(signed_params)
        kvPrint(f"[after]  sendTX() txResult", tx_hash)

    return signed_payload
Пример #11
0
    def get_block(self, block_height):
        icon_service = IconService(HTTPProvider(PrepRPCCalls.USE_NET))

        latest_block = icon_service.get_block("latest")
        if latest_block['height'] < block_height:
            return None

        block = icon_service.get_block(block_height)
        return block
Пример #12
0
    def test_call_api_by_the_initializer_with_valid_url(self):
        http_provider = HTTPProvider(self.FULL_PATH_URL)
        self.assertIsNotNone(http_provider._full_path_url)
        try:
            http_provider._base_domain_url
        except AttributeError:
            self.assertTrue(True)

        icon_service = IconService(http_provider)
        self.assertEqual(type(icon_service.get_block("latest")), dict)
Пример #13
0
    def sendtx(self, conf: dict):
        """Send transaction.

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

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

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

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

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

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

        transaction.step_limit = step_limit

        signed_transaction = SignedTransaction(transaction, wallet)

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

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

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

        return response
Пример #14
0
    def json_rpc_call(self, method_name, params):
        icon_service = IconService(HTTPProvider(DashboardRPCCalls.MAIN_NET))
        call_builder = CallBuilder() \
            .to(self._to_contract) \
            .method(method_name) \
            .params(params) \
            .build()

        response = icon_service.call(call_builder)

        return response
Пример #15
0
    def show_game_room_list(self):

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

        response = _icon_service.call(_)

        return response
Пример #16
0
 def __init__(self, _conf_rpc: dict) -> None:
     # Key Wallet with Password
     self.key_wallet = KeyWallet.load(_conf_rpc["KeyWallet"]["File"],
                                      _conf_rpc["KeyWallet"]["Password"])
     # Service Endpoint (URL)
     self.service_endpoint = IconService(
         HTTPProvider(_conf_rpc["Service Endpoint"]))
     # Smart Contract Address
     self.id_contract_address = _conf_rpc["ID Contract Address"]
     self.ptm_contract_address = _conf_rpc["PTM Contract Address"]
     self.pgm_contract_address = _conf_rpc["PGM Contract Address"]
     # Network ID
     self.nid = int(_conf_rpc["Network ID"])
    def 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)
Пример #18
0
    def __init__(self):
        self.handlers = [
            self._set_revision,
            self._update_governance_score,
            self._set_step_cost,
        ]
        self.revision = 0
        self.gs_version = "0.0.0"

        self.key_wallet = KeyWallet.load(bytes.fromhex(TEST1_PRIVATE_KEY))
        self.preps = []
        for prep in self.PREPS:
            self.preps.append(KeyWallet.load(prep))
        uri, version = uri_parser("http://127.0.0.1:9000/api/v3")
        self.icon_service = IconService(HTTPProvider(uri, version))
 def setUp(self):
     super().setUp()
     self.contracts = {}
     self.contracts['sicx1'] = "cx20fa65cffc720db31e78fba6db5d58f58babd933"
     self.contracts['staking1'] = "cx25c39ed0d27853e44af8ab2739d6af832f35d533"
     self.contracts['staking2'] = "cx8b250e76bc919f73068571c26cadecde69e63b46"
     self.contracts['staking3'] = "cx3502e9af253098d187578ca826fe71032f116e47"
     # WARNING: ICON service emulation is not working with IISS.
     # You can stake and delegate but can't get any I-Score for reward.
     # If you want to test IISS stuff correctly, set self.icon_service and send requests to the network
     self.icon_service = IconService(HTTPProvider(self.TEST_HTTP_ENDPOINT_URI_V3))
     private2="093f12dba9dc75da81ecafc88de73ef9b311b555939aeb5a875dc6ad8feef424"
     private3="167f6ec1694ab63243efdce98f6f6bfdcef0575cefbb86ffe3826f8373f12b85"
     self._test2 = KeyWallet.load(bytes.fromhex(private2))
     self._test3 = KeyWallet.load(bytes.fromhex(private3))
Пример #20
0
 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))
Пример #21
0
def get_icon_service(session):
    if not "nid" in session:
        session["nid"] = 0  # Mainnet

    nid = session["nid"]
    return IconService(
        HTTPProvider(constants.NETWORK_ENDPOINTS[nid]['url'] + "/api/v3"))
    def call(conf):
        """Request icx_call

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

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

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

        response = call_with_logger(icon_service, call, uri)

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

        return response
Пример #23
0
    def process_call(self, call: Call, network: IconService = None):
        if self._network_only and network is None:
            raise URLException("Set network URL")

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

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

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

        return response
Пример #24
0
    def get_txresults(self, network: IconService, tx_hashes: list) -> list:
        tx_results: list = []

        for h in tx_hashes:
            tx_result = network.get_transaction_result(h)
            tx_results.append(tx_result)
        return tx_results
    def lastblock(self, conf):
        """Query last block

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

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

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

        return response
Пример #26
0
def create_icon_service(url: str) -> IconService:
    url: str = get_url(url)
    result: 'ParseResult' = urlparse(url)
    base_url: str = f"{result.scheme}://{result.netloc}"

    icon_service = IconService(HTTPProvider(base_url, 3))

    return icon_service
Пример #27
0
    def process_transaction(self, request: SignedTransaction,
                            network: IconService = None,
                            block_confirm_interval: int = tbears_server_config[TbConf.BLOCK_CONFIRM_INTERVAL]) -> dict:
        try:
            if network is not None:
                # Send the transaction to network
                tx_hash = network.send_transaction(request)
                sleep(block_confirm_interval)
                # Get transaction result
                tx_result = network.get_transaction_result(tx_hash)
            else:
                # process the transaction in local
                tx_result = self._process_transaction_in_local(request.signed_transaction_dict)
        except IconServiceBaseException as e:
            tx_result = e.message

        return tx_result
Пример #28
0
def get_block_range_for_date(provider_uri, date, output):
    """Outputs start and end blocks for given date."""
    svc = IconService(HTTPProvider(provider_uri))
    icx_service = IcxService(svc)

    start_block, end_block = icx_service.get_block_range_for_date(date)

    with smart_open(output, "w") as output_file:
        output_file.write("{},{}\n".format(start_block, end_block))
Пример #29
0
 def process_transaction_bulk_without_txresult(
         self, requests: list, network: IconService) -> list:
     tx_hashes: list = []
     for req in requests:
         # Send the transaction to network
         tx_hashes.append(network.send_transaction(req))
     if self._block_confirm_interval > 0:
         sleep(self._block_confirm_interval)
     return tx_hashes
Пример #30
0
    def process_confirm_block_tx(self, network: IconService):
        # build message tx
        transaction = TransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to("hx0000000000000000000000000000000000000000") \
            .value(0) \
            .step_limit(10_000_000_000) \
            .nonce(0) \
            .build()

        # signing message tx
        request = SignedTransaction(transaction, self._test1)

        network.send_transaction(request)
        if self._block_confirm_interval > 0:
            sleep(self._block_confirm_interval)
        else:
            sleep(self._network_delay)
Пример #31
0
 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))
Пример #32
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)