无法通过混音和元掩码向用户退款多余的以太币

时间:2019-01-21 15:12:07

标签: ethereum solidity metamask

构建众筹应用程序。一旦达到目标,对项目的任何以太捐款将通过msg.sender.transfer(excess)或msg.sender.send(excess)退还。

在Remix和Metamask(通过Web3部署)上进行了广泛的测试。关键问题是多余的资金将从发件人的帐户中全额扣除,而不会退还给发件人。

pragma solidity ^0.5.0;

contract Funds {
    uint public maximumValue = 100;
    uint public currentValue = 0;

    // addFunds function that takes in amount in ether
    function addFunds (uint _amount) public payable {
        // Converts wei (msg.value) to ether
        require(msg.value / 1000000000000000000 == _amount);
        // if the sum of currentValue and amount is greater than maximum value, refund the excess
        if (currentValue + _amount > maximumValue){
            uint excess = currentValue + _amount - maximumValue;
            currentValue = maximumValue;
            msg.sender.transfer(excess);
        } else {
            currentValue += _amount;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

看来您合同中的所有价值都是以太币,所以您可能想要msg.sender.transfer(excess * 1 ether)。我的猜测是退款正在奏效,但它会退还您未注意到的少量wei。

IMO,一个更好的解决方法是在任何地方使用wei:

pragma solidity ^0.5.0;

contract Funds {
    uint public maximumValue = 100 ether;
    uint public currentValue = 0;

    function addFunds() external payable {
        // if the sum of currentValue and amount is greater than maximum value, refund the excess
        if (currentValue + msg.value > maximumValue){
            uint excess = currentValue + msg.value - maximumValue;
            currentValue = maximumValue;
            msg.sender.transfer(excess);
        } else {
            currentValue += msg.value;
        }
    }
}