pythoncryptocurrencyweb3py

Listening to Uniswap contract events using web3.py and infura.io


I want to use web3.py and infura.io to listen for Uniswap factory events however I am not too sure where to go about doing so.

Here is a link: https://uniswap.org/docs/v2/smart-contracts/factory/

More specifically I want to listen for the PairCreated event.


Solution

  • Here is rough guide

    1. Get ABI for Uniswap contract

    2. Create a web3.py contract object

    3. You can use web3.eth.getLogs() to query events over past block range

    4. You cannot query all events once, because there are so many events and Infura would time out. Instead you need to query events carefully over a block range slices.

    Here is some old code which may or may not work with the latest web3.py versions

    https://github.com/TokenMarketNet/sto/blob/master/sto/ethereum/scanner.py#L153

    If you want a real time scanner you can listed to events over a WebSocket connection as they happen:

    https://web3py.readthedocs.io/en/stable/filters.html#asynchronous-filter-polling