【问题标题】:Using Metamask but get Error: Returned error: The method eth_sendTransaction does not exist/is not available使用 Metamask 但得到错误:返回错误:方法 eth_sendTransaction 不存在/不可用
【发布时间】:2022-07-08 05:54:44
【问题描述】:

我想在我部署的智能合约中调用应付函数,但它不起作用。这是我得到的错误:

错误:返回错误:方法 eth_sendTransaction 不存在/不可用

我能找到的答案是只使用私钥,因为 infura 不支持这种方法,但是我希望用户使用 MetaMask 签署智能合约的交易。

这是我的代码:

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);
}

这是实际引发错误的代码:

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

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

我完全迷路了,因为如果我使用普通的window.ethereum.request (https://docs.metamask.io/guide/sending-transactions.html#example) 发送交易,元掩码会打开,我可以签名。使用合约调用它根本不起作用。

你知道原因吗?我该如何解决这个问题?

【问题讨论】:

  • 你连接到 infura 了吗?你如何连接到你的合约部署的区块链
  • @Yilmaz 是的,正如您在第一个代码示例开头看到的那样,我已连接到 infura

标签: javascript reactjs solidity web3js


【解决方案1】:

这一定是问题所在。你只是传递了一个网址:

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

改为:

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

eth_sendTransaction 要求您在将交易广播到网络之前持有私钥对交易进行签名。 Infura 不维护任何私钥。为了发送交易,您需要使用您的私钥签署交易。

您检查提供商的方式不正确。 window.ethereum 也是 metamask 提供的提供者。 provider本身没有意义,必须注入到new Web3()中。

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2019-08-04
    • 2021-10-01
    • 2020-09-30
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多