Beispiel #1
0
    def transfer(self, to, amount, gas_limit=None, gas_price=None):
        '''Transfers ether from this account.
        
        Args:
            to: Account instance or address string to transfer to.
            amount: Amount of ether to send, in wei.
            gas_limit: Gas limit of the transaction.
            gas_price: Gas price of the transaction.

        Returns:
            TransactionReceipt instance'''
        try:
            signed_tx = self._acct.signTransaction({
                'from':
                self.address,
                'nonce':
                self.nonce,
                'gasPrice':
                wei(gas_price) or self._gas_price(),
                'gas':
                wei(gas_limit) or self._gas_limit(to, amount),
                'to':
                str(to),
                'value':
                wei(amount),
                'data':
                ""
            }).rawTransaction
            txid = web3.eth.sendRawTransaction(signed_tx)
        except ValueError as e:
            txid = raise_or_return_tx(e)
        self.nonce += 1
        return TransactionReceipt(txid, self)
Beispiel #2
0
def _convert(a, b):
    if a not in (None, False, True):
        try:
            a = wei(a)
        except (ValueError, TypeError):
            pass
    if b not in (None, False, True):
        try:
            b = wei(b)
        except (ValueError, TypeError):
            pass
    return a, b
Beispiel #3
0
def _format_inputs(name, inputs, types):
    # format contract inputs based on ABI types
    inputs = list(inputs)
    if len(inputs) and not len(types):
        raise AttributeError("{} requires no arguments".format(name))
    if len(inputs) != len(types):
        raise AttributeError("{} requires the following arguments: {}".format(
            name, ",".join(types)))
    for i, type_ in enumerate(types):
        if type_[-1] == "]":
            # input value is an array, have to check every item
            t, length = type_.rstrip(']').rsplit('[', maxsplit=1)
            if length != "" and len(inputs[i]) != int(length):
                raise ValueError(
                    "'{}': Argument {}, sequence has a ".format(name, i) +
                    "length of {}, should be {}".format(len(inputs[i]), type_))
            inputs[i] = _format_inputs(name, inputs[i], [t] * len(inputs[i]))
            continue
        try:
            if "address" in type_:
                inputs[i] = str(inputs[i])
            if "int" in type_:
                inputs[i] = wei(inputs[i])
            elif "bytes" in type_ and type(inputs[i]) is not bytes:
                if type(inputs[i]) is not str:
                    inputs[i] = int(inputs[i]).to_bytes(int(type_[5:]), "big")
                elif inputs[i][:2] != "0x":
                    inputs[i] = inputs[i].encode()
        except:
            raise ValueError(
                "'{}': Argument {}, could not convert {} '{}' to type {}".
                format(name, i,
                       type(inputs[i]).__name__, inputs[i], type_))
    return inputs
Beispiel #4
0
def _get_tx(owner, args):
    # seperate contract inputs from tx dict
    if args and type(args[-1]) is dict:
        args, tx = (args[:-1], args[-1])
        if 'from' not in tx:
            tx['from'] = owner
        for key in [i for i in ['value', 'gas', 'gasPrice'] if i in tx]:
            tx[key] = wei(tx[key])
    else:
        tx = {'from': owner}
    return args, tx
Beispiel #5
0
    def estimate_gas(self, to, amount, data=""):
        '''Estimates the gas cost for a transaction. Raises VirtualMachineError
        if the transaction would revert.

        Args:
            to: Account instance or address string of transaction recipient.
            amount: Amount of ether to send in wei.
            data: Transaction data hexstring.

        Returns:
            Estimated gas value in wei.'''
        return web3.eth.estimateGas({
            'from': self.address,
            'to': str(to),
            'data': data,
            'value': wei(amount)
        })