繁体   English   中英

如何调用 Solidity 函数从智能合约返回 Ether?

[英]How to call Solidity Function to return Ether from Smart Contract?

我已经在本地 truffle 项目上部署了一个智能合约,我正在尝试使用 web3 在 React 项目中与其交互。 以下 Solidity 函数应将先前存入合约的以太币发送到布尔条件下的用户地址:

 function Payout() public{

        require( voteEndTime< block.timestamp, "Voting Time is not up. Please come back later" );
        Voter storage sender = voters[msg.sender];

            if (negativeVotes > positiveVotes){
                require(!sender.option, "Wrong Vote. Stake is distributed among winners");
                payable(address(msg.sender)).transfer((stakes*sender.amount) / negativeStakes);
                }

            else if (positiveVotes > negativeVotes){
                require(sender.option, "Wrong Vote. Stake is distributed among winners");
                payable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);
            }

            else{
                payable(address(msg.sender)).transfer((stakes*sender.amount) / stakes);
            }
        }

合同绝对能够使用 msg.sender 读取用户地址,因为它已经在我拥有的其他功能中工作。 合约中的所有其他功能也工作正常。 我可以与它互动,我可以将以太币发送给它。 当我尝试将合约中存储的以太币返还给账户时,就会出现问题。 我正在尝试使用以下 web3 调用在 React on Button Click 中调用我的 Payout() 函数:

var response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })

我指定了更高的 gas 限制,因为如果我尝试使用下面看到的 gas 估计,合约会耗尽 gas。 此调用所在的函数如下所示:

 const giveMeMoney = async (e) => {
    const web3 = await new Web3(window.ethereum);
    await window.ethereum.enable();
    
    var Accounts = await web3.eth.getAccounts() 
        account = Accounts[0]
        console.log(account)

      const gas = await BallotContract.methods.Payout().estimateGas();
      console.log(gas)
      
      var response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })


  }

我可以从前端访问该函数,如果不满足“要求”条件,它会返回正确的字符串。 我的问题是,如果满足条件并且行

payable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);

被访问。 我收到以下错误:

Uncaught (in promise) Error: Returned error: VM Exception while processing transaction: revert
    at Object.ErrorResponse (errors.js:30)
    at onJsonrpcResult (index.js:162)
    at XMLHttpRequest.request.onreadystatechange (index.js:123)
ErrorResponse   @   errors.js:30

现在我不确定可能是什么问题,因为如果我在 Remix 中测试它,合同运行得非常好。 有人看到问题或有解决此类问题的方法吗?

gas错误是由传递函数引起的,传递函数的gas限制为2100,我建议你使用call,你可以在这里查看如何https://solidity-by-example.org/sending-ether / ,同样 Voter 结构的布尔值的默认值为 false,所以如果反对票获胜但用户没有投票,用户仍然可以尝试领取奖励(即使金额为 0 但他们可以尝试),所以我建议你检查如何使用枚举,可能非常有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM