0

I am deploying an erc-20 token with 18 decimal places. And I want that if someone calls the buy function with 1 ETH, the contract should return 1500 tokens to msg.sender. The buy function is implemented as:

function buy() public payable returns (uint){
       require(msg.sender != address(0));
       require(msg.value >= 0);
       uint amount = msg.value.div(buyPrice);
       require(balances[this] >= amount);
       uint oldBalance = balances[this].add(balances[msg.sender]);
       balances[this] = balances[this].sub(amount);
       balances[msg.sender] = balances[msg.sender].add(amount);
       uint newBalance = balances[this].add(balances[msg.sender]);
       assert(newBalance == oldBalance);
       Transfer(this, msg.sender, amount);
       return amount;   
  }

As per the implementation of this method, the buyPrice should be 1/1500. But since buyPrice is uint, I can not pass decimal values to this variable.

Is there any workaround? Do I need to change the standard buy function to suit my case?

1

When you say the buyPrice should be 1/1500, do you mean for every 1 eth the user should receive 1500 of the token? If that is the case then then the buyPrice should actually be 1500, and renamed to something like tokensToEth, and the amount assignment should be uint amount = msg.value.mul(tokensToEth);

0

Posting solution to m own question. As I thought I had to make changes in the standard buy function.

Change 1: The amount was multiplied by 1 ether i.e. 10^18, so the buy price in my case became 10^18/1500. Now buyPrice is being set in Wei.

Chnage2: First multiply msg.value with 1 ether and then divide by buyPrice. Don't reverse the order as dividing very small value first may result in zero value and then multiply will have no effect.

Change 3: Check if amount is greater than zero before proceeding by using require(amount > 0);

Final buy function became:

function buy() public payable returns (uint){
       require(msg.sender != address(0));
       require(msg.value >= 0);
       uint amount = msg.value.mul(1 ether).div(buyPrice);
       require(amount > 0);
       require(balances[this] >= amount);
       uint oldBalance = balances[this].add(balances[msg.sender]);
       balances[this] = balances[this].sub(amount);
       balances[msg.sender] = balances[msg.sender].add(amount);
       uint newBalance = balances[this].add(balances[msg.sender]);
       assert(newBalance == oldBalance);
       Transfer(this, msg.sender, amount);
       return amount;    
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.