As a Python developer, it isn’t easy to find tutorials or articles on the ‘how to’ for creating Ethereum wallets. So, I spent hours figuring out the program and now you don’t have to.
If you choose to read on, what you’ll find below is the solution in ten lines of code.
In this tutorial, I will walk through how to create a unique public-private key pair for Ethereum and other EVM chains. I will use BIP-39
mnemonics, web3.py, and Infura
to achieve this.
Note: You can use any provider, like Moralis
to achieve the same. Just swap it out with Infura.
This code is compatible with Python 3.8+ and has been tested to work with Django 4.0.
Before we get started you will need to create an account on Infura.io
. Once that’s done and you have verified your information, you will see your Keys and your blockchain endpoint. We’ll come back to these at a later stage of the project.
Let’s install the mnemonic and web3.py libraries:
The above libraries install the dependencies you need to generate a mnemonic word list which is used to generate your Private Key using the BIP-39
standard. You will also need the web3.py library to interact with the blockchain.
1. Create a new file and import the required libraries:
2. Initialize the mnemonic class:
Let’s take a second to understand the code. First, we initialize the
class. Then, we generate our phrase using
Finally, we generate
using the words we generated in the previous step. You can choose to provide an extra
of your choice for extra security. You have now generated a unique private key for the Ethereum chain. Now let’s generate our public address from the above key.
3. Initialize web3.py:
Get your endpoint URL from Infura
and set it to
above. Then, initialize a class named
with the endpoint.
4. Initialize the account class:
above as we only need to use the 32-bit string of the seed as our private key.
5. Get your public and private keys:
And that’s it — you’re done!
And yes, it is that simple. Don’t believe me? You can print
and import it using metamask. You can also print
and use it to recover your account.
Here’s the code all together so it’s easier for you to copy: