1

I've been using local_account = w3.eth.account.create(keys['private_key_1']) to create a local account offline. When I check the public key returned from local_account.address it does not match the existing public key. What should I do?

P.S. The key returned is a string & I've tried changing the private key format from "0x12345" to "12345". I think this is a solution but I can't figure out how to instantiate the class and call the from_key method.

1 Answer 1

8

That's because the attribute of the function w3.eth.account.create(...) is not the private key.

To generate an account from an external private key you must use the function w3.eth.account.privateKeyToAccount(...).

Example:

>>> private_key = "f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315"
>>> acct = w3.eth.account.privateKeyToAccount(private_key)
>>> acct.address
'0x001d3F1ef827552Ae1114027BD3ECF1f086bA0F9'

privateKeyToAccount will be deprecated for version 0.5 and replaced by w3.eth.account.from_key(...).

Example:

>>> private_key = 0xf8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315
>>> acct = Account.from_key(private_key)
>>> acct.address
'0x001d3F1ef827552Ae1114027BD3ECF1f086bA0F9'
10
  • Thanks. Can this new account be used as the default account in order to sign and send transactions?
    – pjonson2
    Jun 4, 2019 at 14:26
  • 1
    You can set the default account doing w3.eth.defaultAccount = acct where acct is the account created previously. Check w3.eth.defaultAccount.address.
    – alberto
    Jun 4, 2019 at 16:09
  • I'm getting the same error as in this question ethereum.stackexchange.com/questions/97912/… when trying to run .transact() on a contract when setting w3.eth.default_account = Account.from_key(private_key). Look like it's expecting a string.
    – shellwhale
    Jun 16, 2021 at 11:37
  • @shellwhale You are giving an object as an argument, you should pass acct.address since it is the address as a string.
    – alberto
    Jun 16, 2021 at 11:59
  • 1
    What I'm saying is that you should write transact({'from': acct.address}) instead of transact({'from': acct}).
    – alberto
    Jun 16, 2021 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.