Accessing a private key in a MetaMask wallet
Asked Answered
R

3

5

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.
Rusell answered 2/4, 2021 at 3:28 Comment(0)
D
6

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.

Designer answered 2/4, 2021 at 9:24 Comment(0)
X
2

MetaMask does not give you access to a private key and never will.

The whole point of the wallet is to protect the user against malicious Dapps.

Xever answered 2/4, 2021 at 9:23 Comment(0)
C
1

Here's an example of how you would sign your Metamask transaction:

export const mintNFT = async(url, name, description) => {
    
    //error handling
    if (url.trim() == "" || (name.trim() == "" || description.trim() == "")) { 
        return {
            success: false,
            status: "❗Please make sure all fields are completed before minting.",
        }
    }
  
    //make metadata
    const metadata = new Object();
    metadata.name = name;
    metadata.image = url;
    metadata.description = description;

    //pinata pin request
    const pinataResponse = await pinJSONToIPFS(metadata);
    if (!pinataResponse.success) {
        return {
            success: false,
            status: "😢 Something went wrong while uploading your tokenURI.",
        }
    } 
    const tokenURI = pinataResponse.pinataUrl;  

    //load smart contract
    window.contract = await new web3.eth.Contract(contractABI, contractAddress);//loadContract();

    //set up your Ethereum transaction
    const transactionParameters = {
        to: contractAddress, // Required except during contract publications.
        from: window.ethereum.selectedAddress, // must match user's active address.
        'data': window.contract.methods.mintNFT(window.ethereum.selectedAddress, tokenURI).encodeABI() //make call to NFT smart contract 
    };
  
    //sign transaction via Metamask
    try {
        const txHash = await window.ethereum
            .request({
                method: 'eth_sendTransaction',
                params: [transactionParameters],
            });
        return {
            success: true,
            status: "✅ Check out your transaction on Etherscan: https://ropsten.etherscan.io/tx/" + txHash
        }
    } catch (error) {
        return {
            success: false,
            status: "😥 Something went wrong: " + error.message
        }
    }
}

In this example, we're signing a transaction to mint an NFT. You can check out more details here: https://docs.alchemyapi.io/alchemy/tutorials/nft-minter#step-8-implement-the-mintnft-function

Crisis answered 23/4, 2021 at 19:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.