def _deploy_score(self, to: str = SCORE_INSTALL_ADDRESS) -> dict:
        # Generates an instance of transaction for deploying 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.SCORE_PROJECT)) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)

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

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

        return tx_result
Example #2
0
    def setUpClass(cls):
        super().setUpClass()

        param = {"init_supply": 10000}
        deploy_transaction = DeployTransactionBuilder() \
            .from_(cls.setting["from"]) \
            .to(cls.setting["to_install"]) \
            .step_limit(cls.setting["step_limit"]) \
            .nid(cls.setting["nid"]) \
            .nonce(cls.setting["nonce"]) \
            .content_type(cls.setting["content_type"]) \
            .content(cls.setting["content_install"]) \
            .params(param) \
            .version(3) \
            .build()

        # Test install SCORE : Sends transaction which makes the SCORE install correctly
        signed_transaction_dict = SignedTransaction(deploy_transaction,
                                                    cls.wallet)
        tx_result = cls.icon_service.send_transaction(signed_transaction_dict)

        sleep(2)

        cls.tx_hash = tx_result
Example #3
0
def main():
    cmd_args = sys.argv[1:]
    parser = get_parser()

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

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

            register_fee: int = 2000 * 10 ** 18
            tx = CallTransactionBuilder(). \
                from_(wallet.get_address()). \
                to(ZERO_ADDRESS). \
                step_limit(step_limit). \
                value(register_fee). \
                nid(nid). \
                nonce(100). \
                method("registerPRep"). \
                params(reg_info). \
                build()
            signed_data = SignedTransaction(tx, wallet)
            result = icon_service.send_transaction(signed_data)
        elif command == 'unregister':
            wallet = get_wallet(args)
            params = {}
            if args.get('address'):
                params['address'] = args['address']
            tx = CallTransactionBuilder().from_(wallet.get_address()).to(ZERO_ADDRESS). \
                step_limit(step_limit).nid(nid).nonce(100).method("unregisterPRep").\
                params(params).value(0).build()
            signed_data = SignedTransaction(tx, wallet)
            result = icon_service.send_transaction(signed_data)
        elif command == 'preps':
            json_path = args.get('json')
            if json_path is not None:
                with open(json_path, mode='r') as prep_info:
                    params = json.load(prep_info)
            else:
                params = {}
            call_data = CallBuilder(from_=f"hx{'0'*40}", to=ZERO_ADDRESS,
                                    method="getPReps").params(params).build()
            result = icon_service.call(call_data)
        else:
            print('unknown command')
            sys.exit(2)
        print('result : ', result)
        return 0
    except BaseException as e:
        print(e)
        sys.exit(3)
    def test_transfer_from_approved(self):

        # Mint an NFT token first via 'mint'
        params = {'_to': self._test1.get_address(), '_tokenId': 1}
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(100_000_000) \
            .method("mint") \
            .params(params) \
            .build()

        signed_transaction = SignedTransaction(transaction, self._test1)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])

        # Approve token operation to new wallet via 'approve'
        params = {'_to': self._wallet_array[0].get_address(), '_tokenId': 1}
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(100_000_000) \
            .method("approve") \
            .params(params) \
            .build()

        signed_transaction = SignedTransaction(transaction, self._test1)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])

        # Check approval of token 1 via 'getApproval'
        # owner of token 1 should be self._test1
        # approvee of token 1 should be self._wallet_array[0]

        params = {"_tokenId": 1}
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("getApproved") \
            .params(params) \
            .build()

        response = self.process_call(call, self.icon_service)
        self.assertEqual(response, self._wallet_array[0].get_address())

        # Transfer ownership of token 1 from self._test1 to self._wallet_array[1] by its operator approvee self._wall_array[0] using 'transferFrom'
        params = {
            '_from': self._test1.get_address(),
            '_to': self._wallet_array[1].get_address(),
            '_tokenId': 1
        }
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(100_000_000) \
            .method("transferFrom") \
            .params(params) \
            .build()

        signed_transaction = SignedTransaction(transaction, self._test1)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])

        # Check new ownership of token 1, expected to be self._wallet_array[1]
        params = {"_tokenId": 1}
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("ownerOf") \
            .params(params) \
            .build()

        response = self.process_call(call, self.icon_service)
        self.assertEqual(response, self._wallet_array[1].get_address())

        # Check token 1's new approved operator, expected zero address
        params = {"_tokenId": 1}
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("getApproved") \
            .params(params) \
            .build()

        response = self.process_call(call, self.icon_service)
        self.assertEqual(
            response, str(Address.from_prefix_and_int(AddressPrefix.EOA, 0)))

        # Check token count of self._test1, expected 0
        params = {"_owner": self._test1.get_address()}
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("balanceOf") \
            .params(params) \
            .build()

        response = self.process_call(call, self.icon_service)
        self.assertEqual(response, hex(0))

        # Last we burn the token from the new owner self._wallet_array[1]
        params = {
            "_tokenId": 1,
        }
        transaction = CallTransactionBuilder() \
            .from_(self._wallet_array[1].get_address()) \
            .to(self._score_address) \
            .step_limit(100_000_000) \
            .method("burn") \
            .params(params) \
            .build()

        signed_transaction = SignedTransaction(transaction,
                                               self._wallet_array[1])
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])

        # Check owner of token 1, expect invalid owner (zero address)
        params = {"_tokenId": 1}
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("ownerOf") \
            .params(params) \
            .build()

        with self.assertRaises(IconScoreException) as e:
            self.process_call(call, self.icon_service)
        self.assertEqual(e.exception.code, 32)
        self.assertEqual(e.exception.message,
                         "Invalid _tokenId. NFT is burned")
Example #5
0
    def test_transaction(self):
        self.logger.info('Start transfer transaction...')

        _user_wallet = self._wallet_array[1]
        _remote_wallet = self._wallet_array[2]
        _to = self._wallet_array[3]

        self._transfer_token(self._test1, _user_wallet, True)
        self._transfer_token(self._test1, _remote_wallet, True)
        self._transfer_token(self._test1, _to, True)
        #self._transfer_token(_remote_wallet, self._test1, False)

        response = self._call_balance(_user_wallet.get_address())
        self.logger.info("BALANCE [%s] : %s" %
                         (_user_wallet.get_address(), int(response, 16)))
        response = self._call_balance(_remote_wallet.get_address())
        self.logger.info("BALANCE [%s] : %s" %
                         (_remote_wallet.get_address(), int(response, 16)))
        response = self._call_balance(_to.get_address())
        self.logger.info("BALANCE [%s] : %s" %
                         (_to.get_address(), int(response, 16)))

        self.logger.info('Token Transfer Transaction Build ...')
        value = 100
        params = {
            '_from': _user_wallet.get_address(),
            '_to': _to.get_address(),
            '_value': value
        }
        transaction = CallTransactionBuilder() \
            .from_(_user_wallet.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transfer") \
            .params(params) \
            .build()
        signedTransaction = SignedTransaction(transaction, _user_wallet)

        data = json.dumps(transaction.to_dict(),
                          sort_keys=True,
                          indent=4,
                          separators=(',', ': '))
        self.logger.debug(f'Inner TX Data : {data}')

        data = json.dumps(signedTransaction.signed_transaction_dict,
                          sort_keys=True,
                          indent=4,
                          separators=(',', ': '))
        self.logger.debug(f'Inner TX Signed Data : {data}')

        self.logger.info('Remote Excute Transaction Build ...')
        params = {
            '_data': f'{signedTransaction.signed_transaction_dict}'.encode()
        }
        transaction = CallTransactionBuilder() \
            .from_(_remote_wallet.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("remotetx") \
            .params(params) \
            .build()
        signed_transaction = SignedTransaction(transaction, _remote_wallet)

        self.logger.info('Excute Transaction ...')
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)

        self.logger.debug('TX RESULT : %s' % tx_result)

        response = self._call_balance(_user_wallet.get_address())
        self.logger.info("BALANCE [%s] : %s" %
                         (_user_wallet.get_address(), int(response, 16)))
        response = self._call_balance(_remote_wallet.get_address())
        self.logger.info("BALANCE [%s] : %s" %
                         (_remote_wallet.get_address(), int(response, 16)))
        response = self._call_balance(_to.get_address())
        self.logger.info("BALANCE [%s] : %s" %
                         (_to.get_address(), int(response, 16)))
    def test_remove_blacklist_by_owner(self):
        print('------ Remove Blacklist by owner start -----')
        # Make params of add_blacklist method

        to = self.non_owner_wallet.get_address()
        value = 100
        params = {
            'addr': to,
        }

        # Generates an instance of transaction for calling method in SCORE.
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("add_blacklist") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)

        # Sends the transaction to the network
        print('Add blacklist by owner', 'From:', self._test1.get_address(),
              'Address:', to)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])

        # Checkwhitelist
        params = {'addr': to}
        # Generates a call instance using the CallBuilder
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("check_blacklist") \
            .params(params) \
            .build()

        # Sends the call request
        response = self.process_call(call, self.icon_service)

        print('BlackList status of ', to, 'Status:', response)

        params = {
            'addr': to,
        }

        # Generates an instance of transaction for calling method in SCORE.
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("remove_blacklist") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)

        # Sends the transaction to the network
        print('Remove blacklist by owner', 'From:', self._test1.get_address(),
              'Address:', to)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])
        # Checkwhitelist
        params = {'addr': to}
        # Generates a call instance using the CallBuilder
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("check_blacklist") \
            .params(params) \
            .build()

        # Sends the call request
        response = self.process_call(call, self.icon_service)
        print('BlackList status of ', to, 'Status:', response)

        to = self._wallet_array[0].get_address()
        value = 100
        params = {
            '_to': to,
            '_value': value,
        }
        # Generates an instance of transaction for calling method in SCORE.
        transaction = CallTransactionBuilder() \
            .from_(self.non_owner_wallet.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transfer") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction,
                                               self.non_owner_wallet)

        # Sends the transaction to the network
        print('Transfer Transaction', value, 'From:',
              self.non_owner_wallet.get_address(), 'To:', to)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertEqual(tx_result['status'], 0)
        self.assertFalse(tx_result['failure'] is None)
        print('\t(Transaction Reverted)', tx_result['failure']['message'])

        print('------ Remove Blacklist by owner  end -----')
Example #7
0
          wallet1.get_private_key())

    # Enters transaction information
    deploy_transaction = DeployTransactionBuilder()\
        .from_(wallet1.get_address())\
        .to(SCORE_INSTALL_ADDRESS) \
        .step_limit(get_max_step_limit())\
        .nid(3)\
        .nonce(3)\
        .content_type("application/zip")\
        .content(install_content_bytes)\
        .version(3)\
        .build()

    # Returns the signed transaction object having a signature
    signed_transaction_dict = SignedTransaction(deploy_transaction, wallet1)

    # Sends the transaction
    tx_hash = icon_service.send_transaction(signed_transaction_dict)
    print("txHash: ", tx_hash)

    @retry(JSONRPCException, tries=10, delay=1, back_off=2)
    def get_tx_result():
        # Returns the result of a transaction by transaction hash
        tx_result = icon_service.get_transaction_result(tx_hash)
        print("transaction status(1:success, 0:failure): ",
              tx_result["status"])
        print("score address: ", tx_result["scoreAddress"])
        print("waiting a second for accepting score...\n")

    get_tx_result()
Example #8
0
header = "This timestamp of " + str(url) + " was taken at " + str(utc_datetime) + " UTC." + "\n\n"
header_hex = header.encode("utf-8").hex()
tx_message = header_hex + html_hex

#Calculate transaction message length
tx_message_length = len(tx_message)
if tx_message_length > 509950:
	print("Sorry, this HTML page is too large to timestamp in an ICX transaction.")
	exit()
elif tx_message_length <= 509950:
	keystore_location = input("What is the file path of your keystore file? ")
	keystore_password = input("What is your keystore password? ")
	keystore_location_str = keystore_location.rstrip()
	keystore_password_str = keystore_password.rstrip()

#Create ICX transaction
wallet = KeyWallet.load(keystore_location_str, keystore_password_str)
transaction = MessageTransactionBuilder()\
	.from_(wallet.get_address())\
	.to(wallet.get_address())\
	.step_limit(100000000)\
	.data("0x" + tx_message)\
	.nid(1)\
	.build()
icon_service = IconService(HTTPProvider("https://wallet.icon.foundation/api/v3"))
signed_transaction = SignedTransaction(transaction, wallet)
tx_hash = icon_service.send_transaction(signed_transaction)

#Print success message with link to transaction on ICON tracker
print("\nSuccess! View your timestamped HTML at the URL below.\nhttps://tracker.icon.foundation/transaction/" + tx_hash + "\n")
    def test_deploy_integrate(self):
        """
        Integrate-test for deploying SCORE

        1. Installs a SCORE named SampleToken.
        2. Checks if making an instance of installing SCORE transaction correctly.
        *** It needs about 1 sec to build consensus.
        3. Sends a call Transaction which calls a method `acceptScore` to make the new SCORE active
        4. Updates the SCORE having added methods
        5. Checks if making an instance of updating SCORE transaction correctly.
        *** It needs about 1 sec to build consensus.
        6. Sends a call transaction which calls a method `acceptScore` to make the updated SCORE active
        7. Calls a querying method `hello` of the updated SCORE
        8. Calls a querying method `total_supply` of the updated SCORE
        9. Calls a invoking method `transfer` of the updated SCORE
        """
        # Test install SCORE : Checks if making an instance of deploy transaction correctly
        param = {"init_supply": 10000}
        deploy_transaction = DeployTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(self.setting["to_install"]) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .content_type(self.setting["content_type"]) \
            .content(self.setting["content_install"]) \
            .params(param) \
            .version(3) \
            .build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(
            deploy_transaction)
        self.assertTrue(is_deploy_transaction(tx_dict))

        # Test install SCORE : Sends transaction which makes the SCORE install correctly
        signed_transaction_dict = SignedTransaction(deploy_transaction,
                                                    self.wallet)
        result_install = self.icon_service.send_transaction(
            signed_transaction_dict)
        self.assertTrue(is_T_HASH(result_install))

        # Test install SCORE : Sends a call transaction calling a method `acceptScore` to make the SCORE active
        params = {"txHash": result_install}
        call_transaction = CallTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(self.setting["to_governance"]) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .method("acceptScore") \
            .params(params) \
            .build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(
            call_transaction)
        self.assertTrue(is_call_transaction(tx_dict))

        signed_transaction_dict = SignedTransaction(call_transaction,
                                                    self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        # Test update SCORE : Checks if making an instance of deploy transaction correctly
        sleep(2)
        installed_score_address = self.icon_service.get_transaction_result(
            result_install)["scoreAddress"]
        deploy_transaction = DeployTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(installed_score_address) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .content_type(self.setting["content_type"]) \
            .content(self.setting["content_update"]) \
            .build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(
            deploy_transaction)
        self.assertTrue(is_deploy_transaction(tx_dict))

        # Test update SCORE : Sends transaction which makes the SCORE update correctly
        signed_transaction_dict = SignedTransaction(deploy_transaction,
                                                    self.wallet)
        result_update = self.icon_service.send_transaction(
            signed_transaction_dict)
        self.assertTrue(is_T_HASH(result_update))

        # Test update SCORE : Sends a call transaction calling a method `acceptScore` to make the SCORE active
        params = {"txHash": result_update}

        call_transaction = CallTransactionBuilder().from_(self.setting["from"]).to(self.setting["to_governance"]) \
            .step_limit(self.setting["step_limit"]).nid(self.setting["nid"]).method("acceptScore").params(
            params).build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(
            call_transaction)
        self.assertTrue(is_call_transaction(tx_dict))

        signed_transaction_dict = SignedTransaction(call_transaction,
                                                    self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        # Test update SCORE : Calls a method `hello` of the updated SCORE
        sleep(2)
        call_transaction = CallBuilder().from_(self.setting["from"]).to(installed_score_address) \
            .method("hello").build()
        result = self.icon_service.call(call_transaction)
        self.assertEqual(result, "Hello")

        # Test update SCORE : Calls a method `total_supply` of the updated SCORE
        call_transaction = CallBuilder().from_(self.setting["from"]).to(installed_score_address) \
            .method("total_supply").build()
        result = self.icon_service.call(call_transaction)
        self.assertEqual(result, "0x0")

        # Test call a invoking method of SCORE
        value = "0x1"
        params = {
            "addr_to": "hxab2d8215eab14bc6bdd8bfb2c8151257032ecd8b",
            "value": value
        }
        call_transaction = CallTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(installed_score_address) \
            .method("transfer") \
            .params(params) \
            .nid(self.setting["nid"]) \
            .step_limit(self.setting["step_limit"]) \
            .build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(
            call_transaction)
        self.assertTrue(is_call_transaction(tx_dict))

        signed_transaction_dict = SignedTransaction(call_transaction,
                                                    self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))
Example #10
0
    def test_transfer(self):

        # When having an optional property, nonce
        icx_transaction = TransactionBuilder()\
            .from_(self.setting["from"])\
            .to(self.setting["to"]) \
            .value(self.setting["value"])\
            .step_limit(self.setting["step_limit"])\
            .nid(3) \
            .nonce(self.setting["nonce"])\
            .version(3) \
            .build()
        tx_dict = SignedTransaction.to_dict(icx_transaction)
        self.assertTrue(is_icx_transaction(tx_dict))

        signed_transaction_dict = SignedTransaction(icx_transaction,
                                                    self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        # When not having an optional property, nonce
        icx_transaction = TransactionBuilder().from_(self.setting["from"]).to(self.setting["to"]) \
            .value(self.setting["value"]).step_limit(self.setting["step_limit"]).nid(self.setting["nid"]).build()
        tx_dict = SignedTransaction.to_dict(icx_transaction)
        self.assertTrue(is_icx_transaction(tx_dict))

        signed_transaction_dict = SignedTransaction(icx_transaction,
                                                    self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        # When value is wrong prefixed with '0x'
        wrong_value = "0x34330000000"
        icx_transaction = TransactionBuilder().from_(self.setting["from"]).to(self.setting["to"]) \
            .value(wrong_value).step_limit(self.setting["step_limit"]).nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]).build()
        self.assertRaises(DataTypeException, SignedTransaction,
                          icx_transaction, self.wallet)

        # When value is valid which type is int
        wrong_value = 34330000000
        icx_transaction = TransactionBuilder().from_(self.setting["from"]).to(self.setting["to"]) \
            .value(wrong_value).step_limit(self.setting["step_limit"]).nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]).build()
        signed_transaction_dict = SignedTransaction(icx_transaction,
                                                    self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        # When address is wrong
        wrong_address = "hx5bfdb090f43a808005ffc27c25b213145e8"
        icx_transaction = TransactionBuilder().from_(self.setting["from"]).to(wrong_address) \
            .value(self.setting["value"]).step_limit(self.setting["step_limit"]).nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]).build()
        signed_transaction_dict = SignedTransaction(icx_transaction,
                                                    self.wallet)
        self.assertRaises(JSONRPCException, self.icon_service.send_transaction,
                          signed_transaction_dict)

        # When not having a required property, nid
        icx_transaction = TransactionBuilder().from_(self.setting["from"]).to(self.setting["to"]) \
            .value(self.setting["value"]).step_limit(self.setting["step_limit"]) \
            .nonce(self.setting["nonce"]).build()
        signed_transaction_dict = SignedTransaction(icx_transaction,
                                                    self.wallet)
        self.assertRaises(JSONRPCException, self.icon_service.send_transaction,
                          signed_transaction_dict)

        # When a sending address is wrong - not the wallet's address
        wrong_address = "hx5bfdb090f43a808005ffc27c25b213145e80b7cd"
        icx_transaction = TransactionBuilder().from_(wrong_address).to(self.setting["to"]) \
            .value(self.setting["value"]).step_limit(self.setting["step_limit"]).nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]).build()
        signed_transaction_dict = SignedTransaction(icx_transaction,
                                                    self.wallet)
        self.assertRaises(JSONRPCException, self.icon_service.send_transaction,
                          signed_transaction_dict)
Example #11
0
    def deploy(self, conf: dict) -> dict:
        """Deploy SCORE on the server.
        :param conf: deploy command configuration
        """
        # check keystore, and get password from user's terminal input
        password = conf.get('password', None)
        password = self._check_deploy(conf, password)

        if conf['mode'] == 'install':
            score_address = f'cx{"0"*40}'
        else:
            score_address = conf['to']

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

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

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

        # make zip and convert to hexadecimal string data (start with 0x) and return
        content = gen_deploy_data_content(conf['project'])

        deploy_transaction = DeployTransactionBuilder() \
            .from_(from_) \
            .to(score_address) \
            .nid(convert_hex_str_to_int(conf['nid'])) \
            .content_type("application/zip") \
            .content(content) \
            .params(conf.get('scoreParams', {})) \
            .build()

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

        deploy_transaction.step_limit = step_limit

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

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

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

        if 'error' in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print('Send deploy request successfully.')
            tx_hash = response['result']
            print(
                f'If you want to check SCORE deployed successfully, execute txresult command'
            )
            print(f"transaction hash: {tx_hash}")

        return response
Example #12
0
    def test_deposit_add_and_withdraw(self):
        # Test install SCORE : Checks if making an instance of deploy transaction correctly
        param = {"init_supply": 10000}
        deploy_transaction = DeployTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(self.setting["to_install"]) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .content_type(self.setting["content_type"]) \
            .content(self.setting["content_install"]) \
            .params(param) \
            .version(3) \
            .build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(
            deploy_transaction)
        self.assertTrue(is_deploy_transaction(tx_dict))

        # Test install SCORE : Sends transaction which makes the SCORE install correctly
        signed_transaction_dict = SignedTransaction(deploy_transaction,
                                                    self.wallet)
        result_install = self.icon_service.send_transaction(
            signed_transaction_dict)
        self.assertTrue(is_T_HASH(result_install))

        sleep(2)
        installed_score_address = self.icon_service.get_transaction_result(
            result_install)["scoreAddress"]

        _DEPOSIT_AMOUNT = 5000 * (10**18)
        deposit_transaction_of_add_0: DepositTransaction = DepositTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(installed_score_address) \
            .value(_DEPOSIT_AMOUNT) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .action("add") \
            .build()

        # Checks if sending transaction correctly
        signed_transaction_dict = SignedTransaction(
            deposit_transaction_of_add_0, self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        sleep(2)
        self.assertEqual(
            self.icon_service.get_transaction_result(result)["status"], 1)

        # transaction instance for withdraw action
        deposit_transaction_of_withdraw: DepositTransaction = DepositTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(installed_score_address) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .id(result) \
            .action("withdraw") \
            .build()

        signed_transaction_dict = SignedTransaction(
            deposit_transaction_of_withdraw, self.wallet)
        result = self.icon_service.send_transaction(signed_transaction_dict)
        self.assertTrue(is_T_HASH(result))

        sleep(2)
        self.assertEqual(
            self.icon_service.get_transaction_result(result)["status"], 1)
    def test_auction_sell(self):
        ################### TEST_TOKEN ADD ###################
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("init_add") \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        self.process_transaction(signed_transaction, self.icon_service)

        params = {"_playerId": 1, "_price": 1}

        transaction = CallTransactionBuilder() \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("auction_sell") \
            .params(params) \
            .build()
        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        response = self.process_transaction(signed_transaction,
                                            self.icon_service)
        print("auction_sell : ", response)

        params = {"_tokenId": 0}

        call_balanceOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("getApproved") \
            .params(params) \
            .build()

        response = self.process_call(call_balanceOf, self.icon_service)
        print("getApproved : ", response)

        params = {
            "_to": "hx08711b77e894c3509c78efbf9b62a85a4354c8df",
            "_tokenId": 0
        }

        ################ buy 성공하면 스코어가 바이한테 approve하기
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("approve") \
            .params(params) \
            .build()
        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        response = self.process_transaction(signed_transaction,
                                            self.icon_service)
        print("approve2 : ", response)

        params = {"_tokenId": 0}

        call_balanceOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("getApproved") \
            .params(params) \
            .build()

        response = self.process_call(call_balanceOf, self.icon_service)
        print("getApproved : ", response)

        # 구매할때 메소드 따로 처리하고
        params = {"_playerId": 1}
        transaction = CallTransactionBuilder() \
            .from_("hx08711b77e894c3509c78efbf9b62a85a4354c8df") \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("auction_buy") \
            .params(params) \
            .build()
        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        response = self.process_transaction(signed_transaction,
                                            self.icon_service)
        print("auction_buy : ", response)

        params = {
            "_from": "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb",
            "_to": "hx08711b77e894c3509c78efbf9b62a85a4354c8df",
            "_tokenId": 0
        }
        transaction = CallTransactionBuilder() \
            .from_(self._score_address) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transferFrom") \
            .params(params) \
            .build()
        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        response = self.process_transaction(signed_transaction,
                                            self.icon_service)
        print("transferFrom : ", response)

        params = {"_tokenId": 0}

        call_balanceOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("ownerOf") \
            .params(params) \
            .build()

        response = self.process_call(call_balanceOf, self.icon_service)
        print("ownerOf : ", response)
    def test_transferFrom(self):
        ################### TEST_TOKEN ADD ###################
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("init_add") \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        self.process_transaction(signed_transaction, self.icon_service)
        ####################################################

        ################### TEST BALANCEOF ###################
        params = {
            "_owner": "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb",
        }

        call_ownerOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("balanceOf") \
            .params(params) \
            .build()

        response = self.process_call(call_ownerOf, self.icon_service)
        print("balanceOf : ", response)
        ####################################################

        params = {
            "_to": "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb",
            "_tokenId": 2,
        }

        transaction = CallTransactionBuilder() \
            .from_("hx08711b77e894c3509c78efbf9b62a85a4354c8df") \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("approve") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        self.process_transaction(signed_transaction, self.icon_service)
        ####################################################

        ################### TEST TRANSFERFROM ###################
        params = {
            "_from": "hx08711b77e894c3509c78efbf9b62a85a4354c8df",
            "_to": "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb",
            "_tokenId": 2,
        }

        transaction = CallTransactionBuilder() \
            .from_("hx79e7f88e6186e72d86a1b3f1c4e29bd4ae00ff53") \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transferFrom") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        self.process_transaction(signed_transaction, self.icon_service)
        ####################################################

        ################### TEST TRANSFER ###################
        params = {
            "_tokenId": 1,
        }

        call_ownerOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("ownerOf") \
            .params(params) \
            .build()

        response = self.process_call(call_ownerOf, self.icon_service)
        print("token_owner : ", response)
        ####################################################

        ################### TEST BALANCEOF ###################
        params = {
            "_owner": "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb",
        }

        call_ownerOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("balanceOf") \
            .params(params) \
            .build()

        response = self.process_call(call_ownerOf, self.icon_service)
        print("balanceOf : ", response)
    def test_approve(self):
        ################### TEST_TOKEN ADD ###################
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("init_add") \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        self.process_transaction(signed_transaction, self.icon_service)

        params = {
            "_to": "hx08711b77e894c3509c78efbf9b62a85a4354c8df",
            "_tokenId": 1,
        }

        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("approve") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)
        # print("signed_transaction: ", signed_transaction)
        self.process_transaction(signed_transaction, self.icon_service)

        params = {
            "_tokenId": 1,
        }

        call_ownerOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("getApproved") \
            .params(params) \
            .build()

        response = self.process_call(call_ownerOf, self.icon_service)
        print("getApproved : ", response)

        params = {
            "_owner": self._test1.get_address()
            # "_owner":"hx08711b77e894c3509c78efbf9b62a85a4354c8df"
        }


        call_balanceOf = CallBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("balanceOf") \
            .params(params) \
            .build()
        response = self.process_call(call_balanceOf, self.icon_service)
        print("balanceOf : ", response)
Example #16
0
def dice_bot(next_bet, loss_streak, bet_count):
    # Checks for integer or float bet amount and converts it
    if isinstance(next_bet, int):
        next_bet = int_to_bigint(next_bet)

    else:
        next_bet = float_value(next_bet)

    # Params for the contract call. You can write a lucky phrase in user_seed if you want to.
    params = {
        "upper": hex(upper),
        "lower": hex(lower),
        "user_seed": ""
    }

    transaction = CallTransactionBuilder() \
        .from_(wallet.get_address()) \
        .to(testnet) \
        .step_limit(40000000) \
        .value(next_bet) \
        .nid(nid) \
        .nonce(50) \
        .method("call_bet") \
        .params(params) \
        .build()
    # Signs and sends the tx to the contract
    signed_transaction = SignedTransaction(transaction, wallet)
    tx_hash = icon_service.send_transaction(signed_transaction)

    # Important to put some delay to get the result of your bet. 4sec is enough but its better to put some bigger number
    time.sleep(wait_time)

    tx_result = icon_service.get_transaction_result(tx_hash)

    my_bet_range = tx_result["eventLogs"][3]["indexed"]
    my_bet_range = sorted([from_hex(dice) for dice in my_bet_range[2:]])
    bet_result = tx_result["eventLogs"][4]["indexed"]
    winning_number = from_hex(bet_result[2])
    # You can change the bet amounts after a loss streak or return to your base bet.
    bet_value = [0.2, 0.8, 1.6, 3.2]
    # A counter checks for number of lose streaks, changing the bet and reseting after a win.
    if lower <= winning_number <= upper:
        bet_count += 1
        loss_streak = 0
        print(
            f"\tWIN   \t\t\t\t{icx_balance:6.2f}\t\t\t\t{from_bigint(next_bet):5.2f}\t\t\t\t\t\t{winning_number:2}\
             \t\t\t{my_bet_range[0]:2}-{my_bet_range[1]:2}\t\t\t\t{bet_counter:4}\t\t\t{tx_hash}")
        next_bet = bet_value[0]

    else:
        loss_streak += 1
        bet_count += 1
        if loss_streak == 1:
            print(
                f"\tLOSS(x1)\t\t\t\t{icx_balance:6.2f}\t\t\t\t{from_bigint(next_bet):5.2f}\t\t\t\t\t\t{winning_number:2}\
             \t\t\t{my_bet_range[0]:2}-{my_bet_range[1]:2}\t\t\t\t{bet_counter:4}\t\t\t{tx_hash}")
            next_bet = bet_value[1]
        elif loss_streak == 2:
            print(
                f"\tLOSS(X2)\t\t\t{icx_balance:6.2f}\t\t\t\t{from_bigint(next_bet):5.2f}\t\t\t\t\t\t{winning_number:2}\
             \t\t\t{my_bet_range[0]:2}-{my_bet_range[1]:2}\t\t\t\t{bet_counter:4}\t\t\t{tx_hash}")
            next_bet = bet_value[2]
        elif loss_streak == 3:
            print(
                f"\tLOSS(X3)\t\t\t{icx_balance:6.2f}\t\t\t\t{from_bigint(next_bet):5.2f}\t\t\t\t\t\t{winning_number:2}\
             \t\t\t{my_bet_range[0]:2}-{my_bet_range[1]:2}\t\t\t{bet_counter:4}\t\t\t{tx_hash}")
            next_bet = bet_value[3]
        else:
            print("REKT : Bot exits")
            exit()

    return next_bet, loss_streak, bet_count
Example #17
0
    def _send_transaction(self, transaction) -> dict:
        signed_tx = SignedTransaction(transaction, self._wallet)
        tx_hash = self._icon_service.send_transaction(signed_tx)

        sleep(SLEEP_TIMER)
        return self.get_tx_result_by_hash(tx_hash)
class calltransaction_transaction_RT():
    #python 내에 calltransaction_transaction_RT 이라는 클래스를 선언해준다.
    start_time = time.time()
    #시작시간을 측정하기위해 만듦 start_time변수 안에 time함수를 사용하여 시간을 저장

    now = datetime.datetime.now()
    #now라는 변수안에 현재 날짜와 시간을 대입
    nowDate = now.strftime('%Y%m%d')
    #nowDate 현재 날짜를 구분하기위해 변수선언한후 now변수에 저장된 시간들을 갖고오는데 %년%월%일만 가져와서 저장
    nowTime = now.strftime('%H%M')
    #nowTime에 현재시각을 대입하기위해 %시간 %분을 대입해준다

    #DB에 들어가게 될 데이터 값으로 Local 타임존 값을 지정해 준다.
    localnow = datetime.datetime.now(timezone('Asia/Seoul'))
    localnowDate = localnow.strftime('%Y%m%d')

    html = requests.get('https://www.naver.com/').text
    #html이란 변수에 beautifulsoup을 사용하여 요청하여 얻어온다 naver를 text형식으로
    soup = BeautifulSoup(html, 'html.parser')
    #무엇을이 여기서 결정된다 soup에 beautifulsoup을 사용하여 html에 저장된 것을 parser해온다
    #parser란 구문분석이란 의미로 인터넷소스들을 끌어온다
    title_list = soup.select(
        '.PM_CL_realtimeKeyword_rolling span[class*=ah_k]')
    #title_list안에 soup에 저장된 값들중에 select 선택하겠다. ()안의 값들만 골라오겠다
    #()안의 값은 네이버소스에서 직접검색하면 찾아볼수 있다.

    Machined_title_list = list()
    #Machined_Google_title_list라는 리스트를 선언해준다
    for idx, title in enumerate(title_list, 1):
        Machined_title_list.append(title.text)
    #for문에 idx(순서)와 title(새로운변수)을 돌리는데 enumerate(숫자를세다) title_list를
    #그리고 그값을 Machined_Google_title_list에 하나씩 append}(리스트에 삽입시킨다 title.text를)
    naver_list = Machined_title_list[0:5]
    #네이버 순위를 5개만 갖고오기 위한 작업
    print(naver_list)

    params = {
        "_date": nowDate,
        "_time": nowTime,
        "_div": 'NAVER',
        "_value": json.dumps(naver_list)
    }
    #params 란 스코어와 sdk관계에서 값들을 넘겨줄 매게변수를 설정해주는 값을 정해줄 수 있는 것 이라고 생각하면쉽다
    #그렇기에 키값으로 들어갈 것들과 위에서 리스트로 정리할 값을 json 형식으로 묶어서 보낸다
    transaction = CallTransactionBuilder() \
        .from_(_keystore_address) \
        .to(_score_address) \
        .step_limit(10_000_000) \
        .nid(1) \
        .nonce(100) \
        .method("transaction_RT") \
        .params(params) \
        .build()
    #스코어와 연동시킬 CallTransactionBuilder()를 transaction에 넣을건데 그밑의 값들을 넣을 것이다 라는 의미이다.
    '''
	
	    from_ : 거래를 수행하는 지갑 주소. 기본 주소는 귀하의 계정 주소입니다.
	    to : 거래를 받기 위해 동전이나 SCORE 주소를받는 지갑 주소
	    step_limit : 트랜잭션 처리를위한 최대 단계 값
	    nid : 네트워크 ID. 값을 설정하지 않으면 기본 nid는 1입니다. (주망 1 등)
	    nonce : 트랜잭션 해시 충돌을 방지하는 데 사용되는 임의의 숫자
	    method : SCORE의 메소드
	    params : SCORE 메서드에 전달 된 매개 변수입니다. 매개 변수의 데이터 유형은 dict 여야합니다 . (선택 과목)
	    버전 : 프로토콜 버전 (V3의 경우 3). 값을 설정하지 않은 경우 기본 버전은 3입니다.
	    timestamp : 트랜잭션 생성 시간. 시간 소인은 마이크로 초입니다. 값을 설정하지 않으면 기본 타임 스탬프가 설정됩니다.
	    Build : 호출 트랜잭션 객체를 반환합니다.
	'''

    #print(nowDate, nowTime, 'NAVER')
    signed_transaction = SignedTransaction(transaction, wallet)
    #SignedTransaction(transaction: Transaction, wallet: Wallet)
    #transaction : 아직 서명 필드가없는 트랜잭션 객체
    tx_hash = icon_service.send_transaction(signed_transaction)

    # print(tx_hash)
    time.sleep(5)
    # tx_result = icon_service.get_transaction_result(tx_hash)
    # print(tx_result['status'])
    #print("--- %s seconds ---" % (time.time() - start_time))

    #---------------------------------------------GOOGLE----------------------------------------
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('window-size=1920x1080')
    options.add_argument("disable-gpu")
    #위의 옵션들은 selenium을쓸때 아래에서 구글브라우저를 열때 자동으로 닫히게 해주는 옵션들이다 이외에 다른옵션들도 많다
    path = "/usr/local/bin/chromedriver"  #"/home/ubuntu/Downloads/chromedriver"
    #이전에 chromedriver을 압축해제한 곳의 경로를 path 변수에 저장시킨다
    driver = webdriver.Chrome(path, chrome_options=options)
    time.sleep(5)
    #dirver 안에 path라는 경로에 있는 크롬 웹드라이버를 대입
    driver.get(
        "https://trends.google.com/trends/trendingsearches/realtime?geo=US&category=all"
    )
    #driver.get("url") 구글 개발자모드안에 소스에서 xpath로 검색해오면 된다. 위 드라이브로 get 얻어오겠다 가로안의 url 의 값을
    time.sleep(5)

    req = driver.page_source
    #req안에 driver로 얻어온 page_source를 넣어준다

    soup = BeautifulSoup(req, 'html.parser')
    #soup안에 Beautifulsoup으로 (req에 저장된 값을 파싱시킨다 html.parser)

    title_list = soup.select('div > span:nth-child(1) > a')
    #셀레니움 드라이버 종료
    driver.quit()
    '''
	그리고 title_list에 soup안에 저장내용중에 select 선택해온다
	(div > span:nth-child(1) > a) 
	자신이 갖고오고 싶은 소스 값들을 개발자모드에서 selector 해오면
	해당값들이 복사되어 온다
	'''

    Temp_list = title_list[0:5]
    Machined_Google_title_list = list()

    for title in Temp_list:
        Machined_Google_title_list.append(title.text.strip())
    print(Machined_Google_title_list)
    params_G = {
        "_date": nowDate,
        "_time": nowTime,
        '_div': 'GOOGLE',
        "_value": json.dumps(Machined_Google_title_list)
    }
    transaction_G = CallTransactionBuilder() \
        .from_(_keystore_address) \
        .to(_score_address) \
        .step_limit(10_000_000) \
        .nid(1) \
        .nonce(100) \
        .method("transaction_RT") \
        .params(params_G) \
        .build()
    #print(nowDate, nowTime, 'GOOGLE')
    signed_transaction_G = SignedTransaction(transaction_G, wallet)
    tx_hash_G = icon_service.send_transaction(signed_transaction_G)
    #send_transaction(signed_transaction: SignedTransaction)
    #트랜잭션을 보냅니다.
    #print("--- %s seconds ---" % (time.time() - start_time))
    #------------time sleep-------------------------------------
    # print(tx_hash_G)
    # time.sleep(10)
    # tx_result_G = icon_service.get_transaction_result(tx_hash_G)
    # print(tx_result_G['status'])

    # ------------------------Google DB Con------------------------
    # MySQL Connection 연결
    conn = pymysql.connect(host='127.0.0.1',
                           user='******',
                           password='******',
                           db='Crawling_DB',
                           charset='utf8')

    #DB접근을 위한 기능을 객체화 한다, 뒤에 pymysql.cursors.DictCursor은 변수를 통해 동적으로 할당해주기 위한 옵션이다.
    curs = conn.cursor(pymysql.cursors.DictCursor)

    #5점 부터 1점까지 차례대로 점수를 부여하기 위해 b라는 변수 선언
    b = 5
    '''
        #누락값 DB 저장
	# 가지고온 현재 1등 데이터가 TOP20 테이블에 이미 존재하고 있는지 검사 (없다면 누락값을 의심해 볼 수 있음)
	# 가지고온 현재 1등 데이터를 check라는 변수에 할당한다.
	check = Machined_Google_title_list[0]
	#crawling_App_receive_google_data라는 테이블에서 key1 칼럼이 변수 nowDate 값과 일치하고 G_Word 칼럼이 check와 일치하는 값을 가지고 온다
	sql = "select * from crawling_App_receive_google_data where key1=%s and G_Word=%s"
	curs.execute(sql, (localnowDate, check))
	check_resuit = curs.fetchall()
	print(check_resuit)

	#만약 데이터가 테이블에 존재하지 않으면 missing_data테이블에 값을 입력해준다. (누락값으로 의심되는 값을 의미)
	if not check_resuit and int(nowTime) != 0:
	    sql = "INSERT INTO crawling_App_missing_data (key1,Word,type) VALUES(%s,%s,'G')"
	    curs.execute(sql, (localnowDate, check))
	    rows = curs.fetchall()
	    conn.commit()
	'''

    # 가져온 20개의 키워드 insert 또는 update
    # 첫번째 키워드 부터 스무번째 키워드 까지 순서대로 수행
    for a in Machined_Google_title_list:

        #insert할지 update할지 구분을 위해 검색된 단어의 점수 존재 여부를 체크하고, 몇점인지 확인한다.
        #crawling_App_receive_google_data라는 테이블에서 key1 칼럼이 변수 nowDate 값과 일치하고 G_Word 칼럼이 a와 일치하는 값의 G_Rating를 가져온다.
        #조건절에 nowDate 옵션을 주어서 현재 날짜에 있는 데이터로 범위를 제한한다.
        sql = "select G_Rating from crawling_App_receive_google_data where key1=%s and G_Word=%s"
        curs.execute(sql, (localnowDate, a))
        num = curs.fetchall()

        #만약 G_Word 값이 존재한다면
        if num:
            # print("already exist")
            #DB에서 가져온 데이터의 첫번째 키워드 부터 스무번째 키워드 까지 순서대로 수행
            #기존의 점수 값에서 점수를 더해주는 기능
            for x in num:
                d = list(x.values())
                k = int(d[0])
                k = k + b
                # 만약 a[0]값이 crawling_receive_google_data에 없으며 주의 메세지 출력

                #crawling_App_receive_google_data라는 테이블에서 G_Word 칼럼이 a와 일치하는 값의 G_Rating을 k변수로 업데이트 한다.
                sql = "UPDATE crawling_App_receive_google_data SET G_Rating=%s WHERE G_Word=%s"
                curs.execute(sql, (k, a))
                rows = curs.fetchall()
                conn.commit()

    #만약 G_Word 값이 존재하지 않는다면
        else:
            # print("New Input")
            #crawling_App_receive_google_data라는 테이블에서 새로운 레코드를 생성한다.(key1 : localnowDate, G_Word : a, G_Rating : b)
            sql = "INSERT INTO crawling_App_receive_google_data (key1,G_Word,G_Rating) VALUES(%s,%s,%s)"
            curs.execute(sql, (localnowDate, a, b))
            rows = curs.fetchall()
            conn.commit()
    #키워드 순위가 떨어지면 점수도 1점씩 작게 부여하기 위해서 b에서 1을 뺀다.
        b = b - 1

    # ------------------------Naver DB Con------------------------
    #5점 부터 1점까지 차례대로 점수를 부여하기 위해 b라는 변수 선언
    b = 5
    '''
        # 누락값 DB저장
	# 가지고온 현재 1등 데이터가 TOP20 테이블에 이미 존재하고 있는지 검사 (없다면 누락값을 의심해 볼 수 있음)
	# 가지고온 현재 1등 데이터를 check라는 변수에 할당한다.
	check = naver_list[0]
	#crawling_App_receive_naver_data라는 테이블에서 key1 칼럼이 변수 nowDate 값과 일치하고 N_Word 칼럼이 check와 일치하는 값을 가지고 온다
	sql = "select * from crawling_App_receive_naver_data where key1=%s and N_Word=%s"
	curs.execute(sql, (localnowDate, check))
	check_resuit = curs.fetchall()
	
	#만약 데이터가 테이블에 존재하지 않으면 missing_data테이블에 값을 입력해준다. (누락값으로 의심되는 값을 의미)
	if not check_resuit and int(nowTime) != 0 :
	    sql = "INSERT INTO crawling_App_missing_data (key1,Word,type) VALUES(%s,%s,'N')"
	    curs.execute(sql, (localnowDate, check))
	    rows = curs.fetchall()
	    conn.commit()
	'''

    # 가져온 20개의 키워드 insert 또는 update
    # 첫번째 키워드 부터 스무번째 키워드 까지 순서대로 수행
    for a in naver_list:

        #insert할지 update할지 구분을 위해 검색된 단어의 점수 존재 여부를 체크하고, 몇점인지 확인한다.
        #crawling_App_receive_naver_data라는 테이블에서 key1 칼럼이 변수 nowDate 값과 일치하고 N_Word 칼럼이 a와 일치하는 값의 N_Rating를 가져온다.
        #조건절에 nowDate 옵션을 주어서 현재 날짜에 있는 데이터로 범위를 제한한다.
        sql = "select N_Rating from crawling_App_receive_naver_data where key1=%s and N_Word=%s"
        curs.execute(sql, (localnowDate, a))
        num = curs.fetchall()

        #만약 N_Word 값이 존재한다면
        if num:
            #DB에서 가져온 데이터의 첫번째 키워드 부터 스무번째 키워드 까지 순서대로 수행
            #기존의 점수 값에서 점수를 더해주는 기능
            for x in num:
                d = list(x.values())
                k = int(d[0])
                k = k + b

                #crawling_App_receive_naver_data라는 테이블에서 N_Word 칼럼이 a와 일치하는 값의 N_Rating을 k변수로 업데이트 한다.
                sql = "UPDATE crawling_App_receive_naver_data SET N_Rating=%s WHERE N_Word=%s"
                curs.execute(sql, (k, a))
                rows = curs.fetchall()
                conn.commit()

    #만약 N_Word 값이 존재하지 않는다면
        else:
            #crawling_App_receive_naver_data라는 테이블에서 새로운 레코드를 생성한다.(key1 : localnowDate, N_Word : a, N_Rating : b)
            sql = "INSERT INTO crawling_App_receive_naver_data (key1,N_Word,N_Rating) VALUES(%s,%s,%s)"
            curs.execute(sql, (localnowDate, a, b))
            rows = curs.fetchall()
            conn.commit()
    #키워드 순위가 떨어지면 점수도 1점씩 작게 부여하기 위해서 b에서 1을 뺀다.
        b = b - 1
    conn.close()
Example #19
0
    def test_send_message(self):
        sleep_time = 2

        # Checks if making an instance of message transaction correctly
        message_transaction = MessageTransactionBuilder()\
            .from_(self.setting["from"])\
            .to(self.setting["to"]) \
            .step_limit(self.setting["step_limit"])\
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"])\
            .data(self.setting["data"]).build()
        tx_dict = SignedTransaction.convert_tx_to_jsonrpc_request(message_transaction)
        self.assertTrue(is_message_transaction(tx_dict))

        # Checks if sending transaction correctly
        signed_transaction = SignedTransaction(message_transaction, self.wallet)
        result = self.icon_service.send_transaction(signed_transaction)
        self.assertTrue(is_T_HASH(result))

        # When having an optional property, nonce
        sleep(sleep_time)
        message_transaction = MessageTransactionBuilder().from_(self.setting["from"]).to(self.setting["to"]) \
            .step_limit(self.setting["step_limit"]).nid(self.setting["nid"]).data(self.setting["data"]).build()
        signed_transaction = SignedTransaction(message_transaction, self.wallet)
        result = self.icon_service.send_transaction(signed_transaction)
        self.assertTrue(is_T_HASH(result))

        # When the data is hex string
        sleep(sleep_time)
        tx_result = self.icon_service.get_transaction_result(result)
        tx = self.icon_service.get_transaction(result)

        # Checks the transaction
        self.assertEqual(tx["data"], self.setting["data"])
        block = self.icon_service.get_block(int(tx_result["blockHeight"]))

        # Checks the block's transaction
        self.assertEqual(block["confirmed_transaction_list"][0]["data"], self.setting["data"])

        # When data is not hex string
        message_transaction = MessageTransactionBuilder() \
            .from_(self.setting["from"]) \
            .to(self.setting["to"]) \
            .step_limit(self.setting["step_limit"]) \
            .nid(self.setting["nid"]) \
            .nonce(self.setting["nonce"]) \
            .data("test")

        # Raise DataTypeException
        self.assertRaises(DataTypeException, message_transaction.build)

        # When address is wrong
        message_transaction = MessageTransactionBuilder().from_(self.setting["from"]).to(self.setting["to"][2:]) \
            .step_limit(self.setting["step_limit"]).nid(self.setting["nid"]).data(self.setting["data"]).build()
        signed_transaction = SignedTransaction(message_transaction, self.wallet)
        self.assertRaises(JSONRPCException, self.icon_service.send_transaction, signed_transaction)

        # When not having a required property, nid
        message_transaction = MessageTransactionBuilder().from_(self.setting["from"]).to(self.setting["to"][2:]) \
            .step_limit(self.setting["step_limit"]).data(self.setting["data"]).build()
        signed_transaction = SignedTransaction(message_transaction, self.wallet)
        self.assertRaises(JSONRPCException, self.icon_service.send_transaction, signed_transaction)

        # When a sending address is wrong - not the wallet's address
        message_transaction = MessageTransactionBuilder().from_(self.setting["to"]).to(self.setting["to"]) \
            .step_limit(self.setting["step_limit"]).nid(self.setting["nid"]).data(self.setting["data"]).build()
        signed_transaction = SignedTransaction(message_transaction, self.wallet)
        self.assertRaises(JSONRPCException, self.icon_service.send_transaction, signed_transaction)
Example #20
0
    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
Example #21
0
            to_ = to_.get_address()

        msg_byte = msg.encode('utf-8')

        # build message tx
        transaction = MessageTransactionBuilder() \
            .from_(from_.get_address()) \
            .to(to_) \
            .step_limit(step_limit) \
            .nid(3) \
            .nonce(100) \
            .data(f"0x{msg_byte.hex()}") \
            .build()

        # signing message tx
        request = SignedTransaction(transaction, from_)
        tx_hashes: list = [network.send_transaction(request)]
        sleep(self._block_confirm_interval)
        return tx_hashes

    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 mock_calculate(self, _path, _block_height):
        context: 'IconScoreContext' = IconScoreContext(
            IconScoreContextType.QUERY)
Example #22
0
class calltransaction_transaction_RT():
    while(1):
        # def Crawling_main():
        start_time = time.time()
        # t = time.time()
        # now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t))
        # with open('/home/lyu/PycharmProjects/Without_Doubt_Project/Total_Crawler/Time_log.txt', 'a+') as f:
        #     f.write(now + "\n")

        now = datetime.datetime.now()
        nowDate = now.strftime('%Y%m%d')
        nowTime = now.strftime('%H%M')


        html = requests.get('https://www.naver.com/').text
        soup = BeautifulSoup(html, 'html.parser')
        title_list = soup.select('.PM_CL_realtimeKeyword_rolling span[class*=ah_k]')
        Machined_title_list = list()
        for idx, title in enumerate(title_list, 1):
            Machined_title_list.append(title.text)

        print(Machined_title_list)
        params = {
            "_date": nowDate,
            "_time": nowTime,
            "_div": 'NAVER',
            "_value": json.dumps(Machined_title_list)
        }

        transaction = CallTransactionBuilder() \
            .from_(_keystore_address) \
            .to(_score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transaction_RT") \
            .params(params) \
            .build()
        print(nowDate, nowTime, 'NAVER')
        signed_transaction = SignedTransaction(transaction, wallet)
        tx_hash = icon_service.send_transaction(signed_transaction)
        #
        # print(tx_hash)
        time.sleep(5)
        # tx_result = icon_service.get_transaction_result(tx_hash)
        # print(tx_result['status'])
        print("--- %s seconds ---" % (time.time() - start_time))

        #---------------------------------------------GOOGLE----------------------------------------
        now = datetime.datetime.now()
        # options = webdriver.ChromeOptions()
        # options.add_argument('headless')
        # options.add_argument('window-size=800x600')
        # options.add_argument("disable-gpu")
        # path = "/home/lyu/Downloads/chromedriver"
        # driver = webdriver.Chrome(path, chrome_options=options)

        # driver.get("https://trends.google.com/trends/trendingsearches/realtime?geo=US&category=all")
        #
        # #driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[2]/div/div[2]').click()
        # element = driver.find_element_by_css_selector("body > div.trends-wrapper > div:nth-child(2) > div > div.feed-content > div > div.feed-load-more-button")
        options = webdriver.ChromeOptions()
        options.add_argument('headless')
        options.add_argument('window-size=1920x1080')
        options.add_argument("disable-gpu")
        path = "/home/lyu/Downloads/chromedriver"
        driver = webdriver.Chrome(path, chrome_options=options)
        driver.get("https://trends.google.com/trends/trendingsearches/realtime?geo=US&category=all")

        # driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[2]/div/div[2]').click()



        element = driver.find_element_by_css_selector("body > div.trends-wrapper > div:nth-child(2) > div > div.feed-content > div > div.feed-load-more-button")
        # element.click()
        # time.sleep(4)
        #element2 = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[2]/div/div[2]")
        #print(element)
        #print(element2)
        req = driver.page_source

        soup = BeautifulSoup(req, 'html.parser')

        # time.sleep(10)
        title_list = soup.select('div > span:nth-child(1) > a')
        if ((len(title_list)) <= 20):
            element.click()
            time.sleep(4)
            title_list = soup.select('div > span:nth-child(1) > a')


        # shit_list = soup.select('body > div.trends-wrapper > div:nth-child(2) > div > div.feed-content > div > div.feed-load-more-button')
        # print(shit_list)


        # while not title_list or len(title_list) < 10:
        #     now = datetime.datetime.now()
        #     options = webdriver.ChromeOptions()
        #     options.add_argument('headless')
        #     options.add_argument('window-size=800x600')
        #     options.add_argument("disable-gpu")
        #     path = "/home/lyu/Downloads/chromedriver"
        #     driver = webdriver.Chrome(path, chrome_options=options)
        #
        #     driver.get("https://trends.google.com/trends/trendingsearches/realtime?geo=US&category=all")
        #     element = driver.find_element_by_css_selector("body > div.trends-wrapper > div:nth-child(2) > div > div.feed-content > div > div.feed-load-more-button")
        #     element.click()
        #     time.sleep(2)
        #     # element = driver.find_element_by_xpath("body > div.trends-wrapper > div:nth-child(2) > div > div.feed-content > div > div.feed-load-more-button")
        #     # element2 = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[2]/div/div[2]")
        #     # print(element)
        #     # print(element2)
        #     #driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[2]/div/div[2]').click()
        #     #driver.execute_script("arguments[0].click();", element)
        #     req = driver.page_source
        #
        #     soup = BeautifulSoup(req, 'html.parser')
        #     # time.sleep(10)
        #     title_list = soup.select('div > span:nth-child(1) > a')




        Temp_list = title_list[0:20]
        Machined_Google_title_list = list()

        for title in Temp_list:
            Machined_Google_title_list.append(title.text.strip())
        print(Machined_Google_title_list)

        params_G = {
            "_date": nowDate,
            "_time": nowTime,
            '_div': 'GOOGLE',
            "_value": json.dumps(Machined_Google_title_list)
        }
        transaction_G = CallTransactionBuilder() \
            .from_(_keystore_address) \
            .to(_score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transaction_RT") \
            .params(params_G) \
            .build()
        print(nowDate, nowTime, 'GOOGLE')
        signed_transaction_G = SignedTransaction(transaction_G, wallet)
        tx_hash_G = icon_service.send_transaction(signed_transaction_G)
        print("--- %s seconds ---" % (time.time() - start_time))
        #------------time sleep-------------------------------------
        # print(tx_hash_G)
        # time.sleep(10)
        # tx_result_G = icon_service.get_transaction_result(tx_hash_G)
        # print(tx_result_G['status'])

        # ------------------------Google DB Con------------------------

        # MySQL Connection 연결
        conn = pymysql.connect(host='127.0.0.1', user='******', password='******',
                               db='Crawling_DB', charset='utf8')

        # Connection 으로부터 Cursor 생성
        # curs = conn.cursor()
        curs = conn.cursor(pymysql.cursors.DictCursor)

        b = 20

        # 현재 1등 데이터가 TOP20 테이블에 이미 존재하고 있는지 검사
        check = Machined_Google_title_list[0]
        sql = "select * from crawling_App_receive_google_data where key1=%s and G_Word=%s"
        curs.execute(sql, (nowDate, check))
        check_resuit = curs.fetchall()
        if not check_resuit:
            print("Warning:%s" %check)

        # 가져온 20개의 키워드 insert, update
        for a in Machined_Google_title_list:
            # orgin score call

            # 검색된 단어의 점수가 존재하는 지, 몇점인지 확인한다.
            sql = "select G_Rating from crawling_App_receive_google_data where key1=%s and G_Word=%s"
            curs.execute(sql, (nowDate, a))
            num = curs.fetchall()

            if num:
                # print("already exist")
                for x in num:
                    d = list(x.values())
                    k = int(d[0])
                    k = k + b
                    # 만약 a[0]값이 crawling_receive_google_data에 없으며 주의 메세지 출력

                    sql = "UPDATE crawling_App_receive_google_data SET G_Rating=%s WHERE G_Word=%s"
                    #### 전날 날짜에 업데이트 하게되는 문제
                    curs.execute(sql, (k, a))
                    rows = curs.fetchall()
                    conn.commit()

            else:
                # print("New Input")
                sql = "INSERT INTO crawling_App_receive_google_data (key1,G_Word,G_Rating) VALUES(%s,%s,%s)"
                # sql = "select * from crawling_receive_google_data where key1=%s and G_Word='abc' and G_Rating=%s" % (nowDate, b)
                curs.execute(sql, (nowDate, a, b))
                rows = curs.fetchall()
                conn.commit()

            b = b - 1

        sql = "select G_Word from crawling_App_receive_google_data where key1=%s" % (nowDate)
        curs.execute(sql)
        rows = curs.fetchall()
        print(rows)

        # ------------------------Naver DB Con------------------------

        b=20

        check = Machined_title_list[0]
        sql = "select * from crawling_App_receive_naver_data where key1=%s and N_Word=%s"
        curs.execute(sql, (nowDate, check))
        check_resuit = curs.fetchall()
        if not check_resuit:
            print("Warning!!!")

        # 가져온 20개의 키워드 insert, update
        for a in Machined_title_list:
            # orgin score call

            # 검색된 단어의 점수가 존재하는 지, 몇점인지 확인한다.
            sql = "select N_Rating from crawling_App_receive_naver_data where key1=%s and N_Word=%s"
            curs.execute(sql, (nowDate, a))
            num = curs.fetchall()

            if num:
                # print("already exist")
                for x in num:
                    d = list(x.values())
                    k = int(d[0])
                    k = k + b
                    # 만약 a[0]값이 crawling_receive_google_data에 없으며 주의 메세지 출력

                    sql = "UPDATE crawling_App_receive_naver_data SET N_Rating=%s WHERE N_Word=%s"
                    #### 전날 날짜에 업데이트 하게되는 문제
                    curs.execute(sql, (k, a))
                    rows = curs.fetchall()
                    conn.commit()

            else:

                # print("New Input")
                sql = "INSERT INTO crawling_App_receive_naver_data (key1,N_Word,N_Rating) VALUES(%s,%s,%s)"
                # sql = "select * from crawling_receive_google_data where key1=%s and G_Word='abc' and G_Rating=%s" % (nowDate, b)
                curs.execute(sql, (nowDate, a, b))
                rows = curs.fetchall()
                conn.commit()

            b = b - 1

        sql = "select N_Word from crawling_App_receive_naver_data where key1=%s" % (nowDate)
        curs.execute(sql)
        rows = curs.fetchall()
        print(rows)

        conn.close()

        print("===========================================================================================================================================")
        print("start_time", start_time)
        k= (time.time() - start_time)
        print("--- %s seconds ---" % (time.time() - start_time))
        god = int((60 - (time.time() - start_time)))
        time.sleep(god)
    def test_token_transfer(self):
        # Make params of transfer method
        to = self._wallet_array[0].get_address()
        value = 100
        params = {
            '_to': to,
            '_value': value,
        }

        # Generates an instance of transaction for calling method in SCORE.
        transaction = CallTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._score_address) \
            .step_limit(10_000_000) \
            .nid(3) \
            .nonce(100) \
            .method("transfer") \
            .params(params) \
            .build()

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, self._test1)

        # Sends the transaction to the network
        print('Transfer Transaction', value, 'From:',
              self._test1.get_address(), 'To:', to)
        tx_result = self.process_transaction(signed_transaction,
                                             self.icon_service)
        self.assertTrue('status' in tx_result)
        self.assertEqual(1, tx_result['status'])

        # Make params of balanceOf method
        params = {'_owner': to}
        # Generates a call instance using the CallBuilder
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("balanceOf") \
            .params(params) \
            .build()

        # Sends the call request
        response = self.process_call(call, self.icon_service)
        # print('Balance Of Receiver:', to, 'in HEX:', response)
        balance = int(response, 0)
        print('Balance Of Receiver=>', 'Address:', to, 'Balance:', balance)

        # check balance of receiver
        self.assertEqual(hex(value), response)

        # Make params of balanceOf method
        params = {'_owner': self._test1.get_address()}
        # Generates a call instance using the CallBuilder
        call = CallBuilder().from_(self._test1.get_address()) \
            .to(self._score_address) \
            .method("balanceOf") \
            .params(params) \
            .build()

        # Sends the call request
        response = self.process_call(call, self.icon_service)
        # print('Balance Of Sender:', self._test1.get_address(), 'in HEX:', response)
        balance = int(response, 0)
        print('Balance Of Sender =>', 'Address:', self._test1.get_address(),
              'Balance:', balance)

        # check balance of sender
        self.assertEqual(hex(self.initial_supply * 10**self.decimals - value),
                         response)
Example #24
0
 def _distribute(self, condition: bool = True):
     tx = self._build_transaction(method="distribute", margin=100000000000)
     tx_result = self.process_transaction(
         SignedTransaction(tx, self._wallet), self._icon_service)
     self.assertEqual(condition, tx_result["status"])
     return tx_result
params = {"_to": wallet2.get_address(), "_value": 10}

# Enters transaction information.
call_transaction = CallTransactionBuilder()\
    .from_(wallet1.get_address())\
    .to(SCORE_ADDRESS) \
    .step_limit(get_default_step_cost()*2)\
    .nid(3) \
    .nonce(4) \
    .method("transfer")\
    .params(params)\
    .build()

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

# Reads params to transfer to nodes
print("params:")
pprint(signed_transaction.signed_transaction_dict)

# Sends transaction
tx_hash = icon_service.send_transaction(signed_transaction)
print("txHash: ", tx_hash)


@retry(JSONRPCException, tries=10, delay=1, back_off=2)
def get_tx_result():
    # Returns the result of a transaction by transaction hash
    tx_result = icon_service.get_transaction_result(tx_hash)
    print("transaction status(1:success, 0:failure): ", tx_result["status"])
Example #26
0
 def _unpause(self):
     tx = self._build_transaction(method="unPause", type_="write")
     tx_result = self.process_transaction(
         SignedTransaction(tx, self._wallet), self._icon_service)
     self.assertTrue(tx_result["status"])
     return tx_result