Interacting with Python
Using web3.py
Installation
We will use the web3.py
package to programatically interact with the Ethereum testnet.
Once installed, we can connect to the RPC using
In order to interact with contracts specifically, we need to be able to provide the ABI (Application Binary Interface) of the contract. An ABI decribes the protocol for interacting with a system, in this case, for interacting with the contract. Effectively, an ABI tells web3.py
exactly how to interact with the remote contract.
Luckily, we can use Python to generate the ABI from the source code itself. To do so, we need to install py-solc-x
:
py-solc-x
handles versions of solc
, the Solidity compiler. Different versions could generate different ABIs, so keep an eye on it, but generally it won't matter too much. Before we can use it to generate a contract's ABI, we have to install the version of solc
that we want:
Interacting with Contracts in Python
Now we can use the source code of the Solidity contract to generate an ABI for it. After that, everything is pretty self-explanatory!
Running this code multiple times shows the counter incrementing!
Accounts on Local Nodes
Typically transactions - such as the last line, with .transact()
- need to be signed using a private key. Here, we have not specified the private key, yet it still works. Why is that?
Our anvil
testnet spins up a node locally, with several unlocked accounts. Running the program locally, w3
will take the first unlocked account and use it. We can print the unlocked accounts out:
Comparing this to the output of anvil
, we see that they are the same addresses in the same order. To override this functionality, we can set the variable w3.eth.default_account
, which defaults to None
(and when it's None
, the default account used is w3.eth.accounts[0]
).
Alternatively, if it's a one-off, you can set the from
field in the transact
method:
Last updated
Was this helpful?