Reputation: 187
I'm making my own desktop BSC wallet with web3. At the moment I'm using
private_key = "private key"
account = w3.eth.account.privateKeyToAccount(private_key)
But I want to create the account using a mnemonic phrase like "hello john pizza guitar". I have been searching but I can't manage to achieve it.
Upvotes: 8
Views: 12777
Reputation: 7373
This code generates 10 addresses with their private key ready to be copy/past in your python code:
from web3 import Web3
w3 = Web3()
# test mnemonic from ganache (don't use it!)
mnemonic = "witness explain monitor check grid depend music purchase ready title bar federal"
w3.eth.account.enable_unaudited_hdwallet_features()
for i in range(10):
acc = w3.eth.account.from_mnemonic(mnemonic, account_path=f"m/44'/60'/0'/0/{i}")
print(f"\naddress{i + 1} = '{acc.address}'")
print(f"private{i + 1} = '{Web3.toHex(acc.key)}'")
Upvotes: 3
Reputation: 1447
At this moment the requested feature is not stable inside Web3.py
web3 = Web3()
web3.eth.account.enable_unaudited_hdwallet_features()
account = web3.eth.account.from_mnemonic(my_mnemonic, account_path="m/44'/60'/0'/0/0")
Note: The default account_path
matches Ethereum and BSC as well. Iterating the last number you would get the next accounts. The account object could manage some operations
account.address # The address for the chosen path
account.key # Private key for that address
Upvotes: 11
Reputation: 331
If you don't care about using unaudited features you can use this:
w3.eth.account.enable_unaudited_hdwallet_features()
account = w3.eth.account.from_mnemonic("hello john pizza guitar")
print(account.address)
I couldn't find any mention of the unaudited features in the docs, but simply viewing the attributes of this (account) object I could find you have the following attributes:
full list (including private attributes):
['__abstractmethods__', '__bytes__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_address', '_key_obj', '_private_key', '_publicapi', 'address', 'encrypt', 'key', 'privateKey', 'signHash', 'signTransaction', 'sign_message', 'sign_transaction']
You should probably not use this account object to sign transactions as it is undocumented and in all examples of the docs, transactions are usually signed with private keys using web3.eth.sign_transaction(txn, key). You would have a hard time finding information about this object and its features, I stumbled upon this function accidentally thanks to vscode auto-completeion
Instead, use this to retrieve the private key and use it as seen in the docs
pk = account.privateKey
Upvotes: 5