Skip to content

Commit

Permalink
docs: eth_subscribe api, misc. cleanup (#3386)
Browse files Browse the repository at this point in the history
docs: subscribe api, misc. cleanup

---------

Co-authored-by: felipe <fselmo2@gmail.com>
  • Loading branch information
wolovim and fselmo committed May 13, 2024
1 parent 6ef4398 commit b2f5574
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 109 deletions.
2 changes: 2 additions & 0 deletions docs/providers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,8 @@ WebSocketProvider
available arguments.


.. _subscription-examples:

Using Persistent Connection Providers
+++++++++++++++++++++++++++++++++++++

Expand Down
2 changes: 1 addition & 1 deletion docs/resources.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Tutorials
---------

- Intro to `Ape development framework <https://snakecharmers.ethereum.org/intro-to-ape/>`__
- Intro to `websockets <https://snakecharmers.ethereum.org/websockets-v2/>`__ and web3.py
- Intro to `websockets <https://snakecharmers.ethereum.org/websocketprovider/>`__ and web3.py
- Intro to `asynchronous web3.py <https://snakecharmers.ethereum.org/web3-py-patterns-intro-async/>`__
- Intro to `threaded web3.py <https://snakecharmers.ethereum.org/web3-py-patterns-multithreading/>`__
- Sign `typed data messages <https://snakecharmers.ethereum.org/typed-data-message-signing/>`__ (EIP 712)
Expand Down
42 changes: 30 additions & 12 deletions docs/troubleshooting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,6 @@ If that does not address your issue, it's probable that you still have a
Provider configuration issue. There are several options for configuring
a Provider, detailed :ref:`here<providers>`.

How do I use my MetaMask accounts from web3.py?
-----------------------------------------------
Often you don't need to do this, just make a new account in web3.py,
and transfer funds from your MetaMask account into it. But if you must...

Export your private key from MetaMask, and use
the local private key tools in web3.py to sign and send transactions.

See `how to export your private key
<https://ethereum.stackexchange.com/questions/33053/what-is-a-private-key-in-an-ethereum-wallet-like-metamask-and-how-do-i-find-it>`_
and :ref:`eth-account`.

.. _faucets:

How do I get ether for my test network?
Expand All @@ -117,6 +105,16 @@ Each test network has its own version of test ether, so each one must maintain
its own faucet. Faucet mechanisms tend to come and go, so a web search for
"ethereum testnet faucet" should give you the most up-to-date options.

How do I use my MetaMask accounts from web3.py?
-----------------------------------------------

Export your private key from MetaMask, and use
the local private key tools in web3.py to sign and send transactions.

See `how to export your private key
<https://ethereum.stackexchange.com/questions/33053/what-is-a-private-key-in-an-ethereum-wallet-like-metamask-and-how-do-i-find-it>`_
and :ref:`eth-account`.

.. _account_troubleshooting:

How do I create an account?
Expand All @@ -131,6 +129,26 @@ In general, your options for accounts are:
.. Warning:: Don't store real value in an account until you are familiar with security best practices.
If you lose your private key, you lose your account!

Why doesn't my transaction work on another network?
---------------------------------------------------

web3.py is an Ethereum-specific library, which defaults to
`"type 2" EIP-1559 transactions <https://ethereum.org/en/developers/docs/transactions/#typed-transaction-envelope>`_
as of the London network upgrade. Some chains (including Ethereum L2s) do not support
the same transaction types.

If your chain doesn't support this transaction type, you likely need to create a
"legacy" transaction, i.e., include ``gasPrice``, but not ``type``, ``maxFeePerGas``,
or ``maxPriorityFeePerGas`` in your transaction body.

If that doesn't resolve your issue, open a GitHub issue or reach out for help in the community
`Discord`_ server if you're having trouble with an Ethereum-ecosystem chain. If you're
debugging in an alternative ecosystem, please find another appropriate forum to raise
your question.

.. _Discord: https://discord.gg/GHryRvPB84


How do I conform to ABI types?
------------------------------

Expand Down
174 changes: 86 additions & 88 deletions docs/web3.contract.rst
Original file line number Diff line number Diff line change
Expand Up @@ -437,37 +437,6 @@ Each Contract Factory exposes the following methods.
will be rejected.


.. _ambiguous-contract-functions:

Invoke Ambiguous Contract Functions Example
-------------------------------------------

Below is an example of a contract that has multiple functions of the same name,
and the arguments are ambiguous.

.. code-block:: python
>>> contract_source_code = """
pragma solidity ^0.4.21;
contract AmbiguousDuo {
function identity(uint256 input, bool uselessFlag) returns (uint256) {
return input;
}
function identity(int256 input, bool uselessFlag) returns (int256) {
return input;
}
}
"""
# fast forward all the steps of compiling and deploying the contract.
>>> ambiguous_contract.functions.identity(1, True) # raises Web3ValidationError
>>> identity_func = ambiguous_contract.get_function_by_signature('identity(uint256,bool)')
>>> identity_func(1, True)
<Function identity(uint256,bool) bound to (1, True)>
>>> identity_func(1, True).call()
1
.. _disable-strict-byte-check:

Disabling Strict Checks for Bytes Types
Expand Down Expand Up @@ -1262,60 +1231,6 @@ will be used to find the contract function by signature,
and forwarded to the contract function when applicable.


Contract FAQs
-------------

How do I pass in a struct as a function argument?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

web3.py accepts struct arguments as dictionaries. This format also supports nested structs.
Let's take a look at a quick example. Given the following Solidity contract:

.. code-block:: none
contract Example {
address addr;
struct S1 {
address a1;
address a2;
}
struct S2 {
bytes32 b1;
bytes32 b2;
}
struct X {
S1 s1;
S2 s2;
address[] users;
}
function update(X memory x) public {
addr = x.s1.a2;
}
function retrieve() public view returns (address) {
return addr;
}
}
You can interact with web3.py contract API as follows:

.. code-block:: python
# deploy or lookup the deployed contract, then:
>>> deployed_contract.functions.retrieve().call()
'0x0000000000000000000000000000000000000000'
>>> deployed_contract.functions.update({'s1': ['0x0000000000000000000000000000000000000001', '0x0000000000000000000000000000000000000002'], 's2': [b'0'*32, b'1'*32], 'users': []}).transact()
>>> deployed_contract.functions.retrieve().call()
'0x0000000000000000000000000000000000000002'
Examples
--------

Expand Down Expand Up @@ -1447,7 +1362,7 @@ spend using the ``allowance`` function.


Performing an external transfer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```````````````````````````````

When someone has an allowance they can transfer those tokens using the
``transferFrom`` function.
Expand All @@ -1469,10 +1384,93 @@ When someone has an allowance they can transfer those tokens using the
.. _ERC-20: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-20.md


Using a struct as a function argument
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

web3.py accepts struct arguments as dictionaries. This format also supports nested structs.
Let's take a look at a quick example. Given the following Solidity contract:

.. code-block:: none
contract Example {
address addr;
struct S1 {
address a1;
address a2;
}
struct S2 {
bytes32 b1;
bytes32 b2;
}
struct X {
S1 s1;
S2 s2;
address[] users;
}
function update(X memory x) public {
addr = x.s1.a2;
}
function retrieve() public view returns (address) {
return addr;
}
}
You can interact with the web3.py contract API as follows:

.. code-block:: python
# deploy or lookup the deployed contract, then:
>>> deployed_contract.functions.retrieve().call()
'0x0000000000000000000000000000000000000000'
>>> deployed_contract.functions.update({'s1': ['0x0000000000000000000000000000000000000001', '0x0000000000000000000000000000000000000002'], 's2': [b'0'*32, b'1'*32], 'users': []}).transact()
>>> deployed_contract.functions.retrieve().call()
'0x0000000000000000000000000000000000000002'
.. _ambiguous-contract-functions:

Invoke Ambiguous Contract Functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Below is an example of a contract that has multiple functions of the same name,
and the arguments are ambiguous. You can use the :meth:`Contract.get_function_by_signature`
method to reference the intended function and call it with the correct arguments.

.. code-block:: python
>>> contract_source_code = """
pragma solidity ^0.8.24;
contract AmbiguousDuo {
function identity(uint256 input, bool uselessFlag) public pure returns (uint256) {
return input;
}
function identity(int256 input, bool uselessFlag) public pure returns (int256) {
return input;
}
}
"""
# fast forward all the steps of compiling and deploying the contract.
>>> ambiguous_contract.functions.identity(1, True) # raises Web3ValidationError
>>> identity_func = ambiguous_contract.get_function_by_signature('identity(uint256,bool)')
>>> identity_func(1, True)
<Function identity(uint256,bool) bound to (1, True)>
>>> identity_func(1, True).call()
1
.. _ccip-read-example:

CCIP Read support for offchain lookup
-------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Contract calls support CCIP Read by default, via a ``ccip_read_enabled`` flag on the call and, more globally, a
``global_ccip_read_enabled`` flag on the provider. The following should work by default without raising an
Expand Down Expand Up @@ -1508,7 +1506,7 @@ appropriately in the following way:
tx_hash = w3.eth.send_transaction(tx)
Contract Unit Tests in Python
-----------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is an example of how one can use the `pytest`_ framework in python, web3.py,
eth-tester, and PyEVM to perform unit tests entirely in python without any
Expand Down
44 changes: 36 additions & 8 deletions docs/web3.eth.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,6 @@ web3.eth API

.. py:module:: web3.eth
.. warning:: Whoa there, Binance Smart Chain user! web3.py is an Ethereum-specific library,
which now defaults to "type 2" transactions as of the London network upgrade. BSC apparently
does not support these newer transaction types.

From issues opened, it seems BSC transactions must include ``gasPrice``, but not ``type``,
``maxFeePerGas``, or ``maxPriorityFeePerGas``. If you have trouble beyond that, please find an
appropriate BSC forum to raise your question.

.. py:class:: Eth
The ``web3.eth`` object exposes the following properties and methods to
Expand Down Expand Up @@ -1108,6 +1100,42 @@ The following methods are available on the ``web3.eth`` namespace.
``(web3, transaction_params)`` and return a gas price denominated in wei.


.. py:method:: Eth.subscribe(subscription_identifier, subscription_params)
* Delegates to ``eth_subscribe`` RPC Method
Only available on persistent connection providers:
:class:`~web3.providers.persistent.WebSocketProvider` and
:class:`~web3.providers.persistent.AsyncIPCProvider`.
Returns a subscription ID that can be used to track a particular subscription to, or unsubscribe from, an event.
For usage examples see the docs on :ref:`subscription-examples`.
.. code-block:: python
>>> subscription_id = await web3.eth.subscribe('newHeaders')
>>> subscription_id
'0xbd63bb89e7475591a0a6fc9014307bc4'
.. py:method:: Eth.unsubscribe(subscription_id)
* Delegates to ``eth_unsubscribe`` RPC Method
Only available on persistent connection providers:
:class:`~web3.providers.persistent.WebSocketProvider` and
:class:`~web3.providers.persistent.AsyncIPCProvider`.
Returns ``True`` if successfully unsubscribed. For usage examples see the docs on
:ref:`subscription-examples`.
.. code-block:: python
>>> result = await web3.eth.unsubscribe(subscription_id)
>>> result
True
Filters
-------

Expand Down
1 change: 1 addition & 0 deletions newsfragments/3386.docs.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add subscribe/unsubscribe API

0 comments on commit b2f5574

Please sign in to comment.