[Ethereum] best to use – Private Key or Mnemonic

contract-designcontract-developmentmnemonicprivate-key

Is there a best practice for which one to use?

Many tutorials online take various approaches – the older ones seems to use mnemonic whereas the newer ones tends to utilize private key.

I understand that the mnemonic is the parent of all it's private keys – so I can see logically how the usage of a private key would be better in this sense.

Truffle seems to suggest mnemonic

I suppose this is related to the usage of HD Wallet Provider

Hardhat seems to suggest Private Key

In the case of Private Key/ Mnemonic:

[1] Is there a known best practice in this case and where is it defined?

[2] What is your preference and why have you chosen it to be so?

Best Answer

Directly pasting a mnemonic or a private keys in your code is a practice you should only use for non critical stuff like development on test network. Once you go in production, you will have to secure your keys another way. Tutorials usually don't show you that a lot.

That said, there's two ways to handle keys for your dapp (I assume you are talking about dapp development given the tools you mentioned):

  • let users handle the keys (metamask, hardware wallet,...) and only let your dapp work if a wallet is connected. This is really the preferred way and you don't have to hold any keys, just use the the API (see metamask JS API). It works for most use cases where users are the key holders (also provides the most decentralised architecture).

  • handle keys on your side, for instance on your local computer to deploy your smart contract and dapp or on server side (custodial architecture). I'm not fond of custodial architecture but it may make sense sometimes (in centralised exchanges for instance). In these cases, it's your responsibility to secure keys. You should make sure to properly hide the computer that holds the keys from the outside and anyone trying to hack your system. Contract deployment using Truffle should be signed using a hardware wallet (so you don't even know the private key and only have a backup mnemonic on paper safely hidden somewhere). For online custodial apps, favour use of signing proxies (search for instance for Ethsigner) and get keys secured using HSMs or Vaults so the private key doesn't leave the secure enclave. Any other setup is dangerous and will lead to hacks and loss of assets and confidence from your users.

Disclosure: as indicated in my profile, I work for Consensys that is the author of Ethsigner, an open source Apache 2.0 signer and Metamask, the open source wallet.

Related Topic