Using Metamask but get Error: Returned error: The method eth_sendTransaction does not exist/is not available

Viewed 782

I want to call a payable function in a smart contract I deployed, but it does not work. This is the error I am getting:

Error: Returned error: The method eth_sendTransaction does not exist/is not available

The answer I could find is to just use a private key, because infura does not cater this method, however I want the user to sign the transaction to the smart contract with MetaMask.

This is my code:

export async function helloworld() {
  const rpcURL =
    "https://ropsten.infura.io/v3/KEY";
  const web3 = new Web3(rpcURL);
  let provider = window.ethereum;

  if (typeof provider !== "undefined") {
    provider
      .request({ method: "eth_requestAccounts" })
      .then((accounts) => {
        selectedAccount = accounts[0];
        console.log(`Selected account is ${selectedAccount}`);
      })
      .catch((err) => {
        console.log(err);
        return;
      });

    window.ethereum.on("accountsChanged", function (accounts) {
      selectedAccount = accounts[0];
      console.log(`Selected account changed to ${selectedAccount}`);
    });
  }

  const networkId = await web3.eth.net.getId();

  const thecontract = new web3.eth.Contract(
    simpleContractAbi,
    "0x50A404efF9A057900f87ad0E0dEfA0D485931464"
  );
  isInitialized = true;

  investit(thecontract, selectedAccount);
}

and this is the code that actually throws the error:

export const investit = async (thecontract, selectedAccount) => {
  if (!isInitialized) {
    await helloworld();
  }

  thecontract.methods
    .invest()
    .send({ from: selectedAccount, value: 10000 })
    .catch(function (err) {
      console.log(err);
    });
};

I am completely lost, since if I use the normal window.ethereum.request (https://docs.metamask.io/guide/sending-transactions.html#example) to send a transaction, metamask opens up and I can sign it. With the contract call it simply does not work.

Do you know the reason? How can I fix this?

1 Answers

This must be the issue. you are just passing an url:

  const rpcURL ="https://ropsten.infura.io/v3/KEY";

instead:

const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/KEY"))

eth_sendTransaction requires you holding the private key to sign the transaction before broadcasting it to the network. Infura doesn’t maintain any private keys. In order to send a transaction, you need to sign the transaction on your end with your private key.

The way you check providers is not correct. window.ethereum is also a provider which is provided by metamask. provider itself is meaningless, it has to be injected into the new Web3().

Related