使用 web3 ethereum 调用 withdraw 方法

Calling withdraw method with web3 ethereum

我正在使用 metamask 从 react.js 应用程序中以 solidity 编写的合约调用提款方法。交易失败,我不知道为什么。我认为这与汽油费有关,因为当我更改它时会出现不同的错误。这是反应代码:

     contract.methods
      .withdrawDividends()
      .send({
        from: userAddress,
        value: availableToWithdraw,
      })
      .on("transactionHash", function (hash: string) {
        console.log(hash);
      })
      .on(
        "confirmation",
        function (confirmationNumber: number, receipt: unknown) {
          console.log(confirmationNumber);
          console.log(receipt);
        }
      )
      .on("receipt", function (receipt: unknown) {
        // receipt example
        console.log(receipt);
      })
      .on("error", function (error: unknown, receipt: unknown) {
        // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
        console.log(error);
        console.log(receipt);
      });

这是我的稳固方法:

function withdrawDividends() public {
    User storage user = users[_msgSender()];

    uint256 totalAmount = getUserDividends(_msgSender());

    require(totalAmount > 0, "User has no dividends");

    user.checkpoint = block.timestamp;

    (bool success, ) = _msgSender().call.value(totalAmount)("");
    require(success, "Transfer failed.");

    emit Withdrawn(_msgSender(), totalAmount);

}

该方法没有崩溃,但我在 metamask 中看到以下错误:

我做错了什么?跟气有关系吗? 提前致谢

如果你想让你的函数接受 ETH 值,它需要有 payable 修饰符。

你的情况:

function withdrawDividends() public payable {

您可以在 docs 中阅读有关 payable 修饰符的更多信息。它链接到 receive 函数,这是一个稍微不同的主题。但它也涵盖了 payable 修饰符。