Web3.py: How to send EIP-1559 transactions (ETH & ERC-20 tokens)
Hello friends! 👋
In this tutorial we’re going to take a look at how to use Web3.py to send EIP-1559 transactions, containing either ETH or any verified ERC-20 token. As usual, if you only need the script’s code, feel free to scroll down to the end of the article.
Script’s structure
The script will be split within two methods, one for sending ETH and another for sending ERC-20 tokens.
I recommend only using one method per script run, since the nonce can be erroneously calculated when two transactions are sent in a short amount of time. A fix for this can be, of course, manually incrementing the nonce for the second transaction.
Prerequisites
For this tutorial to work, you will need to have installed:
- web3.py (can be installed by running - pip install web3)
- dotenv (optional, but recommended for better security - pip install python-dotenv)
Setting up our project
Let’s start by importing the required libraries and creating our .env file, which will contain our account’s private key (you can use a test wallet without any real funds on it) and the Infura project ID.
If you need a little more help on creating a .env file, you can check out this article.
For this tutorial’s purposes you can also not use environmental variables, but it’s a good practice to use them, so the sensible information is not easily accessible within the code.
from web3 import Web3
import json
import os
from dotenv import load_dotenv
load_dotenv()
private_key = os.getenv('SIGNER_PRIVATE_KEY')
project_id = os.getenv('INFURA_PROJECT_ID')
infura_url = 'https://goerli.infura.io/v3/{}'.format(project_id)
web3 = Web3(Web3.HTTPProvider(infura_url))