Search code examples
javascriptblockchainethereumweb3jsmetamask

Accessing a private key in a MetaMask wallet


I have a simple Dapp and I want to sign a transaction but I don't have the private key as a string.

The user is using a MetaMask wallet. After they grant web3 access to their account, how can I access the private key to sign a transaction?

const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
// PRIVATE_KEY is what I'm trying to get.

Solution

  • Metamask doesn't share the private key directly for security reasons. And sometimes it doesn't even have the key - for instance when the user is using the Metamask UI to operate a hardware wallet account.

    You'll need to construct the transaction object and pass it to the ethereum.request() method. This will open the Metamask window where the user can sign or decline the transaction request.

    Code example is pretty straightforward and is in the linked documentation.