Exemple #1
0
    def signTransaction(self, transaction_dict, private_key):
        '''
        @param private_key in bytes, str, or int.
            In Python 2, a bytes, unicode or str object will be interpreted as hexstr
            In Python 3, only a str object will be interpreted as hexstr
        '''
        assert isinstance(transaction_dict, Mapping)

        account = self.privateKeyToAccount(private_key)

        # sign transaction
        (
            v,
            r,
            s,
            transaction_hash,
            rlp_encoded,
        ) = sign_transaction_dict(account._key_obj, transaction_dict)

        return AttributeDict({
            'rawTransaction': to_hex(rlp_encoded),
            'hash': to_hex(transaction_hash),
            'r': to_hex(r),
            's': to_hex(s),
            'v': v,
        })
Exemple #2
0
def abi_bytes_to_hex(abi_type, data):
    base, sub, arrlist = process_type(abi_type)
    if base == 'bytes' and not arrlist:
        bytes_data = hexstr_if_str(to_bytes, data)
        if not sub:
            return abi_type, to_hex(bytes_data)
        else:
            num_bytes = int(sub)
            if len(bytes_data) <= num_bytes:
                padded = bytes_data.ljust(num_bytes, b'\0')
                return abi_type, to_hex(padded)
            else:
                raise ValueError(
                    "This value was expected to be at most %d bytes, but instead was %d: %r"
                    % ((num_bytes, len(bytes_data), data)))
Exemple #3
0
    def get_transaction_data(self, tx_id):
        """Gets transaction data.

        :param str tx_id: transaction id
        :return: transaction data
        :rtype: :class:`~kin.TransactionData`
        """
        tx_data = TransactionData()
        tx = self.web3.eth.getTransaction(tx_id)
        if not tx:
            return tx_data
        tx_data.from_address = tx['from']
        tx_data.to_address = tx['to']
        tx_data.ether_amount = float(self.web3.fromWei(tx['value'], 'ether'))
        tx_data.status = self._get_tx_status(tx)
        if not tx.get('blockNumber'):
            tx_data.num_confirmations = 0
        else:
            tx_block_number = int(tx['blockNumber'])
            cur_block_number = int(self.web3.eth.blockNumber)
            tx_data.num_confirmations = cur_block_number - tx_block_number + 1
        if tx.get('input') and not (tx['input'] == '0x' or tx['input']
                                    == '0x0'):  # contract transaction
            to, amount = decode_abi(
                ['uint256', 'uint256'],
                tx['input'][len(ERC20_TRANSFER_ABI_PREFIX):])
            tx_data.to_address = to_hex(to)
            tx_data.token_amount = float(self.web3.fromWei(amount, 'ether'))
        return tx_data
Exemple #4
0
    def add_receipt(cls, receipt_data, block_number, timestamp):
        """
        Creates a new receipt object from data received from JSON-RPC call
        eth_getTransactionReceipt.

        :param dict receipt_data: receipt data received from the JSON RPC callable
        :param int timestamp: timestamp of the block where this transaction was included
        :param int block_number: block number of the block where this transaction was included
        """
        if block_number > constants.FORK_BLOCK_NUMBER['Byzantium']:
            status = bool(to_int(receipt_data['status']))
        else:
            status = None

        receipt = cls(
            transaction_hash=to_hex(receipt_data['transactionHash']),
            status=status,
            gas_used=to_int(receipt_data['gasUsed']),
            cumulative_gas_used=to_int(receipt_data['cumulativeGasUsed']),
            contract_address=receipt_data['contractAddress'],
            block_number=block_number,
            timestamp=timestamp,
            transaction_index=to_int(receipt_data['transactionIndex']))

        return receipt
Exemple #5
0
def encode_abi(web3, abi, arguments, data=None):
    argument_types = get_abi_input_types(abi)

    if not check_if_arguments_can_be_encoded(abi, arguments, {}):
        raise TypeError(
            "One or more arguments could not be encoded to the necessary "
            "ABI type.  Expected types are: {0}".format(
                ', '.join(argument_types), ))

    try:
        normalizers = [
            abi_ens_resolver(web3),
            abi_address_to_hex,
            abi_bytes_to_bytes,
            abi_string_to_text,
        ]
        normalized_arguments = map_abi_data(
            normalizers,
            argument_types,
            arguments,
        )
        encoded_arguments = eth_abi_encode_abi(
            argument_types,
            normalized_arguments,
        )
    except EncodingError as e:
        raise TypeError(
            "One or more arguments could not be encoded to the necessary "
            "ABI type: {0}".format(str(e)))

    if data:
        return to_hex(HexBytes(data) + encoded_arguments)
    else:
        return encode_hex(encoded_arguments)
    def _check_parse_contract_tx(self, tx, filter_args):
        """Parse contract transaction and check whether it matches the supplied filter.
        If the transaction matches the filter, the first returned value will be True, and the rest will be
        correctly filled. If there is no match, the first returned value is False and the rest are empty.

        :param dict tx: transaction object

        :param dict filter_args: a filter that contains fields 'to', 'from' or both.

        :returns: matching status, from address, to address, token amount
        :rtype: tuple
        """
        if not tx.get('to') or tx['to'].lower() != self.token_contract.address.lower():  # must be sent to our contract
            return False, '', '', 0
        tx_input = tx.get('input')
        if not tx_input or tx_input == '0x':  # not a contract transaction
            return False, '', '', 0
        if not tx_input.lower().startswith(ERC20_TRANSFER_ABI_PREFIX.lower()):
            # only interested in calls to 'transfer' method
            return False, '', '', 0

        to, amount = decode_abi(['uint256', 'uint256'], tx_input[len(ERC20_TRANSFER_ABI_PREFIX):])
        to = to_hex(to)
        amount = self.web3.fromWei(amount, 'ether')
        if (('from' in filter_args and tx['from'].lower() == filter_args['from'].lower() and
                ('to' not in filter_args or to.lower() == filter_args['to'].lower())) or
            ('to' in filter_args and to.lower() == filter_args['to'].lower())):
                return True, tx['from'], to, amount
        return False, '', '', 0
    def _check_parse_contract_tx(self, tx, filter_args):
        """Parse contract transaction and check whether it matches the supplied filter.
        If the transaction matches the filter, the first returned value will be True, and the rest will be
        correctly filled. If there is no match, the first returned value is False and the rest are empty.

        :param dict tx: transaction object

        :param dict filter_args: a filter that contains fields 'to', 'from' or both.

        :returns: matching status, from address, to address, token amount
        :rtype: tuple
        """
        if not tx.get('to') or tx['to'].lower() != self.token_contract.address.lower():  # must be sent to our contract
            return False, '', '', 0
        tx_input = tx.get('input')
        if not tx_input or tx_input == '0x':  # not a contract transaction
            return False, '', '', 0
        if not tx_input.lower().startswith(ERC20_TRANSFER_ABI_PREFIX.lower()):
            # only interested in calls to 'transfer' method
            return False, '', '', 0

        to, amount = decode_abi(['uint256', 'uint256'], tx_input[len(ERC20_TRANSFER_ABI_PREFIX):])
        to = to_hex(to)
        amount = self.web3.fromWei(amount, 'ether')
        if (('from' in filter_args and tx['from'].lower() == filter_args['from'].lower() and
                ('to' not in filter_args or to.lower() == filter_args['to'].lower())) or
            ('to' in filter_args and to.lower() == filter_args['to'].lower())):
                return True, tx['from'], to, amount
        return False, '', '', 0
    def get_transaction_data(self, tx_id):
        """Gets transaction data for the provided transaction id.

        :param str tx_id: transaction id (hash)
        :return: transaction data
        :rtype: :class:`~erc20tokensdk.TransactionData`
        """
        tx_data = TransactionData()
        tx = self.web3.eth.getTransaction(tx_id)
        if not tx:
            return tx_data
        tx_data.from_address = tx['from']
        tx_data.to_address = tx['to']
        tx_data.ether_amount = self.web3.fromWei(tx['value'], 'ether')
        tx_data.status = self._get_tx_status(tx)
        if not tx.get('blockNumber'):
            tx_data.num_confirmations = 0
        else:
            tx_block_number = int(tx['blockNumber'])
            cur_block_number = int(self.web3.eth.blockNumber)
            tx_data.num_confirmations = cur_block_number - tx_block_number + 1
        tx_input = tx.get('input')
        if tx_input and (tx_input.lower().startswith(ERC20_TRANSFER_ABI_PREFIX.lower())):
            to, amount = decode_abi(['uint256', 'uint256'], tx_input[len(ERC20_TRANSFER_ABI_PREFIX):])
            tx_data.to_address = to_hex(to)
            tx_data.token_amount = self.web3.fromWei(amount, 'ether')
        return tx_data
    def get_transaction_data(self, tx_id):
        """Gets transaction data for the provided transaction id.

        :param str tx_id: transaction id (hash)
        :return: transaction data
        :rtype: :class:`~erc20token.TransactionData`
        """
        tx_data = TransactionData()
        tx = self.web3.eth.getTransaction(tx_id)
        if not tx:
            return tx_data
        tx_data.from_address = tx['from']
        tx_data.to_address = tx['to']
        tx_data.ether_amount = self.web3.fromWei(tx['value'], 'ether')
        tx_data.status = self._get_tx_status(tx)
        if not tx.get('blockNumber'):
            tx_data.num_confirmations = 0
        else:
            tx_block_number = int(tx['blockNumber'])
            cur_block_number = int(self.web3.eth.blockNumber)
            tx_data.num_confirmations = cur_block_number - tx_block_number + 1
        tx_input = tx.get('input')
        if tx_input and (tx_input.lower().startswith(ERC20_TRANSFER_ABI_PREFIX.lower())):
            to, amount = decode_abi(['uint256', 'uint256'], tx_input[len(ERC20_TRANSFER_ABI_PREFIX):])
            tx_data.to_address = to_hex(to)
            tx_data.token_amount = self.web3.fromWei(amount, 'ether')
        return tx_data
Exemple #10
0
    def add_transaction(cls, transaction_data, block_number, iso_timestamp):
        """
        Creates a new transaction object from data received from JSON-RPC call
        eth_getBlockByNumber.

        :param dict transaction_data: data received from JSON RPC call
        :param datetime iso_timestamp: timestamp when the block containing the transaction was mined
        :param int block_number: block number of the block where this transaction was included
        """
        try:
            receiver = to_checksum_address(transaction_data['to'])
        except TypeError:
            receiver = None

        transaction = cls(block_number=block_number,
                          nonce=to_int(transaction_data['nonce']),
                          transaction_hash=to_hex(transaction_data['hash']),
                          sender=to_checksum_address(transaction_data['from']),
                          start_gas=to_int(transaction_data['gas']),
                          value=int(str(to_int(transaction_data['value']))),
                          receiver=receiver,
                          data=transaction_data['input'],
                          gas_price=str(to_int(transaction_data['gasPrice'])),
                          timestamp=iso_timestamp,
                          transaction_index=to_int(
                              transaction_data['transactionIndex']))

        return transaction
Exemple #11
0
 def recoverTransaction(self, serialized_transaction):
     txn_bytes = HexBytes(serialized_transaction)
     txn = Transaction.from_bytes(txn_bytes)
     msg_hash = hash_of_signed_transaction(txn)
     if sys.version_info.major < 3:
         msg_hash = to_hex(msg_hash)
     return self.recover(msg_hash, vrs=vrs_from(txn))
Exemple #12
0
 def raw_transaction(self, privkey, addrto, amount, gasPrice, gasLimit):
     """裸交易"""
     value = amount * (10**self.decimals)  # 单位转转
     # 通过private key实例化账户
     account = Account.privateKeyToAccount(privkey)
     address = account.address
     nonce = self.w3.eth.getTransactionCount(address)
     # 创建交易的json文件(将value从科学计数法变为浮点数)
     value = int(value)
     gasLimit = int(gasLimit)
     gasPrice = int(gasPrice)
     payload = {
         'value': 0,
         'gas': gasLimit,
         'gasPrice': gasPrice,
         'nonce': nonce,
         'from': address
     }
     try:
         unicorn_txn = self.token_contract.functions.transfer(
             addrto, value).buildTransaction(payload)
         # 使用发送方账户对裸交易对象进行签名
         signed = account.signTransaction(unicorn_txn)
         tx_hash = self.w3.eth.sendRawTransaction(signed.rawTransaction)
         return True, to_hex(tx_hash)
     except ValueError as e:
         print('ValueError:', e)
         return False, str(e)
Exemple #13
0
def abi_bytes_to_hex(abi_type, data):
    base, sub, arrlist = process_type(abi_type)
    if base == 'bytes' and not arrlist:
        bytes_data = hexstr_if_str(to_bytes, data)
        if not sub:
            return abi_type, to_hex(bytes_data)
        else:
            num_bytes = int(sub)
            if len(bytes_data) <= num_bytes:
                padded = bytes_data.ljust(num_bytes, b'\0')
                return abi_type, to_hex(padded)
            else:
                raise ValueError(
                    "This value was expected to be at most %d bytes, but instead was %d: %r" % (
                        (num_bytes, len(bytes_data), data)
                    )
                )
Exemple #14
0
def test_conversion_round_trip(value):
    intermediate_value = to_hex(value)
    result_value = to_int(hexstr=intermediate_value)
    error_msg = "Expected: {0!r}, Result: {1!r}, Intermediate: {2!r}".format(
        value,
        result_value,
        intermediate_value,
    )
    assert result_value == value, error_msg
Exemple #15
0
def abi_bytes_to_hex(abi_type, data):
    base, sub, arrlist = process_type(abi_type)
    if base == 'bytes' and not arrlist:
        bytes_data = hexstr_if_str(to_bytes, data)
        if len(bytes_data) != int(sub):
            raise ValueError(
                "This value was expected to be %d bytes, but instead was %d: %r"
                % ((sub, len(bytes_data), data)))
        return abi_type, to_hex(bytes_data)
Exemple #16
0
def test_conversion_round_trip(value):
    intermediate_value = to_hex(value)
    result_value = to_int(hexstr=intermediate_value)
    error_msg = "Expected: {0!r}, Result: {1!r}, Intermediate: {2!r}".format(
        value,
        result_value,
        intermediate_value,
    )
    assert result_value == value, error_msg
Exemple #17
0
 def sign(self, message=None, private_key=None, message_hexstr=None, message_text=None):
     '''
     @param private_key in bytes, str, or int.
         In Python 2, a bytes, unicode or str object will be interpreted as hexstr
         In Python 3, only a str object will be interpreted as hexstr
     '''
     msg_bytes = to_bytes(message, hexstr=message_hexstr, text=message_text)
     msg_hash = self.hashMessage(msg_bytes)
     key_bytes = HexBytes(private_key)
     key = self._keys.PrivateKey(key_bytes)
     (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash)
     return AttributeDict({
         'message': to_hex(msg_bytes),
         'messageHash': msg_hash,
         'r': to_hex(r),
         's': to_hex(s),
         'v': v,
         'signature': to_hex(eth_signature_bytes),
     })
def rpc_transfer(owner, to, value):
    func_hash = keccak(text='transfer(address,uint256)')
    selector = func_hash[:4]

    encoded_params = encode_abi(['address', 'uint256'], [to, value])
    tx_data = to_hex(HexBytes(selector) + encoded_params)

    payload = {'from': owner, 'to': addr, 'data': tx_data}
    tx_hash = w3.eth.sendTransaction(payload)
    return w3.eth.waitForTransactionReceipt(tx_hash)
def rpc_balanceOf(address):
    func_hash = keccak(text='balanceOf(address)')
    selector = func_hash[:4]

    encoded_params = encode_abi(['address'], [address])
    tx_data = to_hex(HexBytes(selector) + encoded_params)

    payload = {'to': addr, 'data': tx_data}
    ret = w3.eth.call(payload)
    return decode_single('uint256', ret)
Exemple #20
0
    def _write_transactions_to_db(self, transaction):
        """
        把交易数据写入到数据库里
        :param transaction:
        :return:
        """
        data = Transactions(
            transaction_hash=str(to_hex(transaction.get('hash'))),
            block_hash=str(to_hex(transaction.get('blockHash'))),
            block_number=transaction.get('blockNumber'),
            transaction_index=transaction.get('transactionIndex'),
            category=transaction.get('category'),
            from_address=transaction.get('from'),
            to_address=transaction.get('to'),
            value=transaction.get('value'),
            fee=transaction.get('gas'),
        )

        session.add(data)
        session.commit()
Exemple #21
0
 def minerfee_transaction(self, addrfrom, addrto, amount):
     """普通付款转账矿工费"""
     # 单位换算
     amount = int(amount * (10**18))
     payload = {'from': addrfrom, 'to': addrto, 'value': amount}
     try:
         ret = self.w3.personal.sendTransaction(payload, self.passphrase)
         tx_hash = to_hex(ret)
         return True, tx_hash
     except Exception as e:
         payload.update(dict(errormsg=str(e)))
         logging.error('eth payment error:{}'.format(str(payload)))
         return False, str(e)
Exemple #22
0
    def add_block(cls, block_data, iso_timestamp):
        """
        Creates a new block object from data received from JSON-RPC call
        eth_getBlockByNumber.

        :param dict block_data: data received from the JSON RPC call
        :param datetime iso_timestamp: timestamp when the block was mined
        """
        block = cls(block_hash=to_hex(block_data['hash']),
                    parent_hash=to_hex(block_data['parentHash']),
                    difficulty=to_int(block_data['difficulty']),
                    block_number=to_int(block_data['number']),
                    gas_used=to_int(block_data['gasUsed']),
                    miner=to_checksum_address(block_data['miner']),
                    timestamp=iso_timestamp,
                    sha3uncles=to_hex(block_data['sha3Uncles']),
                    extra_data=to_hex(block_data['extraData']),
                    gas_limit=to_int(block_data['gasLimit']),
                    transaction_count=len(block_data['transactions']),
                    uncle_count=len(block_data['uncles']))

        return block
Exemple #23
0
    def __init__(self, key, account):
        '''
        :param eth_keys.PrivateKey key: to prefill in private key execution
        :param web3.account.Account account: the key-unaware management API
        '''
        self._publicapi = account

        self.address = key.public_key.to_checksum_address()

        key_raw = key.to_bytes()
        if sys.version_info.major < 3:
            key_raw = to_hex(key_raw)
        self.privateKey = key_raw

        self._key_obj = key
Exemple #24
0
def new_blocks():
    """
    Celery beat task which runs every second to get new blocks.
    :param block_filter: block filter as described in session.py
    """
    current_session = get_current_session()
    logger.debug("Reached at new blocks to get block hashes")
    block_hashes = current_session.block_filter.get_new_entries()
    for block_hash in block_hashes:
        block_data = current_session.w3.eth.getBlock(block_hash)
        block_number = to_int(block_data['number'])
        BlockTaskMeta.add_block_task_meta(task_name='new_blocks',
                                          state='WAITING',
                                          block_number=block_number,
                                          block_hash=to_hex(block_hash))
    logger.info(block_hashes)
Exemple #25
0
 def payment(self, addrfrom, addrto, amount):
     """普通付款"""
     # 单位换算
     value = amount * (10**self.decimals)
     value = int(value)
     payload = {'from': addrfrom, 'value': 0}
     try:
         unicorn_txn = self.token_contract.functions.transfer(
             addrto, value).buildTransaction(payload)
         ret = self.w3.personal.sendTransaction(unicorn_txn,
                                                self.passphrase)
         tx_hash = to_hex(ret)
         return True, tx_hash
     except Exception as e:
         payload.update(dict(errormsg=str(e)))
         logging.error('IPCHAIN payment error:{}'.format(str(payload)))
         return False, str(e)
Exemple #26
0
    def _encode_data_in_transaction(self, *args, **kwargs):
        constructor_abi = get_constructor_abi(self.abi)

        if constructor_abi:
            if not args:
                args = tuple()
            if not kwargs:
                kwargs = {}

            arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)
            data = add_0x_prefix(
                encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode)
            )
        else:
            data = to_hex(self.bytecode)

        return data
Exemple #27
0
    def _encode_constructor_data(cls, args=None, kwargs=None):
        constructor_abi = get_constructor_abi(cls.abi)

        if constructor_abi:
            if args is None:
                args = tuple()
            if kwargs is None:
                kwargs = {}

            arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)

            deploy_data = add_0x_prefix(
                cls._encode_abi(constructor_abi, arguments, data=cls.bytecode))
        else:
            deploy_data = to_hex(cls.bytecode)

        return deploy_data
Exemple #28
0
def put_initial_blocks_in_waiting():
    current_session = get_current_session()

    put_blocks = range(BASE_BLOCK, BASE_BLOCK + current_session.settings.BLOCK_LAG)
    for block_number in put_blocks:
        block_data = current_session.w3.eth.getBlock(block_number)
        block_hash = block_data['hash']
        BlockTaskMeta.add_block_task_meta(task_name='new_blocks',
                              state='WAITING',
                              block_number=block_number,
                              block_hash=to_hex(block_hash))
    verify_pushed_sql_contents()
    with current_session.db_session_scope():
        block_task_meta = current_session.db_session.query(BlockTaskMeta).first()
        assert block_task_meta.block_number == BASE_BLOCK
        assert block_task_meta.block_hash == EXPECTED_BLOCK_HASHES[BASE_BLOCK]
        assert block_task_meta.state == 'WAITING'
Exemple #29
0
def encode_constructor_data(abi, bytecode, web3, args=None, kwargs=None):

    constructor_abi = get_constructor_abi(abi)

    if constructor_abi:
        if args is None:
            args = tuple()
        if kwargs is None:
            kwargs = {}

        arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)

        deploy_data = add_0x_prefix(
            encode_abi(web3, constructor_abi, arguments, data=bytecode))
    else:
        deploy_data = to_hex(bytecode)

    return deploy_data
Exemple #30
0
    def _encode_constructor_data(cls, args=None, kwargs=None):
        constructor_abi = get_constructor_abi(cls.abi)

        if constructor_abi:
            if args is None:
                args = tuple()
            if kwargs is None:
                kwargs = {}

            arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)

            deploy_data = add_0x_prefix(
                encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode)
            )
        else:
            deploy_data = to_hex(cls.bytecode)

        return deploy_data
Exemple #31
0
    def _encode_abi(cls, abi, arguments, data=None):
        argument_types = get_abi_input_types(abi)

        if not check_if_arguments_can_be_encoded(abi, arguments, {}):
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type.  Expected types are: {0}".format(
                    ', '.join(argument_types),
                )
            )

        try:
            normalizers = [
                abi_ens_resolver(cls.web3),
                abi_address_to_hex,
                abi_bytes_to_hex,
                abi_string_to_hex,
                hexstrs_to_bytes,
            ]
            normalized_arguments = map_abi_data(
                normalizers,
                argument_types,
                arguments,
            )
            encoded_arguments = encode_abi(
                argument_types,
                normalized_arguments,
            )
        except EncodingError as e:
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type: {0}".format(str(e))
            )

        if data:
            return to_hex(HexBytes(data) + encoded_arguments)
        else:
            return encode_hex(encoded_arguments)
Exemple #32
0
 def raw_transaction(self, privkey, addrto, amount, gasPrice, gasLimit):
     value = amount * (10**18)  # 单位转转
     # 通过private key实例化账户
     account = Account.privateKeyToAccount(privkey)
     nonce = self.w3.eth.getTransactionCount(account.address)
     # 创建交易的json文件(将value从科学计数法变为浮点数)
     value = int(value)
     gasLimit = int(gasLimit)
     gasPrice = int(gasPrice)
     payload = {
         'to': addrto,
         'value': value,
         'gas': gasLimit,
         'gasPrice': gasPrice,
         'nonce': nonce,
     }
     try:
         # 使用发送方账户对裸交易对象进行签名
         signed = account.signTransaction(payload)
         tx_hash = self.w3.eth.sendRawTransaction(signed.rawTransaction)
         return True, to_hex(tx_hash), ''
     except ValueError as e:
         print('ValueError:', e)
         return False, '', str(e)
Exemple #33
0
 def sign(self, account, data=None, hexstr=None, text=None):
     message_hex = to_hex(data, hexstr=hexstr, text=text)
     return self.web3.manager.request_blocking(
         "eth_sign", [account, message_hex],
     )
Exemple #34
0
def waitForReceipt(tx_hash, timeout=60, interval=2):
    t0 = time.time()
    while (True):
        receipt = w3.eth.getTransactionReceipt(tx_hash)
        if receipt is not None:
            break
        delta = time.time() - t0
        if (delta > timeout):
            break
        time.sleep(interval)

    return receipt


w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
accounts = w3.eth.accounts

balance = w3.eth.getBalance(accounts[0], 'latest')
print('balance before tx => {0}'.format(balance))

payload = {'from': accounts[0], 'to': accounts[1], 'value': 100}
tx_hash = w3.eth.sendTransaction(payload)
print('tx hash => {0}'.format(to_hex(tx_hash)))

receipt = waitForReceipt(tx_hash)
#receipt = w3.eth.waitForTransactionReceipt(tx_hash)
print('gas used => {0}'.format(receipt.gasUsed))

balance = w3.eth.getBalance(accounts[0], 'latest')
print('balance after tx => {0}'.format(balance))
Exemple #35
0
def test_bytes_that_start_with_0x():
    sneaky_bytes = b'0x\xde\xad'
    assert to_hex(sneaky_bytes) == '0x3078dead'
 def sign(self, account, data=None, hexstr=None, text=None):
     message_hex = to_hex(data, hexstr=hexstr, text=text)
     return self.web3.manager.request_blocking(
         "eth_sign",
         [account, message_hex],
     )
Exemple #37
0
def test_bytes_that_start_with_0x():
    sneaky_bytes = b'0x\xde\xad'
    assert to_hex(sneaky_bytes) == '0x3078dead'
Exemple #38
0
def test_to_hex(value, expected):
    assert to_hex(value) == expected
Exemple #39
0
def test_to_hex(value, expected):
    assert to_hex(value) == expected
Exemple #40
0
def inputBlockNumberFormatter(blockNumber):
    if not blockNumber:
        return None
    elif isPredefinedBlockNumber(blockNumber):
        return blockNumber
    return to_hex(blockNumber)