コード例 #1
0
    def get_smart_contract(self, contract_address: str) -> dict:
        """
        This interface is used to get the information of smart contract based on the specified hexadecimal hash value.

        :param contract_address: str, a hexadecimal hash value.
        :return: the information of smart contract in dictionary form.
        """
        if type(contract_address) != str:
            raise SDKException(
                ErrorCode.param_err(
                    'a hexadecimal contract address is required.'))
        if len(contract_address) != 40:
            raise SDKException(
                ErrorCode.param_err(
                    'the length of the contract address should be 40 bytes.'))
        payload = RpcClient.set_json_rpc_version(RPC_GET_SMART_CONTRACT,
                                                 [contract_address, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        contract = json.loads(response.content.decode())["result"]
        return contract
コード例 #2
0
    def get_smart_contract_event_by_height(self, height: int) -> dict:
        """
        This interface is used to get the corresponding smart contract event based on the height of block.

        Args:
         height (int):
            a decimal height value.

        Return:
            the information of smart contract event in dictionary form.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_SMART_CONTRACT_EVENT,
                                                 [height, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        event = json.loads(response.content.decode())["result"]
        return event
コード例 #3
0
    def get_allowance(self, asset_name: str, from_address: str,
                      to_address: str) -> str:
        """
        This interface is used to get the the allowance
        from transfer-from account to transfer-to account in current network.

        Args:
         from_address (str):
            a base58 encoded account address

        Return:
            the information of allowance in dictionary form.
        """

        payload = RpcClient.set_json_rpc_version(
            RPC_GET_ALLOWANCE, [asset_name, from_address, to_address])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        allowance = json.loads(response.content.decode())["result"]
        return allowance
コード例 #4
0
    def get_balance(self, base58_address: str) -> dict:
        """
        This interface is used to get the account balance of specified base58 encoded address in current network.

        Args:
         base58_address (str):
            a base58 encoded account address

        Return:
            the value of account balance in dictionary form.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_BALANCE,
                                                 [base58_address, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        balance = json.loads(response.content.decode())["result"]
        return balance
コード例 #5
0
    def get_merkle_proof(self, tx_hash: str) -> dict:
        """
        This interface is used to get the corresponding merkle proof based on the specified hexadecimal hash value.

        Args:
         tx_hash (str):
            an hexadecimal transaction hash value.

        Return:
            the merkle proof in dictionary form.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_MERKLE_PROOF,
                                                 [tx_hash, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        proof = json.loads(response.content.decode())["result"]
        return proof
コード例 #6
0
    def get_storage(self, contract_address: str, key: str) -> int:
        """
        This interface is used to get the corresponding stored value
        based on hexadecimal contract address and stored key.

        Args:
         contract_address (str):
            hexadecimal contract address
         key (str):
            a hexadecimal stored key

        Return:
            the information of smart contract event in dictionary form.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_STORAGE, [contract_address, key, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        s = json.loads(response.content.decode())["result"]
        # s = bytearray.fromhex(s)
        # value = (s[0]) | (s[1]) << 8 | (s[2]) << 16 | (s[3]) << 24 | (s[4]) << 32 | (s[5]) << 40 | (s[6]) << 48 | (
        #     s[7]) << 56
        return s
コード例 #7
0
    def get_block_by_hash(self, block_hash: str) -> dict:
        """
        This interface is used to get the hexadecimal hash value of specified block height in current network.

        Args:
         block_hash (str):
            a hexadecimal value of block hash

        Return:
            the block information of the specified block hash.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_BLOCK,
                                                 [block_hash, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        dict_block = json.loads(response.content.decode())["result"]
        return dict_block
コード例 #8
0
    def send_raw_transaction_pre_exec(self, tx: Transaction):
        """
        This interface is used to send the transaction that is prepare to execute.

        Args:
         tx (Transaction):
            Transaction object in ontology Python SDK.

        Return:
            the execution result of transaction that is prepare to execute.
        """

        buf = tx.serialize()
        tx_data = buf.hex()
        payload = RpcClient.set_json_rpc_version(RPC_SEND_TRANSACTION, [tx_data, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        res = json.loads(response.content.decode())
        err = res["error"]
        if err > 0:
            try:
                result = res['result']
                raise RuntimeError(result)
            except KeyError:
                raise RuntimeError('send raw transaction pre-execute error')
        if res["result"]["State"] == 0:
            raise RuntimeError("State = 0")
        return res["result"]["Result"]
コード例 #9
0
    def get_block_hash_by_height(self, height: int) -> str:
        """
        This interface is used to get the hexadecimal hash value of specified block height in current network.

        Args:
         height (int):
            a decimal block height value

        Return:
            the hexadecimal hash value of the specified block height.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_BLOCK_HASH,
                                                 [height, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectTimeout: ',
                                               self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(
                ErrorCode.other_error(''.join(['ConnectionError: ',
                                               self.addr])))
        block_hash = json.loads(response.content.decode())["result"]
        return block_hash
コード例 #10
0
    def send_raw_transaction(self, tx: Transaction) -> str:
        """
        This interface is used to send the transaction into the network.

        Args:
         tx (Transaction):
            Transaction object in ontology Python SDK.

        Return:
            a hexadecimal transaction hash value.
        """

        buf = tx.serialize()
        tx_data = buf.hex()
        payload = RpcClient.set_json_rpc_version(RPC_SEND_TRANSACTION, [tx_data])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        data = json.loads(response.content.decode())
        res = data["result"]
        if data["error"] != 0:
            raise SDKException(ErrorCode.other_error(res))
        return res
コード例 #11
0
ファイル: asset.py プロジェクト: OnyxPayDev/SmartContractDemo
    def new_withdraw_ong_transaction(b58_claimer_address: str,
                                     b58_recv_address: str, amount: int,
                                     b58_payer_address: str, gas_limit: int,
                                     gas_price: int) -> Transaction:
        """
        This interface is used to generate a Transaction object that
        allow one account to withdraw an amount of ong and transfer them to receive address.

        :param b58_claimer_address: a base58 encode address which is used to indicate who is the claimer.
        :param b58_recv_address: a base58 encode address which is used to indicate who receive the claimed ong.
        :param amount: the amount of asset that will be claimed.
        :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction.
        :param gas_limit: an int value that indicate the gas limit.
        :param gas_price: an int value that indicate the gas price.
        :return: a Transaction object which can be used for withdraw ong.
        """
        if not isinstance(b58_claimer_address, str) or not isinstance(
                b58_recv_address, str) or not isinstance(
                    b58_payer_address, str):
            raise SDKException(
                ErrorCode.param_err(
                    'the data type of base58 encode address should be the string.'
                ))
        if len(b58_claimer_address) != 34 or len(
                b58_recv_address) != 34 or len(b58_payer_address) != 34:
            raise SDKException(
                ErrorCode.param_err(
                    'the length of base58 encode address should be 34 bytes.'))
        if amount <= 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the amount should be greater than than zero.'))
        if gas_price < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas price should be equal or greater than zero.'))
        if gas_limit < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas limit should be equal or greater than zero.'))
        ont_contract_address = util.get_asset_address('onyx')
        ong_contract_address = util.get_asset_address("oxg")
        args = {
            "sender": Address.b58decode(b58_claimer_address).to_array(),
            "from": ont_contract_address,
            "to": Address.b58decode(b58_recv_address).to_array(),
            "value": amount
        }
        invoke_code = build_native_invoke_code(ong_contract_address,
                                               bytes([0]), "transferFrom",
                                               args)
        unix_time_now = int(time())
        payer_array = Address.b58decode(b58_payer_address).to_array()
        return Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit,
                           payer_array, invoke_code, bytearray(), [],
                           bytearray())
コード例 #12
0
ファイル: asset.py プロジェクト: OnyxPayDev/SmartContractDemo
    def new_transfer_transaction(asset: str, b58_from_address: str,
                                 b58_to_address: str, amount: int,
                                 b58_payer_address: str, gas_limit: int,
                                 gas_price: int) -> Transaction:
        """
        This interface is used to generate a Transaction object for transfer.

        :param asset: a string which is used to indicate which asset we want to transfer.
        :param b58_from_address: a base58 encode address which indicate where the asset from.
        :param b58_to_address: a base58 encode address which indicate where the asset to.
        :param amount: the amount of asset that will be transferred.
        :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction.
        :param gas_limit: an int value that indicate the gas limit.
        :param gas_price: an int value that indicate the gas price.
        :return: a Transaction object which can be used for transfer.
        """
        if not isinstance(b58_from_address, str) or not isinstance(
                b58_to_address, str) or not isinstance(b58_payer_address, str):
            raise SDKException(
                ErrorCode.param_err(
                    'the data type of base58 encode address should be the string.'
                ))
        if len(b58_from_address) != 34 or len(b58_to_address) != 34 or len(
                b58_payer_address) != 34:
            raise SDKException(
                ErrorCode.param_err(
                    'the length of base58 encode address should be 34 bytes.'))
        if amount <= 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the amount should be greater than than zero.'))
        if gas_price < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas price should be equal or greater than zero.'))
        if gas_limit < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas limit should be equal or greater than zero.'))
        contract_address = util.get_asset_address(asset)
        raw_from = Address.b58decode(b58_from_address).to_array()
        raw_to = Address.b58decode(b58_to_address).to_array()
        raw_payer = Address.b58decode(b58_payer_address).to_array()
        state = [{"from": raw_from, "to": raw_to, "amount": amount}]
        invoke_code = build_native_invoke_code(contract_address, bytes([0]),
                                               "transfer", state)
        unix_time_now = int(time())
        version = 0
        tx_type = 0xd1
        attributes = bytearray()
        signers = list()
        hash_value = bytearray()
        return Transaction(version, tx_type, unix_time_now, gas_price,
                           gas_limit, raw_payer, invoke_code, attributes,
                           signers, hash_value)
コード例 #13
0
ファイル: asset.py プロジェクト: OnyxPayDev/SmartContractDemo
    def new_approve_transaction(asset: str, b58_send_address: str,
                                b58_recv_address: str, amount: int,
                                b58_payer_address: str, gas_limit: int,
                                gas_price: int) -> Transaction:
        """
        This interface is used to generate a Transaction object for approve.

        :param asset: a string which is used to indicate which asset we want to approve.
        :param b58_send_address: a base58 encode address which indicate where the approve from.
        :param b58_recv_address: a base58 encode address which indicate where the approve to.
        :param amount: the amount of asset that will be approved.
        :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction.
        :param gas_limit: an int value that indicate the gas limit.
        :param gas_price: an int value that indicate the gas price.
        :return: a Transaction object which can be used for approve.
        """
        if not isinstance(b58_send_address, str) or not isinstance(
                b58_recv_address, str):
            raise SDKException(
                ErrorCode.param_err(
                    'the data type of base58 encode address should be the string.'
                ))
        if len(b58_send_address) != 34 or len(b58_recv_address) != 34:
            raise SDKException(
                ErrorCode.param_err(
                    'the length of base58 encode address should be 34 bytes.'))
        if amount <= 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the amount should be greater than than zero.'))
        if gas_price < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas price should be equal or greater than zero.'))
        if gas_limit < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas limit should be equal or greater than zero.'))
        contract_address = util.get_asset_address(asset)
        raw_send = Address.b58decode(b58_send_address).to_array()
        raw_recv = Address.b58decode(b58_recv_address).to_array()
        raw_payer = Address.b58decode(b58_payer_address).to_array()
        args = {"from": raw_send, "to": raw_recv, "amount": amount}
        invoke_code = build_native_invoke_code(contract_address, bytes([0]),
                                               "approve", args)
        unix_time_now = int(time())
        return Transaction(0, 0xd1, unix_time_now, gas_price,
                           gas_limit, raw_payer, invoke_code, bytearray(), [],
                           bytearray())
コード例 #14
0
ファイル: asset.py プロジェクト: OnyxPayDev/SmartContractDemo
    def send_transfer_from(self, asset: str, sender: Account,
                           b58_from_address: str, b58_recv_address: str,
                           amount: int, payer: Account, gas_limit: int,
                           gas_price: int) -> str:
        """
        This interface is used to generate a Transaction object for transfer that
        allow one account to transfer a amount of ONT or ONG Asset to another account,
        in the condition of the first account had been approved.

        :param asset: a string which is used to indicate which asset we want to transfer.
        :param sender: an Account class that send the transfer transaction.
        :param b58_from_address: a base58 encode address which indicate where the asset from.
        :param b58_recv_address: a base58 encode address which indicate where the asset to.
        :param amount: the amount of asset want to transfer from from-address.
        :param payer: an Account class that used to pay for the transaction.
        :param gas_limit: an int value that indicate the gas limit.
        :param gas_price: an int value that indicate the gas price.
        :return: hexadecimal transaction hash value.
        """
        if sender is None:
            raise SDKException(
                ErrorCode.param_err('the sender should not be None.'))
        if payer is None:
            raise SDKException(
                ErrorCode.param_err('the payer should not be None.'))
        if amount <= 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the amount should be greater than than zero.'))
        if gas_price < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas price should be equal or greater than zero.'))
        if gas_limit < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas limit should be equal or greater than zero.'))
        b58_payer_address = payer.get_address_base58()
        b58_sender_address = sender.get_address_base58()
        tx = Asset.new_transfer_from_transaction(asset, b58_sender_address,
                                                 b58_from_address,
                                                 b58_recv_address, amount,
                                                 b58_payer_address, gas_limit,
                                                 gas_price)
        tx = self.__sdk.sign_transaction(tx, sender)
        if b58_sender_address != b58_payer_address:
            tx = self.__sdk.add_sign_transaction(tx, payer)
        self.__sdk.rpc.send_raw_transaction(tx)
        return tx.hash256_explorer()
コード例 #15
0
 def test_other_error(self):
     code = 59000
     msg = 'TEST'
     desc = "Other Error, " + msg
     value = ErrorCode.other_error(msg)
     self.assertEqual(value["error"], code)
     self.assertEqual(value["desc"], desc)
コード例 #16
0
 def add_identity(self, id: Identity):
     for identity in self.identities:
         if identity.ont_id == id.ont_id:
             raise SDKException(
                 ErrorCode.other_error(
                     'add identity failed, OntId conflict.'))
     self.identities.append(id)
コード例 #17
0
    def get_raw_transaction(self, tx_hash: str) -> dict:
        """
        This interface is used to get the corresponding transaction information based on the specified hash value.

        :param tx_hash: str, a hexadecimal hash value.
        :return: dict
        """
        payload = RpcClient.set_json_rpc_version(RPC_GET_TRANSACTION, [tx_hash, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        tx = json.loads(response.content.decode())["result"]
        return tx
コード例 #18
0
    def get_gas_price(self) -> int:
        """
        This interface is used to get the gas price in current network.

        Return:
            the value of gas price.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_GAS_PRICE, [])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        price = json.loads(response.content.decode())["result"]['gasprice']
        return price
コード例 #19
0
    def get_node_count(self) -> int:
        """
        This interface is used to get the current number of connections for the node in current network.

        Return:
            the number of connections.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_NODE_COUNT, [])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        count = json.loads(response.content.decode())["result"]
        return count
コード例 #20
0
    def get_current_block_hash(self) -> str:
        """
        This interface is used to get the hexadecimal hash value of the highest block in current network.

        Return:
            the hexadecimal hash value of the highest block in current network.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_CURRENT_BLOCK_HASH)
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        res = json.loads(response.content.decode())["result"]
        return res
コード例 #21
0
    def get_block_by_height(self, height: int) -> dict:
        """
        This interface is used to get the block information by block height in current network.

        Return:
            the decimal total number of blocks in current network.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_BLOCK, [height, 1])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        block = json.loads(response.content.decode())["result"]
        return block
コード例 #22
0
    def get_network_id(self) -> int:
        """
        This interface is used to get the network id of current network.

        Return:
            the network id of current network.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_NETWORK_ID, [])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        id = json.loads(response.content.decode())["result"]
        return id
コード例 #23
0
    def get_version(self) -> str:
        """
        This interface is used to get the version information of the connected node in current network.

        Return:
            the version information of the connected node.
        """

        payload = RpcClient.set_json_rpc_version(RPC_GET_VERSION, [])
        try:
            response = HttpRequest.request("post", self.addr, payload)
        except requests.exceptions.ConnectTimeout:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectTimeout: ', self.addr])))
        except requests.exceptions.ConnectionError:
            raise SDKException(ErrorCode.other_error(''.join(['ConnectionError: ', self.addr])))
        version = json.loads(response.content.decode())["result"]
        return version
コード例 #24
0
ファイル: asset.py プロジェクト: OnyxPayDev/SmartContractDemo
    def send_approve(self, asset, sender: Account, b58_recv_address: str,
                     amount: int, payer: Account, gas_limit: int,
                     gas_price: int) -> str:
        """
        This is an interface used to send an approve transaction
        which allow receiver to spend a amount of ONT or ONG asset in sender's account.

        :param asset: a string which is used to indicate what asset we want to approve.
        :param sender: an Account class that send the approve transaction.
        :param b58_recv_address: a base58 encode address which indicate where the approve to.
        :param amount: the amount of asset want to approve.
        :param payer: an Account class that used to pay for the transaction.
        :param gas_limit: an int value that indicate the gas limit.
        :param gas_price: an int value that indicate the gas price.
        :return: hexadecimal transaction hash value.
        """
        if sender is None:
            raise SDKException(
                ErrorCode.param_err('the sender should not be None.'))
        if payer is None:
            raise SDKException(
                ErrorCode.param_err('the payer should not be None.'))
        if amount <= 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the amount should be greater than than zero.'))
        if gas_price < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas price should be equal or greater than zero.'))
        if gas_limit < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas limit should be equal or greater than zero.'))
        b58_sender_address = sender.get_address_base58()
        b58_payer_address = payer.get_address_base58()
        tx = Asset.new_approve_transaction(asset, b58_sender_address,
                                           b58_recv_address, amount,
                                           b58_payer_address, gas_limit,
                                           gas_price)
        tx = self.__sdk.sign_transaction(tx, sender)
        if sender.get_address_base58() != payer.get_address_base58():
            tx = self.__sdk.add_sign_transaction(tx, payer)
        self.__sdk.rpc.send_raw_transaction(tx)
        return tx.hash256_explorer()
コード例 #25
0
ファイル: asset.py プロジェクト: OnyxPayDev/SmartContractDemo
    def send_withdraw_ong_transaction(self, claimer: Account,
                                      b58_recv_address: str, amount: int,
                                      payer: Account, gas_limit: int,
                                      gas_price: int) -> str:
        """
        This interface is used to withdraw a amount of ong and transfer them to receive address.

        :param claimer: the owner of ong that remained to claim.
        :param b58_recv_address: the address that received the ong.
        :param amount: the amount of ong want to claim.
        :param payer: an Account class that used to pay for the transaction.
        :param gas_limit: an int value that indicate the gas limit.
        :param gas_price: an int value that indicate the gas price.
        :return: hexadecimal transaction hash value.
        """
        if claimer is None:
            raise SDKException(
                ErrorCode.param_err('the claimer should not be None.'))
        if payer is None:
            raise SDKException(
                ErrorCode.param_err('the payer should not be None.'))
        if amount <= 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the amount should be greater than than zero.'))
        if gas_price < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas price should be equal or greater than zero.'))
        if gas_limit < 0:
            raise SDKException(
                ErrorCode.other_error(
                    'the gas limit should be equal or greater than zero.'))
        b58_claimer = claimer.get_address_base58()
        b58_payer = payer.get_address_base58()
        tx = Asset.new_withdraw_ong_transaction(b58_claimer, b58_recv_address,
                                                amount, b58_payer, gas_limit,
                                                gas_price)
        tx = self.__sdk.sign_transaction(tx, claimer)
        if claimer.get_address_base58() != payer.get_address_base58():
            tx = self.__sdk.add_sign_transaction(tx, payer)
        self.__sdk.rpc.send_raw_transaction(tx)
        return tx.hash256_explorer()
コード例 #26
0
    def send_raw_transaction(self, tx: Transaction) -> str:
        """
        This interface is used to send the transaction into the network.

        Args:
         tx (Transaction):
            Transaction object in ontology Python SDK.

        Return:
            a hexadecimal transaction hash value.
        """

        buf = tx.serialize()
        tx_data = buf.hex()
        rpc_struct = RpcClient.set_json_rpc_version(RPC_SEND_TRANSACTION, [tx_data])
        r = HttpRequest.request("post", self.addr, rpc_struct)
        data = json.loads(r.content.decode())
        res = data["result"]
        if data["error"] != 0:
            raise SDKException(ErrorCode.other_error(res))
        return res
コード例 #27
0
 def __init__(self,
              name: str = "MyWallet",
              version: str = "1.1",
              create_time: str = "",
              default_id: str = "",
              default_address="",
              scrypt: Scrypt = None,
              identities: list = None,
              accounts: list = None):
     if scrypt is None:
         scrypt = Scrypt()
     if not isinstance(scrypt, Scrypt):
         raise SDKException(
             ErrorCode.other_error('Wallet Data init failed'))
     if identities is None:
         identities = list()
     if accounts is None:
         accounts = list()
     self.name = name
     self.version = version
     self.create_time = create_time
     self.default_ont_id = default_id
     self.default_account_address = default_address
     self.scrypt = scrypt
     self.identities = list()
     self.accounts = list()
     for index in range(len(identities)):
         dict_identity = identities[index]
         if isinstance(dict_identity, dict):
             list_controls = list()
             try:
                 try:
                     is_default = dict_identity['isDefault']
                 except Exception as e:
                     is_default = False
                 for control_data in dict_identity['controls']:
                     list_controls.append(Control.dict2obj(control_data))
                 identity = Identity(ont_id=dict_identity['ontid'],
                                     label=dict_identity['label'],
                                     lock=dict_identity['lock'],
                                     controls=list_controls,
                                     is_default=is_default)
             except KeyError:
                 raise SDKException(ErrorCode.param_error)
             self.identities.append(identity)
         else:
             self.identities = identities
             break
     for index in range(len(accounts)):
         dict_account = accounts[index]
         if isinstance(dict_account, dict):
             try:
                 public_key = dict_account['publicKey']
             except KeyError:
                 public_key = ''
             try:
                 acct = AccountData(
                     address=dict_account['address'],
                     enc_alg=dict_account['enc-alg'],
                     key=dict_account['key'],
                     algorithm=dict_account['algorithm'],
                     salt=dict_account['salt'],
                     param=dict_account['parameters'],
                     label=dict_account['label'],
                     public_key=public_key,
                     sign_scheme=dict_account['signatureScheme'],
                     is_default=dict_account['isDefault'],
                     lock=dict_account['lock'])
             except KeyError:
                 raise SDKException(ErrorCode.param_error)
             self.accounts.append(acct)
         else:
             self.accounts = accounts
             break