¿Cómo calcular los precios de compra y venta de tokens?

Tengo un token 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

    }

¿Cómo puedo lograr mi resultado? 1 FICHA = 0.001 ETH.

Respuestas (1)

De sus comentarios TokenPerETHBuydebería ser 1000 en su lugar, también TokenPerETHSelldebería ser 1000.

En la buyfunción la cantidad se calcula sin tener en cuenta el token decimals. Debería ser:

amount = msg.value.mul(TokenPerETHBuy);

decimals = 18porque tienes Para 1 ether = 10^18 weique usted tiene que recibir 1000 * 10^18fichas.