@@ -4,7 +4,7 @@ Events and Logs
4
4
===============
5
5
6
6
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:
8
8
9
9
1. Query blocks for transactions that include the contract address in the ``"to" `` field.
10
10
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:
39
39
40
40
See an advanced example of fetching log history :ref: `here <advanced_token_fetch >`.
41
41
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.
43
81
44
82
.. warning ::
45
83
0 commit comments