user3441051
user3441051

Reputation: 43

How to sign an ethereum transaction with metamask

I am currently sending transactions with this code:

      const provider = ethers.getDefaultProvider("ropsten", {
        infura:
          "https://ropsten.infura.io/v3/ee11be9f1d1c43199618db4a7b22aa79",
      });

      const signer = new ethers.Wallet(PRIVATE_KEY);
      const account = signer.connect(provider);
      const uniswap = new ethers.Contract(
        ropstenUniswapContract,
        [
          "function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)",
        ],
        account
      );
      const gasCost = ethers.BigNumber.from((+gasPrice/10) * Math.pow(10, 9));
      console.log('Computed gas cost ->', gasCost);

      const tx = await uniswap.swapExactETHForTokens(
        amountOutMin,
        path,
        to,
        deadline,
        { value, gasPrice: gasCost }
      );

      // Transaction Hash and Block
      setTransactionHash(tx.hash);
      const receipt = await tx.wait();
      console.log(receipt);

My question is:

How can I make MetaMask sign the transaction on my behalf instead of supplying my private key?

Upvotes: 3

Views: 7360

Answers (2)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83636

Transaction signing is abstracted away with web3.js or Ethers.js. You can directly connect your Ethers.js to MetaMask provider (windows.ethereum) in in-page JavaScript code.

An example here.

Upvotes: 1

Petr Hejda
Petr Hejda

Reputation: 43571

Your (browser-facing) app can communicate with the MetaMask browser extension using the Ethereum Provider API.

Speficically the eth_sendTransaction method passing it the data field (specifying which function in your contract you want to execute, as well as the passed argument values), along with other params such as the sender address.

If you're new to MetaMask, just a quick note: To get the user's list of addresses, you need to call the eth_requestAccounts method.

Upvotes: 0

Related Questions