Как рассчитать цену покупки и продажи токенов?

У меня есть токен ERC20

    string public name = "Token ZIZ";
    string public symbol = "ZIZ";
    uint8 public decimals = 18;
    uint256 public totalSupply = 1000000 * 10 ** uint256(decimals);

    /// the price of tokenBuy
    uint256 public TokenPerETHBuy = 10000;  /// 1 TOKEN = 0.001 ETH

    /// the price of tokenSell
    uint256 public TokenPerETHSell = 10000;

    /**
    *  function for Buy Token
    */

    function buy() payable public returns (uint amount){
          require(msg.value > 0);

          amount = ((msg.value.mul(TokenPerETHBuy))).div(1 ether);

          balanceOf[this] -= amount;                        // adds the amount to owner's 
          balanceOf[msg.sender] += amount; 
          emit BuyToken(msg.sender,msg.value,amount);
          return amount;
    }

    /**
    *  function for Sell Token
    */

    function sell(uint amount) public returns (uint revenue){

        require(balanceOf[msg.sender] >= amount);         // checks if the sender has enough to sell
        balanceOf[this] += amount;                        // adds the amount to owner's balance
        balanceOf[msg.sender] -= amount;                  // subtracts the amount from seller's balance

        revenue = (amount).div(TokenPerETHSell) ;

        msg.sender.transfer(revenue);                     // sends ether to the seller: it's important to do this last to prevent recursion attacks
        emit Transfer(msg.sender, this, amount);               // executes an event reflecting on the change
        return revenue;                                   // ends function and returns

    }

Как я могу добиться своего результата? 1 ТОКЕН = 0,001 ETH.

Ответы (1)

Из ваших комментариев TokenPerETHBuyвместо этого должно быть 1000, также TokenPerETHSellдолжно быть 1000.

В buyфункции сумма рассчитывается без учета токена decimals. Так должно быть:

amount = msg.value.mul(TokenPerETHBuy);

Потому что у вас есть decimals = 18. Для 1 ether = 10^18 weiтого, чтобы получить 1000 * 10^18жетоны.