Programmatically Create an Ethereum Wallet With Python and Infura

July 5, 2022
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 or Alchemy 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 mnemo class. Then, we generate our phrase using mnemo.generate(strength=256).Finally, we generate seed using the words we generated in the previous step. You can choose to provide an extra passphrase 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 MAIN_NET_HTTP_ENDPOINT above. Then, initialize a class named w3 with the endpoint. 4. Initialize the account class: We use seed[:32] 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 private_key and import it using metamask. You can also print words and use it to recover your account. Here’s the code all together so it’s easier for you to copy:

Related Posts

Ethical AI Guide: Top 5 Principles for Responsible Technology

Ethical AI Guide: Top 5 Principles for Responsible Technology

In an age where AI understands our habits even better than our family, making technology ethical is essential. Data breaches, privacy scandals, and algorithms going rogue dominate headlines, proving that building ethical and trustworthy AI is not just about avoiding...

Ready to turn insights into action? Let our tech experts bring your vision to life. Hire us today.