Giter Site home page Giter Site logo

ethereum / web3.py Goto Github PK

View Code? Open in Web Editor NEW
4.9K 119.0 1.6K 28.73 MB

A python interface for interacting with the Ethereum blockchain and ecosystem.

Home Page: http://web3py.readthedocs.io

License: MIT License

Makefile 0.13% Python 98.55% Dockerfile 0.01% Solidity 1.26% Shell 0.05%

web3.py's Introduction

web3.py

Join the conversation on Discord Build Status PyPI version Python versions Docs build

A Python library for interacting with Ethereum.

  • Python 3.8+ support

Quickstart

Get started in 5 minutes or take a tour of the library.

Documentation

For additional guides, examples, and APIs, see the documentation.

Want to help?

Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on our guidelines for contributing, then check out issues that are labeled Good First Issue.


Questions on implementation or usage? Join the conversation on discord.

web3.py's People

Contributors

ankitchiplunkar avatar banteg avatar billbsing avatar carver avatar davesque avatar dbfreem avatar djrtwo avatar dylanjw avatar fselmo avatar fubuloubu avatar jasonrhaas avatar jstoxrocky avatar kclowes avatar linda-le1 avatar mhchia avatar miohtama avatar monokh avatar njgheorghita avatar pacrob avatar pipermerriam avatar reedsa avatar shravan-shandilya avatar tmckenzie51 avatar uxio0 avatar veox avatar void4 avatar voith avatar wiseaidev avatar wolovim avatar zheli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web3.py's Issues

Add `MultiProvider` Provider

What was wrong?

Currently tests run against both an RPC and IPC connection to a real geth node. This is useful in that it will surface any discrepancies, but it's slow and overly redundant.

To fix this, I propose a new provider type, MultiProvider.

  • A MultiProvider is composed of multiple other providers.
  • Each RPC method will have a strategy for how it should be called.
  • Strategies might include.
    • Call all providers, check that they all returned the same thing, return the value.
    • Call all providers, return the first value to be returned, discard all other values.
    • Call a single provider (at random, the first one, ...)
    • Round-robin call the providers.

This will be useful for testing in that it will allow the test suite to be faster.

This should also be useful in other situations as it will allow for things like load balancing, or redundancy across multiple providers.

string and byte conversion in events.py corrupts data

  • Version: 3.2.0
  • Python: 3.5
  • OS: linux

What was wrong?

My strings passed in contract events get corrupted. They look like this when I listen to events:
'_ipfsaddr': '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'`

solution

--- events.py   2016-12-07 14:21:27.523182611 +0100
+++ events-new.py       2016-12-07 14:18:24.779178254 +0100
@@ -116,8 +116,8 @@
     entries using the correct types.
     """
     return [
-        'bytes32' if arg_type in {'bytes', 'string'} else arg_type
-        for arg_type in input_types
+        #'bytes32' if arg_type in {'bytes', 'string'} else arg_type
+        arg_type for arg_type in input_types
     ]

now I get my ipfs address correctly:
'_ipfsaddr': 'QmSL2Zj3QmQFNcF6pethSYDF8fGYpz1LDeFiaLSzkCtAQ2'

Undeclared dependencies: gevent and rlp

  • Version: 1.0.0
  • Python: 2.7 / 3.5
  • OS: Ubuntu 16.04 LTS

What was wrong?

On a clean installation, import web3 fails, with import errors due to imports of gevent and rlp.

Should these be added to install_requires?

Cute Animal Picture

kittens

Expose _Contract

What was wrong?

Currently web3.contract._Contract is privateish It would be useful to expose this for static analysis to help IDE auto completion.

I'd suggest renaming _Contract to Contract or ContractBase and then exposing it in necessary __init__ modules.

Cute Animal Picture

moo

stuck on test_contract_estimateGas.py

  • Version: 1.3.0
  • Python: 2.7/3.4/3.5
  • OS: debian stretch

i install and new laptop and I fail here, I haent the slightest idea where to look at from the error log

What was wrong?

the test hangs ans never returns

/usr/local/lib/python3.5/dist-packages/gevent-1.1.2-py3.5-linux-x86_64.egg/gevent/monkey.py:395: RuntimeWarning: Monkey-patching not on the main thread; threading.main_thread().join() will hang from a greenlet
  _warnings)
E
request = <SubRequest 'web3' for <Function 'test_needs_skipping[tester]'>>

    @pytest.yield_fixture(params=[
        'tester',
        pytest.mark.slow('rpc'),
        pytest.mark.slow('ipc'),
    ])
    def web3(request):
        from web3 import Web3

        if request.param == "tester":
            setup_fn = setup_tester_rpc_provider
        elif request.param == "rpc":
            setup_fn = setup_rpc_provider
        elif request.param == "ipc":
            setup_fn = setup_ipc_provider
        else:
            raise ValueError("Unknown param")

>       with setup_fn() as provider:

PycharmProjects/web3.py/conftest.py:171: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/usr/lib/python3.5/contextlib.py:59: in __enter__
    return next(self.gen)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

    @contextlib.contextmanager
    def setup_tester_rpc_provider():
>       from testrpc import testrpc
E       RuntimeError: cannot release un-acquired lock

PycharmProjects/web3.py/conftest.py:99: RuntimeError

Cute Animal Picture

cute animal

Semantic cleanup of the `web3.contract.Contract` interface.

What was wrong?

The following cleanup would help the library in small ways.

The term Contract is not entirely correct. I have been using the term ContractFactory elsewhere and I like it more. Ideally we step through the codebase and replace all names so that they match this moniker.

The actual ContractFactory instances returned by web3.eth.contract are all classes of the same name. I propose changing the function signature to allow one extra optional keyword name. When provided, the class returned from this method would be named with the provided name rather than the boring 'Contract' name that they all currently hold.

Cute Animal Picture

put a cute animal picture here.

dog-with-toy-cover

Strange error from `ethereum.tester`

What was wrong?

On most commands this comes out of standard out when the interpreter exits.

Exception ignored in: <bound method state.__del__ of <ethereum.tester.state object at 0x11350ca20>>
Traceback (most recent call last):
  File "/Users/piper/python-environments/web3.py/lib/python3.5/site-packages/ethereum/tester.py", line 187, in __del__
AttributeError: 'NoneType' object has no attribute 'rmtree'

What is going on?

This is a race condition that occurs when the interpreter is shutting down. The upstream library eth-testrpc needs to be patched so that it doesn't create the instance of the tester client on module import but rather on demand somehow.

Bug in calling methods automatically generated by solidity for public contract attributes

  • Version: 656903b (current master)
  • Python: 2.7/3.4/3.5
  • OS: osx/linux/win

What was wrong?

For solidity code:

contract A {
    mapping (address => bytes32[]) public somename;
}

solc will generate function with ABI:

{
            "constant": True,
            "inputs": [
                {
                    "name": "",
                    "type": "address"
                },
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "name": "somename",
            "outputs": [
                {
                    "name": "",
                    "type": "bytes32",
                    "value": "0x"
                }
            ],
            "payable": False,
            "type": "function"
        },

Notice that both name keys of inputs are empty.

The code in https://github.com/pipermerriam/web3.py/blob/master/web3/utils/abi.py#L162
Will squash two arguments pased to Contract.call().somename(addr, index) into one argument because it uses name as unique identifier.

(Note, above examples are edited from my code so I haven't actually compile this exact code to reproduce the issue)

Cute Animal Picture

Cute animal picture

Intermittent timeout problems

  • Version: latest from the main branch
  • Python: 2.7.12
  • OS: ubuntu 16.04

What was wrong?

I have 3k+ database records to write to a smart contract. Unfortunately, after writing a few records, I'm getting intermittent timeout problems. Here's a traceback of one such occasion:

Traceback (most recent call last):
  File "dataReader.py", line 306, in <module>
    main()
  File "dataReader.py", line 303, in main
    blockchain_writer.writeRecords()
  File "dataReader.py", line 242, in writeRecords
    self.__setCulturalHeritageRecord(coId, record[self.cultural_heritage_keys[CulturalHeritageIndexList.AccessionNumber]])
  File "dataReader.py", line 186, in __setCulturalHeritageRecord
    self.contract.transact().createCulturalHeritageRecord(coId, accessionNumber)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/contract.py", line 815, in transact_with_contract_function
    txn_hash = contract.web3.eth.sendTransaction(transact_transaction)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/utils/string.py", line 86, in inner
    return force_obj_to_text(fn(*args, **kwargs))
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/eth.py", line 252, in sendTransaction
    transaction=formatted_transaction,
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/utils/transactions.py", line 53, in get_buffered_gas_estimate
    gas_estimate = web3.eth.estimateGas(gas_estimate_transaction)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/utils/functional.py", line 22, in inner
    value = fn(*args, **kwargs)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/eth.py", line 295, in estimateGas
    [formatted_transaction],
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/providers/manager.py", line 42, in request_blocking
    response_raw = self.provider.make_request(method, params)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/providers/rpc.py", line 49, in make_request
    **self.get_request_kwargs()
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/web3/utils/compat/compat_requests.py", line 21, in make_post_request
    response = session.post(endpoint_uri, data=data, *args, **kwargs)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/requests/sessions.py", line 535, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/home/s/sh/sh601/.local/lib/python2.7/site-packages/requests/adapters.py", line 499, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='localhost', port=8545): Read timed out. (read timeout=10)

...geth was busy mining a potential block at that point. Any ideas how I might overcome that? I'd rather block and wait (or something) rather than just fail....

Cute Animal Picture

This will grow up to be a vicious killer

Typo in documentation

this Line in the docs is wrong.

It currently is:

        >>> def new_block_callback(block_hash):
        ...     sys.stdout.write("New Block: {0}".format(block_hash))
        ...
        >>> new_block_filter = web3.eth.filter('latest')
        >>> new_block_filter.watch(new_block_filter)

It should be

        >>> def new_block_callback(block_hash):
        ...     sys.stdout.write("New Block: {0}".format(block_hash))
        ...
        >>> new_block_filter = web3.eth.filter('latest')
        >>> new_block_filter.watch(new_block_callback)

Add a new `Manager` class that allows transaction sending without an unlocked node.

What was wrong?

It would be nice to have Manager class which would translate any call to eth_sendTransaction to one of eth_sendRawTransaction or personal_sendTransaction. This would allow running against locked nodes and still being able to send transactions without modifying application code.

How to do it

Probably with a new (RequestManager](https://github.com/pipermerriam/web3.py/blob/master/web3/providers/manager.py#L8) class which would inspect the requests coming in and translate them to the proper requests.

Something like the following.

class SendRawTransactionMixin(object):
    def request_blocking(self, method, params):
        if method == 'eth_sendTransaction':
            # create a fully signed transaction and send through the
            # `eth_sendRawTransaction` endpoint instead.
            ... 

Cute Animal Picture

the-lizard-wizard-761

sendTransaction socket.timeout

  • Version: latest
  • Python: 2.7
  • OS: linux

What was wrong?

I'm trying to send a transaction from an account to Ropsten another but I got error socket timeout

Traceback (most recent call last):
  File "rpc-client.py", line 11, in <module>
    print web3rpc.eth.sendTransaction({'to': john, 'from': web3rpc.eth.coinbase, 'value': 12345})
  File "/usr/local/lib/python2.7/dist-packages/web3/eth.py", line 243, in sendTransaction
    [formatters.input_transaction_formatter(self, formatted_transaction)],
  File "/usr/local/lib/python2.7/dist-packages/web3/providers/manager.py", line 37, in request_blocking
    response_raw = self.provider.make_request(method, params)
  File "/usr/local/lib/python2.7/dist-packages/web3/providers/rpc.py", line 161, in make_request
    response = self.client.post(self.path, body=request_data)
  File "/usr/local/lib/python2.7/dist-packages/geventhttpclient/client.py", line 218, in post
    return self.request(METHOD_POST, request_uri, body=body, headers=headers)
  File "/usr/local/lib/python2.7/dist-packages/geventhttpclient/client.py", line 200, in request
    block_size=self.block_size, method=method.upper(), headers_type=self.headers_type)
  File "/usr/local/lib/python2.7/dist-packages/geventhttpclient/response.py", line 298, in __init__
    super(HTTPSocketPoolResponse, self).__init__(sock, **kw)
  File "/usr/local/lib/python2.7/dist-packages/geventhttpclient/response.py", line 170, in __init__
    self._read_headers()
  File "/usr/local/lib/python2.7/dist-packages/geventhttpclient/response.py", line 190, in _read_headers
    data = self._sock.recv(self.block_size)
  File "/usr/local/lib/python2.7/dist-packages/gevent/_socket2.py", line 280, in recv
    self._wait(self._read_event)
  File "/usr/local/lib/python2.7/dist-packages/gevent/_socket2.py", line 179, in _wait
    self.hub.wait(watcher)
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 630, in wait
    result = waiter.get()
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 878, in get
    return self.hub.switch()
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 609, in switch
    return greenlet.switch(self)
socket.timeout: timed out 

Here is my python script (I'm connected to my server, assuming my remove server IP is : 128.49.52.154) :

from web3 import Web3, KeepAliveRPCProvider

web3rpc = Web3(KeepAliveRPCProvider())
web3rpc = Web3(KeepAliveRPCProvider(host="128.49.52.154", port="8545"))

john = '0xe7bcd3b454c18313fe88d679eaf41251a58793dd'

print web3rpc.eth.sendTransaction({'to': john, 'from': web3rpc.eth.coinbase, 'value': 12345})

I thought it was because I'm using the Ropsten testnet and I have to use TestRPCProvider instead of KeepAliveRPCProvider.

But when I'm using TestRPCProvider I have this error :

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 534, in run
    result = self._run(*self.args, **self.kwargs)
  File "/usr/local/lib/python2.7/dist-packages/gevent/baseserver.py", line 347, in serve_forever
    self.start()
  File "/usr/local/lib/python2.7/dist-packages/gevent/baseserver.py", line 291, in start
    self.init_socket()
  File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 1222, in init_socket
    StreamServer.init_socket(self)
  File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 80, in init_socket
    self.socket = self.get_listener(self.address, self.backlog, self.family)
  File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 91, in get_listener
    return _tcp_listener(address, backlog=backlog, reuse_addr=self.reuse_addr, family=family)
  File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 177, in _tcp_listener
    sock.bind(address)
  File "<string>", line 1, in bind
TypeError: an integer is required
<Greenlet at 0x7f43a554d550: <bound method WSGIServer.serve_forever of <WSGIServer at 0x7f43a5526a50 address=128.49.52.154>>> failed with TypeError

Exception AttributeError: "'NoneType' object has no attribute 'rmtree'" in <bound method state.__del__ of <ethereum.tester.state object at 0x7f43a5543650>> ignored

With this code :

from web3 import Web3, TestRPCProvider

web3rpc = Web3(TestRPCProvider())
web3rpc = Web3(TestRPCProvider(host="128.49.52.154", port="8545"))

print web3rpc.eth.coinbase

Anyone know how can I fix my socket error or TestRPCProvider error ? Or Maybe the socket timeout error is caused by the connection to my remote server ? The connection must be in localhost ?

Cute Animal Picture

Cute animal picture

Timed out

  • Version: Latest
  • Python: 2.7
  • OS: Linux/Ubuntu 14.04 LTS

What was wrong?

I am trying to create an account and list out the accounts. But i got "socket.timeout: timed out"

My Log is:

Traceback (most recent call last):
File "/home/insipc208/Desktop/Eth/Example/create_account.py", line 10, in
web3rpc.personal.newAccount('insoftindia')
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/web3/utils/string.py", line 83, in inner
return force_obj_to_text(fn(*args, **kwargs))
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/web3/personal.py", line 49, in newAccount
"personal_newAccount", [password],
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/web3/providers/manager.py", line 41, in request_blocking
response_raw = self.provider.make_request(method, params)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/web3/providers/rpc.py", line 160, in make_request
response = self.client.post(self.path, body=request_data)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/geventhttpclient/client.py", line 218, in post
return self.request(METHOD_POST, request_uri, body=body, headers=headers)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/geventhttpclient/client.py", line 200, in request
block_size=self.block_size, method=method.upper(), headers_type=self.headers_type)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/geventhttpclient/response.py", line 298, in init
super(HTTPSocketPoolResponse, self).init(sock, **kw)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/geventhttpclient/response.py", line 170, in init
self._read_headers()
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/geventhttpclient/response.py", line 190, in _read_headers
data = self._sock.recv(self.block_size)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/gevent/_socket2.py", line 280, in recv
self._wait(self._read_event)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/gevent/_socket2.py", line 179, in _wait
self.hub.wait(watcher)
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/gevent/hub.py", line 630, in wait
result = waiter.get()
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/gevent/hub.py", line 878, in get
return self.hub.switch()
File "/opt/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/gevent/hub.py", line 609, in switch
return greenlet.switch(self)
socket.timeout: timed out

My Code:

from web3 import Web3, KeepAliveRPCProvider, IPCProvider

web3rpc = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))

print dir(web3rpc.personal.web3.eth)

web3rpc.personal.newAccount('insoftindia')

print web3rpc.eth.accounts

Using testnet:

pyethapp --profile morden --data-dir '/home/insipc208/Desktop/Eth/pyethapp_data/state' -c jsonrpc.listen_port=8545 run

Could please suggest to solve this?

Cute Animal Picture

Cute animal picture

default ipc path incorrect ?

  • Version: 2.7.1
  • Python: 2.7/3.4/3.5
  • OS: /linux/

What was wrong?

I have a running node launched with geth, no params

In[3]: from web3 import Web3, IPCProvider
In[4]: web3 = Web3(IPCProvider())
In[5]: web3.eth.coinbase
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-5-951bbb3a23b6>", line 1, in <module>
    web3.eth.coinbase
  File "/usr/local/lib/python3.5/dist-packages/web3-2.7.1-py3.5.egg/web3/eth.py", line 70, in coinbase
    return self.request_manager.request_blocking("eth_coinbase", [])
  File "/usr/local/lib/python3.5/dist-packages/web3-2.7.1-py3.5.egg/web3/providers/manager.py", line 20, in request_blocking
    response_raw = self.provider.make_request(method, params)
  File "/usr/local/lib/python3.5/dist-packages/web3-2.7.1-py3.5.egg/web3/providers/ipc.py", line 86, in make_request
    with get_ipc_socket(self.ipc_path) as sock:
  File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__
    return next(self.gen)
  File "/usr/local/lib/python3.5/dist-packages/web3-2.7.1-py3.5.egg/web3/providers/ipc.py", line 27, in get_ipc_socket
    sock.connect(ipc_path)
  File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 294, in connect
    raise error(result, strerror(result))
FileNotFoundError: [Errno 2] No such file or directory
In[6]: web3.currentProvider.ipc_path
Out[6]: '/home/user/ethereum/geth.ipc'

debugging the stuff makes me think that in this part in https://github.com/pipermerriam/web3.py/blob/master/web3/providers/ipc.py#L49-L55 there should be a .ethereum instead of ethereum, or I'm smoking and don't use it correctly ?

    elif sys.platform.startswith('linux'):
        return os.path.expanduser(os.path.join(
            "~",
            "ethereum",
            testnet,
            "geth.ipc",
        ))

on my computer the geth.ipc is there : '/home/user/.ethereum/geth.ipc'

Cute Animal Picture

Cute animal picture

Callback functions not getting called for latest block creation.

  • Version: 2.9.0
  • Python: 2.7
  • OS: linux

What was wrong?

I'm following the tutorial given in the web3.py documentation page for filtering new blocks.
The callback function that I register with the newly created filter is not getting called on receipt of new block.However,If I query the filter chages using 'getFilterChanges' method, I can see the new blocks.
Code (Running in the interpreter):

import sys
from web3 import Web3,RPCProvider
web3 = Web3(RPCProvider(host="eth3.augur.net",port="8545"))

def new_block_callback(block_hash):
        sys.stdout.write("New Block: {0}".format(block_hash))

new_block_filter = web3.eth.filter("latest")
new_block_filter.watch(new_block_callback)
new_block_filter.filter_id      #Prints 0x219eb3a71c4b3c4074e883e708928d55
new_block_filter.running      #Prints nothing,not even false
new_block_filter.stopped     #Prints false
#No prints even after few block generation

web3.eth.getFilterChanges('0x219eb3a71c4b3c4074e883e708928d55')    #Prints list of all newly generated block

Cute Animal Picture

Cute animal picture

No connection reuse

  • Version: 3.5.2 Release
  • Python: 2.7
  • OS: alpine linux within Docker

What was wrong?

I was using web3.py within Hive, basically it's run within a docker container and performs various queries against a client.

In one of the tests, I'm verifying a lot of conditions, ~30K. After 28232 requests, the lib failed with the following exception : requests.packages.urllib3.connection.HTTPConnection object at 0x7f4b0a86a750\u003e: Failed to establish a new connection: [Errno 99] Address not available

@karalabe pointed out that 28232 == 61000- 32768. That is; I was exhausing all the TCP ports linux lets me use for outbound connections.

According to requests docs: http://docs.python-requests.org/en/master/user/advanced/#keep-alive:

Excellent news โ€” thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!

However, the library does not use a session:

https://github.com/pipermerriam/web3.py/blob/master/web3/utils/compat/compat_requests.py#L6

def make_post_request(endpoint_uri, data, *args, **kwargs):
    kwargs.setdefault('timeout', 10)
    response = requests.post(endpoint_uri, data=data, *args, **kwargs)

In my case, I only really need a couple of the methods, and it was simple enough to implement these myself using a requests, skipping web3.py altogethere. But it may be an idea to add support for this kind of usecase anyway, since connection reuse also adds a bit of speed, and the library is likely to use the same endpoint over and over again.

With my session-based thingy, the problem went away.

Cute Animal Picture

piper

He's a bit disappointed right now

AttributeError: module '_sha3' has no attribute 'sha3'

  • Version: 1.6.0
  • Python: 2.7/3.4/3.5
  • OS: osx/linux/win

What was wrong?

running tox pass the tests fine
but running them individually yields this error on some
I guess it's my local install since tox is fime, but couldnt find the root of it

โžœ  web3.py git:(master) โœ— sudo pip3 uninstall pysha3
Uninstalling pysha3-0.3:
  /usr/local/lib/python3.5/dist-packages/pysha3-0.3-py3.5-linux-x86_64.egg

pysha3 0.3 is install, seems to be the right version

โ”€
โžœ  web3.py git:(master) โœ— py.test-3 tests/filtering/test_contract_on_event_filtering.py
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 283, in _getconftestmodules
    return self._path2confmods[path]
KeyError: local('/home/lotsos/PycharmProjects/web3.py/tests/filtering/test_contract_on_event_filtering.py')

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 283, in _getconftestmodules
    return self._path2confmods[path]
KeyError: local('/home/lotsos/PycharmProjects/web3.py/tests/filtering')

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 314, in _importconftest
    return self._conftestpath2mod[conftestpath]
KeyError: local('/home/lotsos/PycharmProjects/web3.py/tests/filtering/conftest.py')

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 320, in _importconftest
    mod = conftestpath.pyimport()
  File "/usr/local/lib/python3.5/dist-packages/py/_path/local.py", line 650, in pyimport
    __import__(modname)
  File "/home/lotsos/PycharmProjects/web3.py/tests/filtering/conftest.py", line 6, in <module>
    assert sha3_256(b'').hexdigest() == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
  File "/usr/local/lib/python3.5/dist-packages/sha3/__init__.py", line 97, in sha3_256
    return SHA3256(s)
  File "/usr/local/lib/python3.5/dist-packages/sha3/__init__.py", line 30, in __init__
    self._s = _sha3.sha3()
AttributeError: module '_sha3' has no attribute 'sha3'
ERROR: could not load /home/lotsos/PycharmProjects/web3.py/tests/filtering/conftest.py

Cute Animal Picture

put a cute animal picture here.

json encode error : TypeError: Decimal('100000000000000000000') is not JSON serializable when sending a transaction

  • Version: 1.6.0
  • Python: 2.7/3.4/3.5
  • OS: linux

What was wrong?

I'm trying to create an account and send funds to it from the coinbase I got this error

DEBUG:requests.packages.urllib3.connectionpool:"POST / HTTP/1.1" 200 80
E
web3 = <web3.main.Web3 object at 0x7fc57de45d30>
request = <SubRequest 'account' for <Function 'test_buyAsset[rpc-0-param1]'>>
wait_for_transaction = <function wait_for_transaction.<locals>._wait_for_transaction at 0x7fc57e6a7d08>

    @pytest.fixture(params=[0])
    def account(web3, request, wait_for_transaction):
        if (len(web3.personal.listAccounts))< 2:
            log.debug('web3: {} {}'.format(web3, web3.personal.listAccounts))
            new_account = create_account(web3, password='test')
            log_who_got_what(web3)
>           tx = web3.eth.sendTransaction({"from": web3.eth.coinbase, "to": new_account, "value": to_wei(100, 'ether')})

PycharmProjects/ddn/tests/test_dudes.py:43: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/usr/local/lib/python3.5/dist-packages/web3-1.6.0-py3.5.egg/web3/eth.py:208: in sendTransaction
    [formatted_transaction],
/usr/local/lib/python3.5/dist-packages/web3-1.6.0-py3.5.egg/web3/providers/manager.py:20: in request_blocking
    response_raw = self.provider.make_request(method, params)
/usr/local/lib/python3.5/dist-packages/web3-1.6.0-py3.5.egg/web3/providers/rpc.py:17: in make_request
    request = self.encode_rpc_request(method, params)
/usr/local/lib/python3.5/dist-packages/web3-1.6.0-py3.5.egg/web3/providers/base.py:24: in encode_rpc_request
    "id": next(self.request_counter),
/usr/lib/python3.5/json/__init__.py:230: in dumps
    return _default_encoder.encode(obj)
/usr/lib/python3.5/json/encoder.py:198: in encode
    chunks = self.iterencode(o, _one_shot=True)
/usr/lib/python3.5/json/encoder.py:256: in iterencode
    return _iterencode(o, 0)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <json.encoder.JSONEncoder object at 0x7fc5833e9f98>
o = Decimal('100000000000000000000')

    def default(self, o):
        """Implement this method in a subclass such that it returns
            a serializable object for ``o``, or calls the base implementation
            (to raise a ``TypeError``).

            For example, to support arbitrary iterators, you could
            implement default like this::

                def default(self, o):
                    try:
                        iterable = iter(o)
                    except TypeError:
                        pass
                    else:
                        return list(iterable)
                    # Let the base class default method raise the TypeError
                    return JSONEncoder.default(self, o)

            """
>       raise TypeError(repr(o) + " is not JSON serializable")
E       TypeError: Decimal('100000000000000000000') is not JSON serializable

/usr/lib/python3.5/json/encoder.py:179: TypeError

Cute Animal Picture

parresseux

`web3.eth.contract` does not perform validation on `address` parameter.

What was wrong?

This code does not throw any errors or warnings.

abi = [...]  # the contract ABI
code = "0x..."  # the contract code
web3.eth.contract(abi, code)

The above code is actually passing in the code as the address parameter since the function signature of web3.eth.contract is def contract(self, abi, address=None, **kwargs):.

Validating the address is well formed (and potentially normalizing it) is trivial to do and would keep this subtle error from happening.

Cute Animal Picture

baby_squirrel_sleeping

deplying empty contract

  • Version: 2.7.1
  • Python: 2.7
  • OS: osx

What was wrong?

I used this code to deploy new contracts

    abi_json = json.loads(abi)
    ContractFactory = web3rpc.eth.contract(abi_json, code=bytesource)
    txhash = ContractFactory.deploy()

It used to work for a while till around 2 weeks ago it just deploys empty contracts. I've tried changing everything on my ABI and bytecode (e.g adding 0x in from of the bytecode) but nothing seems to fix it. Any ideas why this might happen? any incompatibility with new geth update?

String type support

What was wrong?

Currently web3.py does not encode string types in functions. This e.g. prevents creating standard token contracts as the constructor fails.

  _type = b'string', value = b'Mootoken'
  ValueError: Unsupported type

Suggested patch

Assume implicit UTF-8 encoding.

Update Math test contract in contracts/conftest.py or add new test contract to contain some string set functions.

contract Math {
    uint public counter;
    string public name;

    event Increased(uint value);

    function increment() public returns (uint) {
        return increment(1);
    }

    function increment(uint amt) public returns (uint result) {
        counter += amt;
        result = counter;
        Increased(result);
        return result;
    }

    function add(int a, int b) public returns (int result) {
        result = a + b;
        return result;
    }

    function multiply7(int a) public returns (int result) {
        result = a * 7;
        return result;
    }

    function return13() public returns (int result) {
        result = 13;
        return result;
    }

    function setName(string _name) {
        name = _name;
    }

   function returnString() public returns (string result) {
       result = "Abracadabra";
       return result;
  }
}

Stress these functions in test_contract_call_interface.py and test_contract_transact_interface.

Cute Animal Picture

Potato cod

How to react to an unreachable node when dealing with filters

  • Version: 3.1.1
  • Python: 2.7
  • OS: linux

What was wrong?

If I have a server running that gets events from a node with the contract.on method, it seems that if it fails because the node is currently not available, it is dead forever and I have no way of reacting to that.

see traceback:

Traceback (most recent call last):
  File ".../local/lib/python2.7/site-packages/gevent/greenlet.py", line 534, in run
    result = self._run(*self.args, **self.kwargs)
  File ".../local/lib/python2.7/site-packages/web3/utils/filters.py", line 80, in _run
    changes = self.web3.eth.getFilterChanges(self.filter_id)
  File ".../local/lib/python2.7/site-packages/web3/utils/functional.py", line 22, in inner
    value = fn(*args, **kwargs)
  File ".../local/lib/python2.7/site-packages/web3/eth.py", line 310, in getFilterChanges
    "eth_getFilterChanges", [filter_id],
....
, in _create_socket
    raise first_error
error: [Errno 111] Connection refused
<LogFilter at 0x7fef3bfd9870> failed with error

I think it should reconnect and work again a soon as the nodes is available again, or there should be an easy way (maybe I am just not aware of it?) to react to this and reconnect in the application code, but I don't know how to do that because it runs in a Greenlet, so I don't know how to catch the Exception.

Thanks for the help.

Cute Animal Picture

Cute animal picture

Add a `CachedManager` class that can be used to cache provider responses.

What is wrong?

Lots of things that web3 returns could be easily cached.

How could it be implemented.

The initial idea looks something like this.

  • Use an LRU cache or something similar so that the cache is some fixed size.
  • Some things can be cached simply by the args they were looked up with. (blocks, transaction receipts, mined transactions)
  • Some things can be cached by block number (any eth_call, transactions)
  • Some things can be cached by time (like eth_blockNumber/eth_coinbase could be throttled so that it will only actually make an RPC request at most once per second)

Cute Animal Picture

j4hps

how you debug ?

  • Version: 0.3.0
  • Python: 2.7/3.4/3.5
  • OS: linux

What was wrong?

i pass all the tests fine but trying to debug them yields this error
cant see why pycharm debugger refuses to kick in

/usr/bin/python3.5 /home/lotsos/pycharm-2016.2/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 35745 --file /home/lotsos/pycharm-2016.2/helpers/pycharm/pytestrunner.py -p pytest_teamcity /home/lotsos/PycharmProjects/web3.py/tests/contracts/test_contract_class_construction.py
Testing started at 16:20 ...
Connected to pydev debugger (build 162.1237.1)
pydev debugger: process 5982 is connecting

/usr/local/lib/python3.5/dist-packages/gevent-1.1.2-py3.5-linux-x86_64.egg/gevent/monkey.py:395: RuntimeWarning: Monkey-patching not on the main thread; threading.main_thread().join() will hang from a greenlet
  _warnings)
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 171, in __exit__
  File "<frozen importlib._bootstrap>", line 123, in release
RuntimeError: cannot release un-acquired lock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/pydevd.py", line 1556, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/pydevd.py", line 940, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/lotsos/pycharm-2016.2/helpers/pycharm/pytestrunner.py", line 60, in <module>
    main()
  File "/home/lotsos/pycharm-2016.2/helpers/pycharm/pytestrunner.py", line 34, in main
    pluginmanager=_pluginmanager, args=args)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 338, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 333, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 595, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 249, in _wrapped_call
    wrap_controller.send(call_outcome)
  File "/usr/lib/python3/dist-packages/_pytest/helpconfig.py", line 28, in pytest_cmdline_parse
    config = outcome.get_result()
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 278, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 264, in __init__
    self.result = func()
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 596, in execute
    res = hook_impl.function(*args)
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 861, in pytest_cmdline_parse
    self.parse(args)
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 966, in parse
    self._preparse(args, addopts=addopts)
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 927, in _preparse
    self.pluginmanager.load_setuptools_entrypoints("pytest11")
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 501, in load_setuptools_entrypoints
    plugin = ep.load()
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 2235, in load
    return self.resolve()
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 2241, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 171, in __exit__
  File "<frozen importlib._bootstrap>", line 123, in release
RuntimeError: cannot release un-acquired lock
Error in sys.excepthook:
Traceback (most recent call last):
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/_pydevd_bundle/pydevd_breakpoints.py", line 119, in _excepthook
    thread.additional_info.pydev_message = exception_breakpoint.qname
AttributeError: '_DummyThread' object has no attribute 'additional_info'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/_pydevd_bundle/pydevd_breakpoints.py", line 121, in _excepthook
    thread.additional_info.pydev_message = exception_breakpoint.qname.encode('utf-8')
AttributeError: '_DummyThread' object has no attribute 'additional_info'

Original exception was:
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 171, in __exit__
  File "<frozen importlib._bootstrap>", line 123, in release
RuntimeError: cannot release un-acquired lock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/pydevd.py", line 1556, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/pydevd.py", line 940, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/home/lotsos/pycharm-2016.2/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/lotsos/pycharm-2016.2/helpers/pycharm/pytestrunner.py", line 60, in <module>
    main()
  File "/home/lotsos/pycharm-2016.2/helpers/pycharm/pytestrunner.py", line 34, in main
    pluginmanager=_pluginmanager, args=args)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 338, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 333, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 595, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 249, in _wrapped_call
    wrap_controller.send(call_outcome)
  File "/usr/lib/python3/dist-packages/_pytest/helpconfig.py", line 28, in pytest_cmdline_parse
    config = outcome.get_result()
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 278, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 264, in __init__
    self.result = func()
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 596, in execute
    res = hook_impl.function(*args)
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 861, in pytest_cmdline_parse
    self.parse(args)
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 966, in parse
    self._preparse(args, addopts=addopts)
  File "/usr/lib/python3/dist-packages/_pytest/config.py", line 927, in _preparse
    self.pluginmanager.load_setuptools_entrypoints("pytest11")
  File "/usr/lib/python3/dist-packages/_pytest/vendored_packages/pluggy.py", line 501, in load_setuptools_entrypoints
    plugin = ep.load()
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 2235, in load
    return self.resolve()
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 2241, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 171, in __exit__
  File "<frozen importlib._bootstrap>", line 123, in release
RuntimeError: cannot release un-acquired lock

Process finished with exit code 1
Empty test suite.

Cute Animal Picture

put a cute animal picture here.

Web3 depends on testrpc.rpc

  • Version: 3.4.1
  • Python: 2.7/3.4/3.5
  • OS: win

What was wrong?

The main web3 now depens on testrpc.rpc package, not even listed in requirements. So firstly web3 cannot be used without installing additional eth-testrpc. Moreover, eth-testrpc is not installable on Windows so we are all f*cked.

Cute Animal Picture

Cute animal picture

Refactor Formatters

  • Remove mutation. The functions should not mutate the values passed into them.
  • Rename to python naming conventions.
  • Remove duplicate functions.
  • Add tests for formatters.

Timeout error when I tried to send transaction

I don't understanda why, but since few days, I can't send transaction.
When I do web3.eth.sendTransaction(transaction) I've this error timeout: timed out.

the transaction looks like this : transaction = {'from': user2, 'to':user1, 'data': web3.toHex("test")}
And user1 and user2are defined . Accounts are unlocked and have gas...

Have you got any idea?

Windows IPC/Named pipe does not work

Right now web3.py use sockets on GNU/Linux to connect to the IPC. This wont work on Windows since named pipes on windows does not make use of sockets. From what google says you can use a simple file handle to write and read on the named pipe (.\pipe\geth.ipc). I have tried using simple popen/open to read and write data, but no luck.

I have also tried to use this library for python, http://docs.activestate.com/activepython/2.6/pywin32/win32file.html

Next step is to check how the JS-version of web3 is connecting to the named pipe, but i can imagine that it uses a more low level connection directly via ethereum code base.

Question On Process

Hi,

I was interested in adding more of the Web3 functionalities. I'm not a developer and just wanted to ask a basic question. Is it fair to say that the web3.py package formats requests into JSON RPC requests and passes onto a running ethereum node? I tried to go through the source code, but it seems like there's a lot of abstraction taking place through a package that's imported (which also seems to be labelled "web3").

If the above is true, I also struggled to see where the JSON RPC request is actually being formed.

Sorry, no cute animal pictures as this is a question rather than a pull request.

Importing TestRPCProvider gives an error.

  • Version: 1.6.0
  • Python: 2.7
  • OS: Ubuntu 14.04

What was wrong?

Importing TestRPCProvider gives an error.

In [1]: from web3 import Web3, TestRPCProvider
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-92ad247d8f86> in <module>()
----> 1 from web3 import Web3, TestRPCProvider

ImportError: cannot import name TestRPCProvider

Cute Animal Picture

Cute animal picture
image

Difficulty to set up infura RPCprovider

  • Version: x.x.x
  • Python: 2.7/3.4/3.5
  • OS: linux (cloud9)

What was wrong?

I registred on Infura, got my token GNAGNAGNA
I read the doc and find infura mention at:
http://web3py.readthedocs.io/en/latest/managers.html

web3 = Web3(Web3.RPCProvider(host='mainnet.infura.io', path='your-infura-access-key'))

I have been trying to use syntaxes:

web3 = Web3(Web3.RPCProvider(host='mainnet.infura.io', path='GNAGNAGNA'))
web3 = Web3(Web3.RPCProvider(host='ropsten.infura.io', path='GNAGNAGNA'))
web3 = Web3(Web3.RPCProvider(host='https://mainnet.infura.io', path='GNAGNAGNA'))
web3 = Web3(Web3.RPCProvider(host='http://mainnet.infura.io', path='GNAGNAGNA'))

none of them seems to work although on nodejs:

web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/GNAGNAGNA"));

works properly

Cute Animal Picture

Cute animal picture

happy holidays !

Wrong owner address while using py.test

What was wrong?

Hi,
Tried to deploy a very simple contract (divided in two files), with an owner variable (owner = msg.sender).
The problem is that when I launch some tests, the returned value is not the good one (checked on etherscan for the contract owner ad it's good).
I created a getter function that just returns an adress type variable . I am of course returning owner.
So I was wondering , is returning an address from a contract going to be well interpreted by python (address -> string) ? Or do I have a weird problem here ?

Thanks !

Cute Animal Picture

Cute animal picture

Implement a new provider that talks directly to `ethereum-tester-client`

What was wrong?

The current pyethereum.tester backed provider piggy backs on the web3.providers.rpc.RPCProvider and does all of it's interactions over a local HTTP server. This adds significant overhead to the interactions.

The proposed solution would be to create a new provider at web3.providers.tester.TesterProvider that talks directly to ethereum-tester-client

Cute Animal Picture

put a cute animal picture here.

tumblr_m9g1n1umq31qbwakso1_1280

Web3IPC - Socket Error

  • Version: 0.1.9
  • Python: 2.7
  • OS: linux

geth.ipc path is given correctly, but I face this error while connecting.
RPC works fine.

File "/usr/local/lib/python2.7/dist-packages/web3/web3/ipcprovider.py", line 36, in init
self.socket = self.getSocket()
File "/usr/local/lib/python2.7/dist-packages/web3/web3/ipcprovider.py", line 42, in getSocket
sock.connect(self.ipcpath)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 2] No such file or directory

Implement support for "function" abi type

  • Version: 3.6.1
  • Pyhon: 2.7
  • OS: macOS

What was wrong?

In (ethereum/solidity#1122) a "function" abi type was added. This is not yet implemented in web3.py

Example:
In my_contract:
function truebool(address a) external constant returns (bool){ return true;}

function get_function() external constant returns( function(address) external constant returns(bool) ){ return (this.truebool); }

In python:
func = my_contract.call().get_function() #returns function type my_other_contract.transact({...}).other_function(func) #expects function type as arg

Currently, func will have value None. It seems like the function type is similar to bytes24 per (http://solidity.readthedocs.io/en/develop/types.html) under function types.

It is possible to trick web3.py to return the function by changing the output type to "bytes24" in the abi for the contract, but this doesn't seem to work for input types; parity gives a Transaction execution error when trying to call other_function(func).

Cute Animal Picture

cute-polar-bear

`Filter.watch` is awkward if you don't know how to use gevent (or even if you do)

  • Version: x.x.x
  • Python: 2.7/3.4/3.5
  • OS: osx/linux/win

What was wrong?

Currently, this won't work.

filter = web3.eth.filter('latest')
filter.watch(sys.stdout.write)

while filter.running:
    gevent.sleep(0)

The reason it doesn't work is that until the first gevent.sleep(..) call happens to yield the execution context, the filter's greenlet doesn't actually spin up.

How can it be fixed.

I think that this could be fixed one or both of two ways.

  • Within Filter.watch add a gevent.sleep(0) to allow the greenlet to spin up. (This might be a bad idea. It feels a little wrong but it might just work fine)
  • Within the Filter.watch method set the running flag to True so that the pattern above will work.

Cute Animal Picture

1356835726-0

-1 on int8 weird value

  • Version: 3.4.4
  • Python: 2.7.10
  • OS: osx

What was wrong?

Assuming that "-1" can be represented by the int8 type (range -128;+127) I have this contract

contract Example {
    int8 myInt = -1;

    function getMyInt() constant returns (int8) {
        return myInt;
    }

    function getMyLittleInt() constant returns (int8 myLittleInt) {
        myLittleInt = -1;
    }
}

then I get an "instance" of this with web3.py and try to retrieve it but this is what I get :

>>> abi = json.loads('[{"constant":true,"inputs":[],"name":"getMyInt","outputs":[{"name":"","type":"int8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getMyLittleInt","outputs":[{"name":"myLittleInt","type":"int8"}],"payable":false,"type":"function"}]')
>>> myIntContract = web3.eth.contract(abi, address="0x1d4e3694b0155bf821963793ecac3b84f4a0815f")
>>> myIntContract
<web3.contract.Contract object at 0x1075a6290>
>>> myIntContract.call().getMyInt()
115792089237316195423570985008687907853269984665640564039457584007913129639679L
>>> myIntContract.call().getMyLittleInt()
115792089237316195423570985008687907853269984665640564039457584007913129639679L

Is that right ? What's wrong ?

Cute Animal Picture

Cute animal picture

Raise TransactionFailed instead of ValueError when there is an error in the contract

  • Version: 2.0.0
  • Python: 2.7
  • OS: linux

What was wrong?

When a contract throws, web3.py raises a ValueError, which has the exact type of error (TransactionFailed) hidden in its message. A ValueError in web3.py can be caused by something entirely different. Checking the fields of ValueError to make sure that it indeed is a TransactionFailed is inconvenient, and does not fit nicely into with pytest.raises() syntax.

I would like to be able to do the following:

with pytest.raises(TransactionFailed):
      contract.some_method.sendTransaction(invalid_args)

Cute Animal Picture

Cute animal picture

Non-helpful error message when calling contract on unsynced chain

  • Version: 3.6.2
  • Python: 2.7
  • OS: linux

What was wrong?

After initializing web3 against a local, unsynced ropsten chain, a new contract could not be called, eg. by con.call().get(). This is correct behaviour, but the error message:

BadFunctionCallOutput: Could not decode contract function call get return data 0x for output_types [u'string']

is not helpful and does not indicate where to look for an error.
Better would be something like

BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?

Cute Animal Picture

Cute animal picture

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.