【问题标题】:Sending ether to a payable function in Solidity doesn't decrease the sender's Ether in Ganache将以太币发送到 Solidity 中的支付功能不会减少发件人在 Ganache 中的以太币
【发布时间】:2021-12-22 02:52:31
【问题描述】:

我有以下智能合约:

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./MyCoinSupply.sol";

contract MyCoinDEX
{
    IERC20 public token;

    event Bought(uint256 amount);
    event Sold(uint256 amount);

    constructor() public
    {
        token = new MyCoinSupply();
    }

    function getSenderAddress() public view returns (address) // for debugging purposes
    {
        return (msg.sender);
    }

    function getAddress() public view returns (address)
    {
        return address(this);
    }

    function getTokenAddress() public view returns (address)
    {
        return address(token);
    }

    function buy() payable public // send ether and get tokens in exchange; 1 token == 1 ether
    {
      uint256 amountTobuy = msg.value;
      uint256 dexBalance = token.balanceOf(address(this));
      require(amountTobuy > 0, "You need to send some ether");
      require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
      token.transfer(msg.sender, amountTobuy);
      emit Bought(amountTobuy);
    }

    function sell(uint256 amount) public // send tokens to get ether back
    {
      require(amount > 0, "You need to sell at least some tokens");
      uint256 allowance = token.allowance(msg.sender, address(this));
      require(allowance >= amount, "Check the token allowance");
      token.transferFrom(msg.sender, address(this), amount);
      // https://stackoverflow.com/questions/67341914/error-send-and-transfer-are-only-available-for-objects-of-type-address-payable
      payable(msg.sender).transfer(amount);
      emit Sold(amount);
    }

}

如果我从truffle console 调用buy() 方法,它会毫无例外地执行:

truffle(development)> MyCoinDEX.buy({value: 1})

我验证调用buy() 方法的帐户收到了令牌。 但是,调用buy() 方法的帐户的Ganache 中的Ether 余额并没有减少。所以基本上,该帐户是免费获得代币的。

这是怎么回事?我该如何解决?

【问题讨论】:

    标签: ethereum solidity smartcontracts truffle ganache


    【解决方案1】:

    我不确定,但有必要调查合约账户的余额。 token.transfer 的 gas 可能由合约账户余额支付,因为合约账户是代币合约的交易发送方。

    否则余额减少会因为太小而无法察觉。

    如果你发现了,我很乐意知道答案。

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多