简体   繁体   中英

Web3: accessing private key in 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.

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.

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

Best of luck: :)

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.

it is possible to obtain private key from your 12 words passphrase, inserting the 12 words passphrase in the field "BIP39 Mnemonic" of site https://iancoleman.io/bip39/ you'll obtain every private and public key of all your accounts under the passphrase you inserted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM