3

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?

user3441051
  • 43
  • 1
  • 3

2 Answers2

1

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.

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
0

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.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100