Skip to content

Commit 5df77f9

Browse files
authored
docs: add subscribe to logs page (#3403)
1 parent 877efc4 commit 5df77f9

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

docs/filters.rst

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Events and Logs
44
===============
55

66
If you're on this page, you're likely looking for an answer to this question:
7-
**How do I know when a specific contract is used?** You have at least three options:
7+
**How do I know when a specific contract is used?** You have several options:
88

99
1. Query blocks for transactions that include the contract address in the ``"to"`` field.
1010
This contrived example is searching the latest block for any transactions sent to the
@@ -39,7 +39,45 @@ If you're on this page, you're likely looking for an answer to this question:
3939
4040
See an advanced example of fetching log history :ref:`here <advanced_token_fetch>`.
4141

42-
3. Use a filter.
42+
3. Subscribe to events for real-time updates. When using a persistent connection provider
43+
(:class:`~web3.providers.persistent.WebSocketProvider` or
44+
:class:`~web3.providers.persistent.AsyncIPCProvider`), the
45+
:meth:`subscribe() <web3.eth.Eth.subscribe>` method can be used to establish a new
46+
event subscription. This example subscribes to ``Transfer`` events of the WETH contract.
47+
48+
.. code-block:: python
49+
50+
import asyncio
51+
from web3 import AsyncWeb3, WebSocketProvider
52+
from eth_abi.abi import decode
53+
54+
WETH_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
55+
56+
57+
async def subscribe_to_transfer_events():
58+
async with AsyncWeb3(WebSocketProvider("...")) as w3:
59+
transfer_event_topic = w3.keccak(text="Transfer(address,address,uint256)")
60+
filter_params = {
61+
"address": WETH_ADDRESS,
62+
"topics": [transfer_event_topic],
63+
}
64+
subscription_id = await w3.eth.subscribe("logs", filter_params)
65+
print(f"Subscribing to transfer events for WETH at {subscription_id}")
66+
67+
async for payload in w3.socket.process_subscriptions():
68+
result = payload["result"]
69+
70+
from_addr = decode(["address"], result["topics"][1])[0]
71+
to_addr = decode(["address"], result["topics"][2])[0]
72+
amount = decode(["uint256"], result["data"])[0]
73+
print(f"{w3.from_wei(amount, 'ether')} WETH from {from_addr} to {to_addr}")
74+
75+
asyncio.run(subscribe_to_transfer_events())
76+
77+
78+
For more usage examples see the docs on :ref:`subscription-examples`.
79+
80+
4. Use a filter.
4381

4482
.. warning ::
4583

newsfragments/3403.docs.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add an ``eth_subscribe`` example to the events guide

0 commit comments

Comments
 (0)